mirror of
https://github.com/frida/frida-core.git
synced 2026-11-09 01:59:34 -10:00
Compare commits
No files matched your search
@@ -0,0 +1 @@
|
||||
github: frida
|
||||
+268
-16
@@ -16,13 +16,13 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- { id: windows-x86_64, runner: '"windows-latest"' }
|
||||
- { id: windows-x86, runner: '"windows-latest"' }
|
||||
- { id: macos-x86_64, runner: '"macos-11"' }
|
||||
- { id: macos-arm64, runner: '"macos-latest"' }
|
||||
- { id: linux-x86_64, runner: '"ubuntu-latest"' }
|
||||
- { id: linux-x86, runner: '"ubuntu-latest"' }
|
||||
- { id: freebsd-arm64, runner: '["self-hosted", "freebsd", "arm64"]' }
|
||||
- { id: windows-arm64, runner: '"windows-11-arm"', sys: CLANGARM64, pkg: 'mingw-w64-clang-aarch64-clang' }
|
||||
- { id: windows-x86_64, runner: '"windows-latest"', sys: MINGW64, pkg: 'mingw-w64-x86_64-gcc' }
|
||||
- { id: windows-x86, runner: '"windows-latest"', sys: MINGW32, pkg: 'mingw-w64-i686-gcc' }
|
||||
- { id: macos-x86_64, runner: '"macos-latest"' }
|
||||
- { id: macos-arm64, runner: '"macos-latest"' }
|
||||
- { id: linux-x86_64, runner: '"ubuntu-latest"' }
|
||||
- { id: linux-x86, runner: '"ubuntu-latest"' }
|
||||
fail-fast: false
|
||||
runs-on: ${{ fromJSON(matrix.runner) }}
|
||||
steps:
|
||||
@@ -30,6 +30,18 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Install MinGW toolchain for cgo support
|
||||
if: ${{ startsWith(matrix.id, 'windows-') }}
|
||||
id: msys2
|
||||
uses: msys2/setup-msys2@v2
|
||||
with:
|
||||
msystem: ${{ matrix.sys }}
|
||||
install: ${{ matrix.pkg }}
|
||||
- name: Install Go toolchain
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: 'src/compiler/go.mod'
|
||||
cache-dependency-path: 'src/compiler/go.mod'
|
||||
- name: Set up Apple certificates
|
||||
if: ${{ startsWith(matrix.id, 'macos-') }}
|
||||
uses: ./.github/actions/setup-apple-certificates
|
||||
@@ -42,22 +54,35 @@ jobs:
|
||||
run: sudo security authorizationdb write system.privilege.taskport allow
|
||||
- name: Install gcc-multilib
|
||||
if: matrix.id == 'linux-x86'
|
||||
run: sudo apt-get install gcc-multilib lib32stdc++-11-dev
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install gcc-multilib lib32stdc++-13-dev
|
||||
- name: Build
|
||||
if: ${{ startsWith(matrix.id, 'windows-') }}
|
||||
run: |
|
||||
.\configure ${{ env.FRIDA_CORE_OPTIONS }}
|
||||
.\configure `
|
||||
--host=${{ matrix.id }} `
|
||||
--enable-compiler-backend `
|
||||
${{ env.FRIDA_CORE_OPTIONS }}
|
||||
.\make
|
||||
env:
|
||||
MSYS2_LOCATION: ${{ steps.msys2.outputs.msys2-location }}
|
||||
- name: Build
|
||||
if: ${{ !startsWith(matrix.id, 'windows-') && matrix.id != 'linux-x86' }}
|
||||
run: |
|
||||
./configure ${{ env.FRIDA_CORE_OPTIONS }}
|
||||
./configure \
|
||||
--enable-compiler-backend \
|
||||
${{ env.FRIDA_CORE_OPTIONS }}
|
||||
make
|
||||
- name: Build
|
||||
if: matrix.id == 'linux-x86'
|
||||
run: |
|
||||
CC="gcc -m32" CXX="g++ -m32" STRIP="strip" \
|
||||
./configure --build=linux-x86 --host=linux-x86 ${{ env.FRIDA_CORE_OPTIONS }}
|
||||
./configure \
|
||||
--build=linux-x86 \
|
||||
--host=linux-x86 \
|
||||
--enable-compiler-backend \
|
||||
${{ env.FRIDA_CORE_OPTIONS }}
|
||||
make
|
||||
- name: Upload devkit
|
||||
if: ${{ !startsWith(matrix.id, 'linux-') }}
|
||||
@@ -66,7 +91,7 @@ jobs:
|
||||
name: core-devkit-${{ matrix.id }}
|
||||
path: build/src/devkit/
|
||||
- name: Test
|
||||
if: matrix.id != 'macos-arm64'
|
||||
if: ${{ matrix.id != 'windows-arm64' && !startsWith(matrix.id, 'macos-') }}
|
||||
run: make test
|
||||
|
||||
cross:
|
||||
@@ -87,10 +112,20 @@ jobs:
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Install toolchain
|
||||
run: sudo apt-get install ${{ matrix.pkg }}
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install ${{ matrix.pkg }}
|
||||
- name: Install Go toolchain
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: 'src/compiler/go.mod'
|
||||
cache-dependency-path: 'src/compiler/go.mod'
|
||||
- name: Build
|
||||
run: |
|
||||
./configure ${{ matrix.opts }} ${{ env.FRIDA_CORE_OPTIONS }}
|
||||
./configure \
|
||||
${{ matrix.opts }} \
|
||||
${{ !contains(matrix.id, 'mips') && '--enable-compiler-backend' || '' }} \
|
||||
${{ env.FRIDA_CORE_OPTIONS }}
|
||||
make
|
||||
- name: Upload devkit
|
||||
if: ${{ !startsWith(matrix.id, 'linux-') }}
|
||||
@@ -111,9 +146,17 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Install Go toolchain
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: 'src/compiler/go.mod'
|
||||
cache-dependency-path: 'src/compiler/go.mod'
|
||||
- name: Build
|
||||
run: |
|
||||
./configure --host=$XTOOLS_HOST ${{ env.FRIDA_CORE_OPTIONS }}
|
||||
./configure \
|
||||
--host=$XTOOLS_HOST \
|
||||
${{ !startsWith(matrix.arch, 'mips') && '--enable-compiler-backend' || '' }} \
|
||||
${{ env.FRIDA_CORE_OPTIONS }}
|
||||
make
|
||||
- name: Upload devkit
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -124,6 +167,131 @@ jobs:
|
||||
if: matrix.arch == 'x86' || matrix.arch == 'x86_64'
|
||||
run: make test
|
||||
|
||||
emulator:
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [armbe8, arm64be]
|
||||
fail-fast: false
|
||||
runs-on: ubuntu-latest
|
||||
container: ghcr.io/frida/x-tools-linux-${{ matrix.arch }}:latest
|
||||
steps:
|
||||
- name: Check out repo
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Build
|
||||
run: |
|
||||
./configure --host=$XTOOLS_HOST --without-prebuilds=sdk:host --enable-tests
|
||||
make
|
||||
- name: Run custom container
|
||||
uses: addnab/docker-run-action@v3
|
||||
with:
|
||||
image: docker:stable
|
||||
options: -v ${{ github.workspace }}:/workspace:delegated
|
||||
run: |
|
||||
cat <<EOF > /workspace/initscript
|
||||
#!/bin/sh
|
||||
dmesg -n1
|
||||
mount -t proc none /proc
|
||||
mount -t sysfs none /sys
|
||||
mount -t tmpfs none /tmp
|
||||
mount -t devtmpfs none /dev
|
||||
mount -t 9p -o rw,sync,dirsync,relatime,trans=virtio,msize=131072,version=9p2000.L host0 /workspace
|
||||
ip link set lo up
|
||||
ip addr add 192.168.76.20/24 dev eth0
|
||||
ip link set eth0 up
|
||||
ip route add default via 192.168.76.2 dev eth0
|
||||
export LD_LIBRARY_PATH=/lib:/lib64:/libilp32
|
||||
/sbin/entropy
|
||||
cat /etc/motd
|
||||
export PS1='\u@frida:\w\$ '
|
||||
/root/frida-tests
|
||||
status=\$?
|
||||
echo "exit status: \$status"
|
||||
if [ \$status -eq 0 ]; then
|
||||
echo EXIT_OK
|
||||
elif [ \$status -gt 128 ]; then
|
||||
signal=\$((\$status - 128))
|
||||
echo "EXIT_FAIL (terminated by signal \$signal)"
|
||||
else
|
||||
echo "EXIT_FAIL (exit code \$status)"
|
||||
fi
|
||||
EOF
|
||||
|
||||
cat <<EOF > /workspace/launch.sh
|
||||
#!/bin/sh
|
||||
LOGFILE=/workspace/qemu.log
|
||||
: > "\$LOGFILE"
|
||||
timeout 120 qemu-system-aarch64 \
|
||||
-M virt \
|
||||
-machine virtualization=true \
|
||||
-machine type=virt \
|
||||
-cpu cortex-a72 \
|
||||
-smp 4 \
|
||||
-kernel /root/Image.gz \
|
||||
-initrd /root/initramfs.img \
|
||||
-append 'earlyprintk=serial,ttyAMA0 console=ttyAMA0 coredump_filter=0x3f' \
|
||||
-m 4096M \
|
||||
-net nic,id=eth \
|
||||
-net user,id=mynet,net=192.168.76.0/24 \
|
||||
-virtfs local,path=/workspace/,mount_tag=host0,security_model=passthrough,id=host0 \
|
||||
-nographic \
|
||||
-no-reboot \
|
||||
>> "\$LOGFILE" 2>&1 &
|
||||
QEMU_PID=\$!
|
||||
echo "QEMU started with PID \$QEMU_PID"
|
||||
tail -n 0 -f "\$LOGFILE" | while read line; do
|
||||
echo "\$line"
|
||||
echo "\$line" | grep "EXIT_OK" >/dev/null 2>&1
|
||||
if [ \$? -eq 0 ]; then
|
||||
echo "Success signal received from guest. Killing QEMU..."
|
||||
kill -9 "\$QEMU_PID"
|
||||
cat -n "\$LOGFILE"
|
||||
exit 0
|
||||
fi
|
||||
echo "\$line" | grep "EXIT_FAIL" >/dev/null 2>&1
|
||||
if [ \$? -eq 0 ]; then
|
||||
echo "Failure signal received from guest. Killing QEMU..."
|
||||
kill -9 "\$QEMU_PID"
|
||||
cat -n "\$LOGFILE"
|
||||
exit 1
|
||||
fi
|
||||
if ! kill -0 "\$QEMU_PID" 2>/dev/null; then
|
||||
echo "QEMU process has exited."
|
||||
cat -n "\$LOGFILE"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
EOF
|
||||
|
||||
cat <<EOF > /workspace/Dockerfile.ci
|
||||
FROM ghcr.io/frida/x-tools-linux-be-target:latest
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
RUN apt-get update && \
|
||||
apt-get install -y \
|
||||
cpio
|
||||
|
||||
RUN mkdir /tmp/initramfs
|
||||
WORKDIR /tmp/initramfs
|
||||
RUN cpio --extract < /root/initramfs.img
|
||||
|
||||
RUN mkdir /tmp/initramfs/workspace
|
||||
|
||||
COPY initscript /tmp/initramfs/init
|
||||
RUN chmod +x /tmp/initramfs/init
|
||||
|
||||
COPY build/tests /tmp/initramfs/root/
|
||||
RUN find . | cpio -o --format=newc -R root:root > /root/initramfs.img
|
||||
|
||||
COPY launch.sh /root/launch.sh
|
||||
RUN chmod +x /root/launch.sh
|
||||
ENTRYPOINT ["/root/launch.sh"]
|
||||
EOF
|
||||
|
||||
docker build -t ci-image -f /workspace/Dockerfile.ci /workspace
|
||||
docker run --rm -v /workspace:/workspace ci-image
|
||||
|
||||
mobile:
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -140,6 +308,11 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Install Go toolchain
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: 'src/compiler/go.mod'
|
||||
cache-dependency-path: 'src/compiler/go.mod'
|
||||
- name: Set up Apple certificates
|
||||
if: startsWith(matrix.id, 'ios-')
|
||||
uses: ./.github/actions/setup-apple-certificates
|
||||
@@ -147,9 +320,20 @@ jobs:
|
||||
certificates-p12: ${{ secrets.APPLE_CERTIFICATES_P12 }}
|
||||
certificates-password: ${{ secrets.APPLE_CERTIFICATES_PASSWORD }}
|
||||
keychain-password: ${{ secrets.APPLE_KEYCHAIN_PASSWORD }}
|
||||
- uses: nttld/setup-ndk@v1
|
||||
if: startsWith(matrix.id, 'android-')
|
||||
id: setup-ndk
|
||||
with:
|
||||
ndk-version: r25c
|
||||
- name: Add NDK to env
|
||||
if: startsWith(matrix.id, 'android-')
|
||||
run: echo ANDROID_NDK_ROOT=${{ steps.setup-ndk.outputs.ndk-path }} >> $GITHUB_ENV
|
||||
- name: Build
|
||||
run: |
|
||||
./configure --host=${{ matrix.id }} ${{ env.FRIDA_CORE_OPTIONS }}
|
||||
./configure \
|
||||
--host=${{ matrix.id }} \
|
||||
--enable-compiler-backend \
|
||||
${{ env.FRIDA_CORE_OPTIONS }}
|
||||
make
|
||||
- name: Upload devkit
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -177,6 +361,7 @@ jobs:
|
||||
tar -C /tmp/pkg -czf /tmp/runner.tar.gz .
|
||||
- name: Test on Corellium iOS device
|
||||
if: matrix.id == 'ios-arm64'
|
||||
continue-on-error: true
|
||||
uses: frida/corellium-action@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -192,6 +377,7 @@ jobs:
|
||||
./frida-tests
|
||||
- name: Test on Corellium Android device
|
||||
if: matrix.id == 'android-arm64'
|
||||
continue-on-error: true
|
||||
uses: frida/corellium-action@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -228,3 +414,69 @@ jobs:
|
||||
cp -a tests/frida-tests tests/labrats lib/agent/frida-agent.so /tmp/pkg/
|
||||
tar -C /tmp/pkg -cf /tmp/runner.tar .
|
||||
/opt/sabrelite/run.sh /tmp/runner.tar /opt/frida/frida-tests
|
||||
|
||||
# This job is used to check that the Linux helpers are built correctly for all
|
||||
# supported architectures. We do this because the binary artifacts are checked
|
||||
# in, and we want to ensure that they are up-to-date with respect to the source
|
||||
# for all architectures.
|
||||
check-linux-helpers:
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [x86, x86_64, arm, armbe8, arm64, arm64be, arm64beilp32, mips, mipsel, mips64, mips64el]
|
||||
fail-fast: false
|
||||
runs-on: ubuntu-latest
|
||||
container: ghcr.io/frida/core-linux-helpers-${{ matrix.arch }}:latest
|
||||
steps:
|
||||
- name: Check out repo
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Build
|
||||
run: |
|
||||
./src/linux/helpers/rebuild.sh ${{ matrix.arch }}
|
||||
- name: Check for unexpected changes
|
||||
run: |
|
||||
git config --global --add safe.directory "$(realpath .)"
|
||||
status_output=$(git status --porcelain tests/labrats/{resident-agent,simple-agent}-linux-${{ matrix.arch }}.so tests/labrats/{forker,sleeper,spawner}-linux-${{ matrix.arch }})
|
||||
if [ -n "$status_output" ]; then
|
||||
echo "Unexpected changes detected:"
|
||||
echo "$status_output"
|
||||
echo "Diff:"
|
||||
git diff
|
||||
exit 1
|
||||
else
|
||||
echo "No unexpected changes detected."
|
||||
fi
|
||||
|
||||
# This job is used to check that the Linux labrats are built correctly for all
|
||||
# supported architectures. We do this because the binary artifacts are checked
|
||||
# in, and we want to ensure that they are up-to-date with respect to the source
|
||||
# for all architectures.
|
||||
check-labrats:
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [x86, x86_64, arm, armbe8, arm64, arm64be, arm64beilp32, mips, mipsel, mips64, mips64el]
|
||||
fail-fast: false
|
||||
runs-on: ubuntu-latest
|
||||
container: ghcr.io/frida/core-linux-helpers-${{ matrix.arch }}:latest
|
||||
steps:
|
||||
- name: Check out repo
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Build
|
||||
run: |
|
||||
./tests/labrats/rebuild.sh ${{ matrix.arch }}
|
||||
- name: Check for unexpected changes
|
||||
run: |
|
||||
git config --global --add safe.directory "$(realpath .)"
|
||||
status_output=$(git status --porcelain src/linux/helpers/{bootstrapper,loader}-${{ matrix.arch }}.bin)
|
||||
if [ -n "$status_output" ]; then
|
||||
echo "Unexpected changes detected:"
|
||||
echo "$status_output"
|
||||
echo "Diff:"
|
||||
git diff
|
||||
exit 1
|
||||
else
|
||||
echo "No unexpected changes detected."
|
||||
fi
|
||||
@@ -1,11 +1,20 @@
|
||||
/build/
|
||||
/deps/
|
||||
/src/barebone/agent/target/
|
||||
/src/barebone/agent/xpacks/
|
||||
/src/barebone/helpers/memory-scanner/target/
|
||||
/src/barebone/helpers/target/
|
||||
/src/barebone/node_modules/
|
||||
/src/barebone/script-runtime.js
|
||||
/src/compiler/node_modules/
|
||||
/src/darwin/agent/osanalytics/node_modules/
|
||||
/src/darwin/agent/osanalytics/osanalytics.js
|
||||
/src/darwin/agent/reportcrash/node_modules/
|
||||
/src/darwin/agent/reportcrash/reportcrash.js
|
||||
/src/droidy/helper/build/
|
||||
/src/fruity/helpers/build/
|
||||
/src/linux/agent/system-server/node_modules/
|
||||
/src/linux/agent/system-server/system-server.js
|
||||
/src/linux/helpers/build/
|
||||
/src/linux/helpers/ext/
|
||||
/subprojects/*
|
||||
+62
-12
@@ -4,6 +4,7 @@ import base64
|
||||
from collections import OrderedDict
|
||||
from dataclasses import dataclass, field
|
||||
import itertools
|
||||
import locale
|
||||
import os
|
||||
from pathlib import Path
|
||||
import pickle
|
||||
@@ -14,7 +15,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
from typing import Any, Literal, Mapping, Optional, Sequence
|
||||
from typing import Any, Literal, Mapping, Optional, Sequence, Tuple
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
@@ -140,16 +141,19 @@ def setup(role: Role,
|
||||
compat = set()
|
||||
else:
|
||||
summary = "enabled by user"
|
||||
missing: list[MissingFeature] = []
|
||||
|
||||
if "native" in compat:
|
||||
have_toolchain = True
|
||||
other_label: Optional[str] = None
|
||||
other_triplet: Optional[str] = None
|
||||
extra_environ: dict[str, str] = {}
|
||||
|
||||
if host_os == "windows" and host_arch == "x86_64" and host_config == "mingw":
|
||||
other_triplet = "i686-w64-mingw32"
|
||||
have_toolchain = shutil.which(other_triplet + "-gcc") is not None
|
||||
other_label = "x86"
|
||||
have_toolchain, other_triplet = detect_mingw_toolchain_for("x86")
|
||||
elif host_os == "linux" and host_arch == "x86_64" and host_config is None:
|
||||
other_label = "x86"
|
||||
other_triplet = "i686-linux-gnu"
|
||||
have_toolchain = shutil.which(other_triplet + "-gcc") is not None
|
||||
if not have_toolchain:
|
||||
@@ -173,7 +177,7 @@ def setup(role: Role,
|
||||
if not have_toolchain:
|
||||
if not auto_detect:
|
||||
raise ToolchainNotFoundError(f"unable to locate toolchain for {other_triplet}")
|
||||
summary = "disabled due to missing toolchain for {other_triplet}"
|
||||
missing.append(MissingFeature(other_label, other_triplet))
|
||||
|
||||
if host_os == "windows" and host_arch == "x86_64" and have_toolchain:
|
||||
group = OutputGroup("x86", other_triplet, extra_environ)
|
||||
@@ -269,6 +273,28 @@ def setup(role: Role,
|
||||
]
|
||||
|
||||
if "emulated" in compat:
|
||||
if host_os == "windows" and host_arch == "arm64":
|
||||
for kind, emulated_arch in [("modern", "x86_64"), ("legacy", "x86")]:
|
||||
if host_config == "mingw":
|
||||
found, emulated_triplet = detect_mingw_toolchain_for(emulated_arch)
|
||||
if not found:
|
||||
if not auto_detect:
|
||||
raise ToolchainNotFoundError(f"unable to locate toolchain for {emulated_triplet}")
|
||||
missing.append(MissingFeature(emulated_arch, emulated_triplet))
|
||||
continue
|
||||
else:
|
||||
emulated_triplet = None
|
||||
outputs[OutputGroup(emulated_arch, emulated_triplet, extra_environ)] = [
|
||||
Output(identifier=f"helper_emulated_{kind}",
|
||||
name=HELPER_FILE_WINDOWS.name.replace(".exe", f"-{emulated_arch}.exe"),
|
||||
file=HELPER_FILE_WINDOWS,
|
||||
target=HELPER_TARGET),
|
||||
Output(identifier=f"agent_emulated_{kind}",
|
||||
name=AGENT_FILE_WINDOWS.name.replace(".dll", f"-{emulated_arch}.dll"),
|
||||
file=AGENT_FILE_WINDOWS,
|
||||
target=AGENT_TARGET),
|
||||
]
|
||||
|
||||
if host_os == "android" and host_arch in {"x86_64", "x86"}:
|
||||
outputs[OutputGroup("arm")] = [
|
||||
Output(identifier="agent_emulated_legacy",
|
||||
@@ -290,6 +316,8 @@ def setup(role: Role,
|
||||
state = State(role, builddir, top_builddir, frida_version, host_os, host_config, allowed_prebuilds, outputs)
|
||||
serialized_state = base64.b64encode(pickle.dumps(state)).decode('ascii')
|
||||
|
||||
if missing:
|
||||
summary = ", ".join([f"{m.label} disabled due to missing toolchain for {m.triplet}" for m in missing])
|
||||
variable_names, output_names = zip(*[(output.identifier, output.name) \
|
||||
for output in itertools.chain.from_iterable(outputs.values())])
|
||||
print("ok")
|
||||
@@ -349,6 +377,12 @@ class Output:
|
||||
target: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class MissingFeature:
|
||||
label: str
|
||||
triplet: str
|
||||
|
||||
|
||||
def compile(privdir: Path, state: State):
|
||||
releng_location = query_releng_location(state.role)
|
||||
subprojects = detect_relevant_subprojects(releng_location)
|
||||
@@ -367,7 +401,7 @@ def compile(privdir: Path, state: State):
|
||||
**kwargs,
|
||||
"stdout": subprocess.PIPE,
|
||||
"stderr": subprocess.STDOUT,
|
||||
"encoding": "utf-8",
|
||||
"encoding": locale.getpreferredencoding(),
|
||||
}
|
||||
else:
|
||||
silenced_kwargs = kwargs
|
||||
@@ -401,6 +435,7 @@ def compile(privdir: Path, state: State):
|
||||
environ={**build_env, **group.extra_environ},
|
||||
allowed_prebuilds=state.allowed_prebuilds,
|
||||
extra_meson_options=[
|
||||
"-Dcompiler_backend=disabled",
|
||||
"-Dhelper_modern=",
|
||||
"-Dhelper_legacy=",
|
||||
"-Dagent_modern=",
|
||||
@@ -432,7 +467,7 @@ def compile(privdir: Path, state: State):
|
||||
path = Path(raw_path)
|
||||
if not path.is_absolute():
|
||||
path = Path(os.path.relpath(workdir / path, top_builddir))
|
||||
input_entries.append(quote(path.as_posix()))
|
||||
input_entries.append(escape_depfile_path(path.as_posix()))
|
||||
depfile_lines.append(f"{output_relpath}: {' '.join(input_entries)}")
|
||||
|
||||
(state.builddir / DEPFILE_FILENAME).write_text("\n".join(depfile_lines), encoding="utf-8")
|
||||
@@ -465,6 +500,8 @@ def option_should_be_forwarded(k: "OptionKey",
|
||||
|
||||
if k.is_project():
|
||||
if is_for_us:
|
||||
if k.name == "compiler_backend":
|
||||
return False
|
||||
tokens = k.name.split("_")
|
||||
if tokens[0] in {"helper", "agent"} and tokens[-1] in {"modern", "legacy"}:
|
||||
return False
|
||||
@@ -480,6 +517,10 @@ def option_should_be_forwarded(k: "OptionKey",
|
||||
return False
|
||||
if not str(v.value):
|
||||
return False
|
||||
if not is_for_child and role == "subproject" and k.subproject in {"", our_project_id}:
|
||||
if not coredata.BUILTIN_OPTIONS[k.as_root()].yielding:
|
||||
return k.subproject == our_project_id
|
||||
return True
|
||||
|
||||
if k.module == "python":
|
||||
if k.name == "install_env" and v.value == "prefix":
|
||||
@@ -519,10 +560,8 @@ def scrub_windows_devenv_dirs_from_path(raw_path: str, env: Mapping[str, str]) -
|
||||
return ";".join(clean_entries)
|
||||
|
||||
|
||||
def quote(path: str) -> str:
|
||||
if " " not in path:
|
||||
return path
|
||||
return "\"" + path.replace ("\"", "\\\"") + "\""
|
||||
def escape_depfile_path(path: str) -> str:
|
||||
return path.replace(" ", "\\ ")
|
||||
|
||||
|
||||
def query_releng_location(role: Role) -> Path:
|
||||
@@ -568,10 +607,10 @@ def grab_subprojects_from_parent(subprojects: dict[str, Path], releng_location:
|
||||
continue
|
||||
|
||||
try:
|
||||
subp_here.symlink_to(location, target_is_directory=True)
|
||||
subp_here.symlink_to(Path("..") / ".." / name, target_is_directory=True)
|
||||
continue
|
||||
except OSError as e:
|
||||
if not getattr(e, "winerror") == 1314:
|
||||
if not getattr(e, "winerror", None) == 1314:
|
||||
raise e
|
||||
|
||||
subprocess.run(["git", "worktree", "add", subp_here],
|
||||
@@ -587,6 +626,12 @@ def configure_import_path(releng_location: Path):
|
||||
sys.path.insert(0, str(releng_location.parent))
|
||||
|
||||
|
||||
def detect_mingw_toolchain_for(arch: str) -> Tuple[bool, Optional[str]]:
|
||||
triplet = MINGW_ARCHS.get(arch, arch) + "-w64-mingw32"
|
||||
found = shutil.which(triplet + "-gcc") is not None
|
||||
return (found, triplet)
|
||||
|
||||
|
||||
STATE_FILENAME = "state.dat"
|
||||
DEPFILE_FILENAME = "compat.deps"
|
||||
|
||||
@@ -614,6 +659,11 @@ MSVS_ENVVARS = {
|
||||
"LIB",
|
||||
}
|
||||
|
||||
MINGW_ARCHS = {
|
||||
"x86": "i686",
|
||||
"arm64": "aarch64",
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
@@ -1,6 +1,8 @@
|
||||
helper_modern = get_option('helper_modern')
|
||||
helper_legacy = get_option('helper_legacy')
|
||||
helper_compat = ''
|
||||
helper_emulated_modern = get_option('helper_emulated_modern')
|
||||
helper_emulated_legacy = get_option('helper_emulated_legacy')
|
||||
helper_depends = []
|
||||
|
||||
agent_modern = get_option('agent_modern')
|
||||
@@ -18,6 +20,7 @@ server_depends = []
|
||||
|
||||
no_overridden_compat_bits = \
|
||||
helper_modern == 'auto' and helper_legacy == 'auto' \
|
||||
and helper_emulated_modern == 'auto' and helper_emulated_legacy == 'auto' \
|
||||
and agent_modern == 'auto' and agent_legacy == 'auto' \
|
||||
and agent_emulated_modern == 'auto' and agent_emulated_legacy == 'auto'
|
||||
|
||||
|
||||
+63
-34
@@ -147,7 +147,7 @@ namespace Frida.Inject {
|
||||
public extern void init ();
|
||||
}
|
||||
|
||||
public class Application : Object {
|
||||
public sealed class Application : Object {
|
||||
public string? device_id {
|
||||
get;
|
||||
construct;
|
||||
@@ -388,7 +388,7 @@ namespace Frida.Inject {
|
||||
return false;
|
||||
}
|
||||
|
||||
script_runner.on_stdin (line);
|
||||
script_runner.on_stdin (line, null);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -414,14 +414,19 @@ namespace Frida.Inject {
|
||||
|
||||
buf[n] = 0;
|
||||
|
||||
script_runner.on_stdin ((string) buf);
|
||||
if (script_runner.terminal_mode == TerminalMode.BINARY) {
|
||||
var bytes = new Bytes (buf[:n]);
|
||||
script_runner.on_stdin ("", bytes);
|
||||
} else {
|
||||
script_runner.on_stdin ((string) buf, null);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private class ScriptRunner : Object, RpcPeer {
|
||||
private sealed class ScriptRunner : Object, RpcPeer {
|
||||
public TerminalMode terminal_mode {
|
||||
get;
|
||||
private set;
|
||||
@@ -549,7 +554,7 @@ namespace Frida.Inject {
|
||||
var stage = new Json.Node.alloc ().init_string ("early");
|
||||
|
||||
try {
|
||||
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, io_cancellable);
|
||||
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, null, io_cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
}
|
||||
}
|
||||
@@ -591,7 +596,7 @@ namespace Frida.Inject {
|
||||
private async TerminalMode query_terminal_mode () {
|
||||
Json.Node mode_value;
|
||||
try {
|
||||
mode_value = yield rpc_client.call ("getFridaTerminalMode", new Json.Node[] {}, io_cancellable);
|
||||
mode_value = yield rpc_client.call ("getFridaTerminalMode", new Json.Node[] {}, null, io_cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
return COOKED;
|
||||
}
|
||||
@@ -599,7 +604,14 @@ namespace Frida.Inject {
|
||||
if (mode_value.get_value_type () != typeof (string))
|
||||
return COOKED;
|
||||
|
||||
return (mode_value.get_string () == "raw") ? TerminalMode.RAW : TerminalMode.COOKED;
|
||||
switch (mode_value.get_string ()) {
|
||||
case "raw":
|
||||
return TerminalMode.RAW;
|
||||
case "binary":
|
||||
return TerminalMode.BINARY;
|
||||
default:
|
||||
return TerminalMode.COOKED;
|
||||
}
|
||||
}
|
||||
|
||||
private void apply_terminal_mode (TerminalMode mode) throws Error {
|
||||
@@ -632,10 +644,10 @@ namespace Frida.Inject {
|
||||
}
|
||||
#endif
|
||||
|
||||
public void on_stdin (string data) {
|
||||
var data_value = new Json.Node.alloc ().init_string (data);
|
||||
public void on_stdin (string str, Bytes? data) {
|
||||
var str_value = new Json.Node.alloc ().init_string (str);
|
||||
|
||||
rpc_client.call.begin ("onFridaStdin", new Json.Node[] { data_value }, io_cancellable);
|
||||
rpc_client.call.begin ("onFridaStdin", new Json.Node[] { str_value }, data, io_cancellable);
|
||||
}
|
||||
|
||||
private void on_script_file_changed (File file, File? other_file, FileMonitorEvent event_type) {
|
||||
@@ -675,7 +687,7 @@ namespace Frida.Inject {
|
||||
handled = try_handle_log_message (message);
|
||||
break;
|
||||
case "send":
|
||||
handled = try_handle_stdout_message (message);
|
||||
handled = try_handle_stdout_message (message, data);
|
||||
break;
|
||||
default:
|
||||
handled = false;
|
||||
@@ -722,20 +734,19 @@ namespace Frida.Inject {
|
||||
*
|
||||
* {"type":"send","payload":["frida:stdout","DATA"]}
|
||||
*/
|
||||
private bool try_handle_stdout_message (Json.Object message) {
|
||||
private bool try_handle_stdout_message (Json.Object message, Bytes? data) {
|
||||
var payload = message.get_member ("payload");
|
||||
if (payload.get_node_type () != Json.NodeType.ARRAY)
|
||||
return false;
|
||||
|
||||
var tuple = payload.get_array ();
|
||||
if (tuple.get_length () != 2)
|
||||
var tuple_len = tuple.get_length ();
|
||||
if (tuple_len == 0)
|
||||
return false;
|
||||
|
||||
var first_element = tuple.get_element (0);
|
||||
if (first_element.get_value_type () != typeof (string))
|
||||
var type = tuple.get_element (0).get_string ();
|
||||
if (type == null)
|
||||
return false;
|
||||
|
||||
var type = first_element.get_string ();
|
||||
switch (type) {
|
||||
case "frida:stdout":
|
||||
case "frida:stderr":
|
||||
@@ -744,31 +755,49 @@ namespace Frida.Inject {
|
||||
return false;
|
||||
}
|
||||
|
||||
var second_element = tuple.get_element (1);
|
||||
if (second_element.get_value_type () != typeof (string))
|
||||
return false;
|
||||
var str = second_element.get_string ();
|
||||
|
||||
switch (type) {
|
||||
case "frida:stdout":
|
||||
stdout.write (str.data);
|
||||
stdout.flush ();
|
||||
return true;
|
||||
case "frida:stderr":
|
||||
stderr.write (str.data);
|
||||
return true;
|
||||
default:
|
||||
if (tuple_len >= 2) {
|
||||
var str = tuple.get_element (1).get_string ();
|
||||
if (str == null)
|
||||
return false;
|
||||
|
||||
switch (type) {
|
||||
case "frida:stdout":
|
||||
stdout.write (str.data);
|
||||
stdout.flush ();
|
||||
break;
|
||||
case "frida:stderr":
|
||||
stderr.write (str.data);
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (data != null) {
|
||||
switch (type) {
|
||||
case "frida:stdout":
|
||||
stdout.write (data.get_data ());
|
||||
stdout.flush ();
|
||||
break;
|
||||
case "frida:stderr":
|
||||
stderr.write (data.get_data ());
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
|
||||
script.post (json, null);
|
||||
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
|
||||
script.post (json, data);
|
||||
}
|
||||
}
|
||||
|
||||
private enum TerminalMode {
|
||||
COOKED,
|
||||
RAW
|
||||
RAW,
|
||||
BINARY
|
||||
}
|
||||
}
|
||||
+22
-23
@@ -11,7 +11,7 @@ namespace Frida.Agent {
|
||||
PROCESS_TRANSITION
|
||||
}
|
||||
|
||||
private class Runner : Object, ProcessInvader, AgentSessionProvider, ExitHandler, ForkHandler, SpawnHandler {
|
||||
private sealed class Runner : Object, ProcessInvader, AgentSessionProvider, ExitHandler, ForkHandler, SpawnHandler {
|
||||
public static Runner shared_instance = null;
|
||||
public static Mutex shared_mutex;
|
||||
private static string? cached_agent_path = null;
|
||||
@@ -1400,12 +1400,12 @@ namespace Frida.Agent {
|
||||
if (nb_api.unload_library == null)
|
||||
parameters.append ("|eternal|sticky");
|
||||
/*
|
||||
* Disable ExitMonitor to work around a bug in Android's libndk_translation.so on Android 11.
|
||||
* We need to avoid modifying libc.so ranges that the translator potentially depends on, to
|
||||
* avoid blowing up when Interceptor's CPU cache flush results in the translated code being
|
||||
* discarded, which seems like an edge-case the translator doesn't handle.
|
||||
* Disable Exceptor and ExitMonitor to work around a bug in Android's libndk_translation.so
|
||||
* on Android 11. We need to avoid modifying libc.so ranges that the translator potentially
|
||||
* depends on, to avoid blowing up when Interceptor's CPU cache flush results in the translated
|
||||
* code being discarded, which seems like an edge-case the translator doesn't handle.
|
||||
*/
|
||||
parameters.append ("|exit-monitor:off");
|
||||
parameters.append ("|exceptor:off|exit-monitor:off");
|
||||
|
||||
emulated_bridge_state = new BridgeState (parameters.str);
|
||||
|
||||
@@ -1509,13 +1509,14 @@ namespace Frida.Agent {
|
||||
}
|
||||
|
||||
public static NativeBridgeApi open () throws Error {
|
||||
string? nb_mod = null;
|
||||
string? vm_mod = null;
|
||||
Gum.Process.enumerate_modules ((details) => {
|
||||
if (/\/lib(64)?\/libnativebridge.so$/.match (details.path))
|
||||
nb_mod = details.path;
|
||||
else if (/^lib(art|dvm).so$/.match (details.name) && !/\/system\/fake-libs/.match (details.path))
|
||||
vm_mod = details.path;
|
||||
Gum.Module? nb_mod = null;
|
||||
Gum.Module? vm_mod = null;
|
||||
Gum.Process.enumerate_modules (module => {
|
||||
unowned string path = module.path;
|
||||
if (/\/lib(64)?\/libnativebridge.so$/.match (path))
|
||||
nb_mod = module;
|
||||
else if (/^lib(art|dvm).so$/.match (module.name) && !/\/system\/fake-libs/.match (path))
|
||||
vm_mod = module;
|
||||
bool carry_on = nb_mod == null || vm_mod == null;
|
||||
return carry_on;
|
||||
});
|
||||
@@ -1530,29 +1531,27 @@ namespace Frida.Agent {
|
||||
NBUnloadLibraryFunc? unload;
|
||||
NBGetTrampolineFunc get_trampoline;
|
||||
|
||||
load = (NBLoadLibraryFunc) Gum.Module.find_export_by_name (nb_mod, "NativeBridgeLoadLibrary");;
|
||||
load = (NBLoadLibraryFunc) nb_mod.find_export_by_name ("NativeBridgeLoadLibrary");;
|
||||
if (load != null) {
|
||||
flavor = MODERN;
|
||||
load_ext = (NBLoadLibraryExtFunc) Gum.Module.find_export_by_name (nb_mod, "NativeBridgeLoadLibraryExt");
|
||||
load_ext = (NBLoadLibraryExtFunc) nb_mod.find_export_by_name ("NativeBridgeLoadLibraryExt");
|
||||
// XXX: NativeBridgeUnloadLibrary() is only a stub as of Android 11 w/ libndk_translation.so
|
||||
unload = null;
|
||||
get_trampoline = (NBGetTrampolineFunc) Gum.Module.find_export_by_name (nb_mod,
|
||||
"NativeBridgeGetTrampoline");
|
||||
get_trampoline = (NBGetTrampolineFunc) nb_mod.find_export_by_name ("NativeBridgeGetTrampoline");
|
||||
} else {
|
||||
flavor = LEGACY;
|
||||
load = (NBLoadLibraryFunc) Gum.Module.find_export_by_name (nb_mod,
|
||||
"_ZN7android23NativeBridgeLoadLibraryEPKci");
|
||||
load_ext = (NBLoadLibraryExtFunc) Gum.Module.find_export_by_name (nb_mod,
|
||||
load = (NBLoadLibraryFunc) nb_mod.find_export_by_name ("_ZN7android23NativeBridgeLoadLibraryEPKci");
|
||||
load_ext = (NBLoadLibraryExtFunc) nb_mod.find_export_by_name (
|
||||
"_ZN7android26NativeBridgeLoadLibraryExtEPKciPNS_25native_bridge_namespace_tE");
|
||||
// XXX: Unload implementation seems to be unreliable.
|
||||
unload = null;
|
||||
get_trampoline = (NBGetTrampolineFunc) Gum.Module.find_export_by_name (nb_mod,
|
||||
get_trampoline = (NBGetTrampolineFunc) nb_mod.find_export_by_name (
|
||||
"_ZN7android25NativeBridgeGetTrampolineEPvPKcS2_j");
|
||||
}
|
||||
if (load == null || get_trampoline == null)
|
||||
throw new Error.NOT_SUPPORTED ("NativeBridge API is not available on this system");
|
||||
|
||||
var get_vms = (JNIGetCreatedJavaVMsFunc) Gum.Module.find_export_by_name (vm_mod, "JNI_GetCreatedJavaVMs");
|
||||
var get_vms = (JNIGetCreatedJavaVMsFunc) vm_mod.find_export_by_name ("JNI_GetCreatedJavaVMs");
|
||||
if (get_vms == null)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to locate Java VM");
|
||||
|
||||
@@ -1622,7 +1621,7 @@ namespace Frida.Agent {
|
||||
}
|
||||
#endif
|
||||
|
||||
private class LiveAgentSession : BaseAgentSession {
|
||||
private sealed class LiveAgentSession : BaseAgentSession {
|
||||
public uint registration_id {
|
||||
get;
|
||||
set;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
global:
|
||||
frida_agent_main;
|
||||
JNI_OnLoad;
|
||||
|
||||
local:
|
||||
*;
|
||||
};
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
global:
|
||||
frida_agent_main;
|
||||
JNI_OnLoad;
|
||||
|
||||
local:
|
||||
*;
|
||||
|
||||
@@ -28,7 +28,7 @@ if host_os_family == 'windows'
|
||||
elif host_os_family == 'darwin'
|
||||
extra_link_args += '-Wl,-exported_symbol,_frida_agent_main'
|
||||
else
|
||||
symscript = 'frida-agent.version'
|
||||
symscript = (host_os == 'android') ? 'frida-agent-android.version' : 'frida-agent.version'
|
||||
extra_link_args += '-Wl,--version-script,' + meson.current_source_dir() / symscript
|
||||
extra_link_depends += symscript
|
||||
endif
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#include "frida-base.h"
|
||||
|
||||
GBytes *
|
||||
frida_make_bytes_with_owner (GType t_type,
|
||||
GBoxedCopyFunc t_dup_func,
|
||||
GDestroyNotify t_destroy_func,
|
||||
void * data,
|
||||
gsize size,
|
||||
gpointer owner)
|
||||
{
|
||||
return g_bytes_new_with_free_func (data, size, t_destroy_func, owner);
|
||||
}
|
||||
+212
-11
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class BufferBuilder : Object {
|
||||
public sealed class BufferBuilder : Object {
|
||||
public ByteOrder byte_order {
|
||||
get;
|
||||
construct;
|
||||
@@ -307,7 +307,7 @@ namespace Frida {
|
||||
NUL
|
||||
}
|
||||
|
||||
public class Buffer : Object {
|
||||
public sealed class Buffer : Object {
|
||||
public Bytes bytes {
|
||||
get;
|
||||
construct;
|
||||
@@ -356,10 +356,20 @@ namespace Frida {
|
||||
return *((int8 *) get_pointer (offset, sizeof (int8)));
|
||||
}
|
||||
|
||||
public unowned Buffer write_int8 (size_t offset, int8 val) {
|
||||
*((int8 *) get_pointer (offset, sizeof (int8))) = val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public uint8 read_uint8 (size_t offset) {
|
||||
return *get_pointer (offset, sizeof (uint8));
|
||||
}
|
||||
|
||||
public unowned Buffer write_uint8 (size_t offset, uint8 val) {
|
||||
*((uint8 *) get_pointer (offset, sizeof (uint8))) = val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int16 read_int16 (size_t offset) {
|
||||
int16 val = *((int16 *) get_pointer (offset, sizeof (int16)));
|
||||
return (byte_order == BIG_ENDIAN)
|
||||
@@ -367,6 +377,14 @@ namespace Frida {
|
||||
: int16.from_little_endian (val);
|
||||
}
|
||||
|
||||
public unowned Buffer write_int16 (size_t offset, int16 val) {
|
||||
int16 target_val = (byte_order == BIG_ENDIAN)
|
||||
? val.to_big_endian ()
|
||||
: val.to_little_endian ();
|
||||
*((int16 *) get_pointer (offset, sizeof (int16))) = target_val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public uint16 read_uint16 (size_t offset) {
|
||||
uint16 val = *((uint16 *) get_pointer (offset, sizeof (uint16)));
|
||||
return (byte_order == BIG_ENDIAN)
|
||||
@@ -374,6 +392,14 @@ namespace Frida {
|
||||
: uint16.from_little_endian (val);
|
||||
}
|
||||
|
||||
public unowned Buffer write_uint16 (size_t offset, uint16 val) {
|
||||
uint16 target_val = (byte_order == BIG_ENDIAN)
|
||||
? val.to_big_endian ()
|
||||
: val.to_little_endian ();
|
||||
*((uint16 *) get_pointer (offset, sizeof (uint16))) = target_val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int32 read_int32 (size_t offset) {
|
||||
int32 val = *((int32 *) get_pointer (offset, sizeof (int32)));
|
||||
return (byte_order == BIG_ENDIAN)
|
||||
@@ -381,6 +407,14 @@ namespace Frida {
|
||||
: int32.from_little_endian (val);
|
||||
}
|
||||
|
||||
public unowned Buffer write_int32 (size_t offset, int32 val) {
|
||||
int32 target_val = (byte_order == BIG_ENDIAN)
|
||||
? val.to_big_endian ()
|
||||
: val.to_little_endian ();
|
||||
*((int32 *) get_pointer (offset, sizeof (int32))) = target_val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public uint32 read_uint32 (size_t offset) {
|
||||
uint32 val = *((uint32 *) get_pointer (offset, sizeof (uint32)));
|
||||
return (byte_order == BIG_ENDIAN)
|
||||
@@ -403,6 +437,14 @@ namespace Frida {
|
||||
: int64.from_little_endian (val);
|
||||
}
|
||||
|
||||
public unowned Buffer write_int64 (size_t offset, int64 val) {
|
||||
int64 target_val = (byte_order == BIG_ENDIAN)
|
||||
? val.to_big_endian ()
|
||||
: val.to_little_endian ();
|
||||
*((int64 *) get_pointer (offset, sizeof (int64))) = target_val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public uint64 read_uint64 (size_t offset) {
|
||||
uint64 val = *((uint64 *) get_pointer (offset, sizeof (uint64)));
|
||||
return (byte_order == BIG_ENDIAN)
|
||||
@@ -428,21 +470,35 @@ namespace Frida {
|
||||
return *((double *) &bits);
|
||||
}
|
||||
|
||||
public string read_string (size_t offset) {
|
||||
public string read_string (size_t offset) throws Error {
|
||||
string * start = (string *) get_pointer (offset, sizeof (char));
|
||||
size_t max_length = size - offset;
|
||||
string * val = (string *) get_pointer (offset, sizeof (char));
|
||||
string * end = memchr (val, 0, max_length);
|
||||
assert (end != null);
|
||||
size_t size = end - val;
|
||||
return val->substring (0, (long) size);
|
||||
string * end = memchr (start, 0, max_length);
|
||||
if (end == null)
|
||||
throw new Error.PROTOCOL ("Missing null character");
|
||||
size_t size = end - start;
|
||||
string val = start->substring (0, (long) size);
|
||||
if (!val.validate ())
|
||||
throw new Error.PROTOCOL ("Invalid UTF-8 string");
|
||||
return val;
|
||||
}
|
||||
|
||||
[CCode (cname = "memchr", cheader_filename = "string.h")]
|
||||
private extern static string * memchr (string * s, int c, size_t n);
|
||||
|
||||
public string read_fixed_string (size_t offset, size_t size) {
|
||||
string * val = (string *) get_pointer (offset, size);
|
||||
return val->substring (0, (long) size);
|
||||
public string read_fixed_string (size_t offset, size_t size) throws Error {
|
||||
string * start = (string *) get_pointer (offset, size);
|
||||
size_t max_length = size_t.min (size, this.size - offset);
|
||||
string * end = memchr (start, 0, max_length);
|
||||
size_t n;
|
||||
if (end != null)
|
||||
n = end - start;
|
||||
else
|
||||
n = size;
|
||||
string val = start->substring (0, (long) n);
|
||||
if (!val.validate ())
|
||||
throw new Error.PROTOCOL ("Invalid UTF-8 string");
|
||||
return val;
|
||||
}
|
||||
|
||||
public unowned Buffer write_string (size_t offset, string val) {
|
||||
@@ -451,6 +507,18 @@ namespace Frida {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Bytes read_bytes (size_t offset, size_t size) {
|
||||
var data = new uint8[size + 1];
|
||||
Memory.copy (data, get_pointer (offset, size), size);
|
||||
return new Bytes.take ((owned) data);
|
||||
}
|
||||
|
||||
public unowned Buffer write_bytes (size_t offset, Bytes bytes) {
|
||||
size_t size = bytes.get_size ();
|
||||
Memory.copy (get_pointer (offset, size), bytes.get_data (), size);
|
||||
return this;
|
||||
}
|
||||
|
||||
private uint8 * get_pointer (size_t offset, size_t n) {
|
||||
size_t minimum_size = offset + n;
|
||||
assert (size >= minimum_size);
|
||||
@@ -458,4 +526,137 @@ namespace Frida {
|
||||
return data + offset;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class BufferReader {
|
||||
public size_t offset {
|
||||
get {
|
||||
return _offset;
|
||||
}
|
||||
}
|
||||
|
||||
public size_t available {
|
||||
get {
|
||||
return buffer.bytes.get_size () - _offset;
|
||||
}
|
||||
}
|
||||
|
||||
private Buffer buffer;
|
||||
private size_t _offset = 0;
|
||||
|
||||
public BufferReader (Buffer buf) {
|
||||
buffer = buf;
|
||||
}
|
||||
|
||||
public uint64 read_pointer () throws Error {
|
||||
var pointer_size = buffer.pointer_size;
|
||||
check_available (pointer_size);
|
||||
var ptr = buffer.read_pointer (_offset);
|
||||
_offset += pointer_size;
|
||||
return ptr;
|
||||
}
|
||||
|
||||
public int8 read_int8 () throws Error {
|
||||
check_available (sizeof (int8));
|
||||
var val = buffer.read_int8 (_offset);
|
||||
_offset += sizeof (int8);
|
||||
return val;
|
||||
}
|
||||
|
||||
public uint8 read_uint8 () throws Error {
|
||||
check_available (sizeof (uint8));
|
||||
var val = buffer.read_uint8 (_offset);
|
||||
_offset += sizeof (uint8);
|
||||
return val;
|
||||
}
|
||||
|
||||
public int16 read_int16 () throws Error {
|
||||
check_available (sizeof (int16));
|
||||
var val = buffer.read_int16 (_offset);
|
||||
_offset += sizeof (int16);
|
||||
return val;
|
||||
}
|
||||
|
||||
public uint16 read_uint16 () throws Error {
|
||||
check_available (sizeof (uint16));
|
||||
var val = buffer.read_uint16 (_offset);
|
||||
_offset += sizeof (uint16);
|
||||
return val;
|
||||
}
|
||||
|
||||
public int32 read_int32 () throws Error {
|
||||
check_available (sizeof (int32));
|
||||
var val = buffer.read_int32 (_offset);
|
||||
_offset += sizeof (int32);
|
||||
return val;
|
||||
}
|
||||
|
||||
public uint32 read_uint32 () throws Error {
|
||||
check_available (sizeof (uint32));
|
||||
var val = buffer.read_uint32 (_offset);
|
||||
_offset += sizeof (uint32);
|
||||
return val;
|
||||
}
|
||||
|
||||
public int64 read_int64 () throws Error {
|
||||
check_available (sizeof (int64));
|
||||
var val = buffer.read_int64 (_offset);
|
||||
_offset += sizeof (int64);
|
||||
return val;
|
||||
}
|
||||
|
||||
public uint64 read_uint64 () throws Error {
|
||||
check_available (sizeof (uint64));
|
||||
var val = buffer.read_uint64 (_offset);
|
||||
_offset += sizeof (uint64);
|
||||
return val;
|
||||
}
|
||||
|
||||
public float read_float () throws Error {
|
||||
check_available (sizeof (float));
|
||||
var val = buffer.read_float (_offset);
|
||||
_offset += sizeof (float);
|
||||
return val;
|
||||
}
|
||||
|
||||
public double read_double () throws Error {
|
||||
check_available (sizeof (double));
|
||||
var val = buffer.read_double (_offset);
|
||||
_offset += sizeof (double);
|
||||
return val;
|
||||
}
|
||||
|
||||
public string read_string () throws Error {
|
||||
check_available (1);
|
||||
var val = buffer.read_string (_offset);
|
||||
_offset += val.length + 1;
|
||||
return val;
|
||||
}
|
||||
|
||||
public string read_fixed_string (size_t size) throws Error {
|
||||
check_available (size);
|
||||
var val = buffer.read_fixed_string (_offset, size);
|
||||
_offset += size;
|
||||
return val;
|
||||
}
|
||||
|
||||
public Bytes read_bytes (size_t size) throws Error {
|
||||
check_available (size);
|
||||
var val = buffer.bytes[_offset:_offset + size];
|
||||
_offset += size;
|
||||
return val;
|
||||
}
|
||||
|
||||
public unowned BufferReader skip (size_t n) throws Error {
|
||||
check_available (n);
|
||||
_offset += n;
|
||||
return this;
|
||||
}
|
||||
|
||||
private void check_available (size_t n) throws Error {
|
||||
if (available < n)
|
||||
throw new Error.PROTOCOL ("Malformed buffer: truncated");
|
||||
}
|
||||
}
|
||||
|
||||
public extern Bytes make_bytes_with_owner<T> (void * data, size_t size, owned T? owner = null);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
namespace Frida {
|
||||
public sealed class ChannelRegistry : Object {
|
||||
public signal void channel_closed (ChannelId id);
|
||||
|
||||
private Gee.Map<ChannelId?, weak IOStream> channels =
|
||||
new Gee.HashMap<ChannelId?, weak IOStream> (ChannelId.hash, ChannelId.equal);
|
||||
|
||||
~ChannelRegistry () {
|
||||
clear ();
|
||||
}
|
||||
|
||||
public void clear () {
|
||||
foreach (IOStream stream in channels.values.to_array ()) {
|
||||
var channel_stream = stream as ChannelStream;
|
||||
if (channel_stream != null)
|
||||
channel_stream.abandon ();
|
||||
}
|
||||
channels.clear ();
|
||||
}
|
||||
|
||||
public void register (ChannelId id, IOStream stream) {
|
||||
stream.set_data ("channel-registry-entry", new Entry (this, id));
|
||||
lock (channels)
|
||||
channels[id] = stream;
|
||||
}
|
||||
|
||||
public IOStream link (ChannelId id) throws Error {
|
||||
IOStream? stream;
|
||||
lock (channels)
|
||||
stream = channels[id];
|
||||
if (stream == null)
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid channel ID");
|
||||
return stream;
|
||||
}
|
||||
|
||||
public void unlink (ChannelId id) {
|
||||
lock (channels) {
|
||||
if (!channels.unset (id))
|
||||
return;
|
||||
}
|
||||
|
||||
channel_closed (id);
|
||||
}
|
||||
|
||||
private class Entry {
|
||||
public ChannelRegistry parent;
|
||||
public ChannelId id;
|
||||
|
||||
public Entry (ChannelRegistry parent, ChannelId id) {
|
||||
this.parent = parent;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
~Entry () {
|
||||
parent.unlink (id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ChannelEndpoint : Object, Channel {
|
||||
private IOStream? stream;
|
||||
|
||||
private ByteArray write_queue = new ByteArray ();
|
||||
private bool writing = false;
|
||||
|
||||
private Cancellable io_cancellable = new Cancellable ();
|
||||
|
||||
public ChannelEndpoint (IOStream stream) {
|
||||
this.stream = stream;
|
||||
|
||||
read_loop.begin ();
|
||||
}
|
||||
|
||||
public async void close (Cancellable? cancellable) throws Error, IOError {
|
||||
io_cancellable.cancel ();
|
||||
}
|
||||
|
||||
public async void input (uint8[] data, Cancellable? cancellable) throws Error, IOError {
|
||||
if (io_cancellable.is_cancelled ())
|
||||
throw new Error.INVALID_OPERATION ("Channel is closed");
|
||||
|
||||
write_queue.append (data);
|
||||
|
||||
if (!writing) {
|
||||
writing = true;
|
||||
|
||||
var source = new IdleSource ();
|
||||
source.set_callback (() => {
|
||||
process_write_queue.begin ();
|
||||
return false;
|
||||
});
|
||||
source.attach (MainContext.get_thread_default ());
|
||||
}
|
||||
}
|
||||
|
||||
private async void read_loop () {
|
||||
var input = stream.get_input_stream ();
|
||||
var buffer = new uint8[64 * 1024];
|
||||
|
||||
while (true) {
|
||||
ssize_t n;
|
||||
try {
|
||||
n = yield input.read_async (buffer, Priority.DEFAULT, io_cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
break;
|
||||
}
|
||||
|
||||
output (buffer[:n]);
|
||||
|
||||
if (n == 0)
|
||||
break;
|
||||
}
|
||||
|
||||
stream.close_async.begin ();
|
||||
stream = null;
|
||||
}
|
||||
|
||||
private async void process_write_queue () {
|
||||
if (stream != null) {
|
||||
var output = stream.get_output_stream ();
|
||||
|
||||
while (write_queue.len > 0) {
|
||||
uint8[] batch = write_queue.steal ();
|
||||
|
||||
size_t bytes_written;
|
||||
try {
|
||||
yield output.write_all_async (batch, Priority.DEFAULT, io_cancellable, out bytes_written);
|
||||
} catch (GLib.Error e) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
writing = false;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ChannelStream : VirtualStream {
|
||||
public Channel channel {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
private ByteArray recv_queue = new ByteArray ();
|
||||
private ByteArray send_queue = new ByteArray ();
|
||||
|
||||
public ChannelStream (Channel channel) {
|
||||
Object (channel: channel);
|
||||
}
|
||||
|
||||
construct {
|
||||
channel.output.connect (on_output);
|
||||
}
|
||||
|
||||
public void abandon () {
|
||||
with_state_lock (() => {
|
||||
state = CLOSED;
|
||||
update_pending_io ();
|
||||
});
|
||||
}
|
||||
|
||||
protected override IOCondition query_events () {
|
||||
IOCondition new_events = 0;
|
||||
|
||||
if (recv_queue.len != 0 || state == CLOSED)
|
||||
new_events |= IN;
|
||||
|
||||
if (state == OPEN)
|
||||
new_events |= OUT;
|
||||
|
||||
return new_events;
|
||||
}
|
||||
|
||||
protected override void handle_close () {
|
||||
channel.close.begin (null);
|
||||
}
|
||||
|
||||
public override ssize_t read (uint8[] buffer) throws IOError {
|
||||
ssize_t n = 0;
|
||||
with_state_lock (() => {
|
||||
n = ssize_t.min (recv_queue.len, buffer.length);
|
||||
if (n > 0) {
|
||||
Memory.copy (buffer, recv_queue.data, n);
|
||||
recv_queue.remove_range (0, (uint) n);
|
||||
|
||||
update_pending_io ();
|
||||
} else {
|
||||
if (state == OPEN)
|
||||
n = -1;
|
||||
}
|
||||
});
|
||||
|
||||
if (n == -1)
|
||||
throw new IOError.WOULD_BLOCK ("Resource temporarily unavailable");
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
public override ssize_t write (uint8[] buffer) throws IOError {
|
||||
with_state_lock (() => {
|
||||
send_queue.append (buffer);
|
||||
});
|
||||
|
||||
if (main_context.is_owner ()) {
|
||||
process_send_queue ();
|
||||
} else {
|
||||
var source = new IdleSource ();
|
||||
source.set_callback (() => {
|
||||
process_send_queue ();
|
||||
return Source.REMOVE;
|
||||
});
|
||||
source.attach (main_context);
|
||||
}
|
||||
|
||||
return buffer.length;
|
||||
}
|
||||
|
||||
private void process_send_queue () {
|
||||
uint8[]? chunk = null;
|
||||
with_state_lock (() => {
|
||||
size_t n = send_queue.len;
|
||||
if (n == 0)
|
||||
return;
|
||||
chunk = send_queue.data[0:n];
|
||||
send_queue.remove_range (0, (uint) n);
|
||||
});
|
||||
if (chunk == null)
|
||||
return;
|
||||
|
||||
channel.input.begin (chunk, io_cancellable);
|
||||
}
|
||||
|
||||
private void on_output (uint8[] data) {
|
||||
with_state_lock (() => {
|
||||
if (data.length != 0)
|
||||
recv_queue.append (data);
|
||||
else
|
||||
state = CLOSED;
|
||||
update_pending_io ();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace Frida {
|
||||
public sealed class CFArray<T> {
|
||||
private CoreFoundation.Array handle;
|
||||
|
||||
public static CFArray<T> wrap<T> (void * handle) {
|
||||
return new CFArray<T> ((CoreFoundation.Array) handle);
|
||||
}
|
||||
|
||||
private CFArray (CoreFoundation.Array handle) {
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
public Iterator<T> iterator () {
|
||||
return new Iterator<T> (handle);
|
||||
}
|
||||
|
||||
public class Iterator<T> {
|
||||
public CoreFoundation.Array handle;
|
||||
private CoreFoundation.Index i = 0;
|
||||
private CoreFoundation.Index length;
|
||||
|
||||
internal Iterator (CoreFoundation.Array arr) {
|
||||
handle = arr;
|
||||
length = arr.length;
|
||||
}
|
||||
|
||||
public unowned T? next_value () {
|
||||
if (i == length)
|
||||
return null;
|
||||
return handle[i++];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -60,7 +60,7 @@ namespace Frida {
|
||||
return yield connection.get_proxy (null, ObjectPath.HOST_SESSION, DBusProxyFlags.NONE, cancellable);
|
||||
}
|
||||
|
||||
private class DummyInputStream : InputStream {
|
||||
private sealed class DummyInputStream : InputStream {
|
||||
private bool done = false;
|
||||
private Mutex mutex;
|
||||
private Cond cond;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#include "frida-darwin.h"
|
||||
|
||||
gpointer
|
||||
_frida_dispatch_retain (gpointer object)
|
||||
{
|
||||
dispatch_retain (object);
|
||||
return object;
|
||||
}
|
||||
|
||||
void
|
||||
_frida_xpc_connection_set_event_handler (xpc_connection_t connection, FridaXpcHandler handler, gpointer user_data)
|
||||
{
|
||||
xpc_connection_set_event_handler (connection, ^(xpc_object_t object)
|
||||
{
|
||||
handler (object, user_data);
|
||||
});
|
||||
}
|
||||
|
||||
void
|
||||
_frida_xpc_connection_send_message_with_reply (xpc_connection_t connection, xpc_object_t message, dispatch_queue_t replyq,
|
||||
FridaXpcHandler handler, gpointer user_data, GDestroyNotify notify)
|
||||
{
|
||||
xpc_connection_send_message_with_reply (connection, message, replyq, ^(xpc_object_t object)
|
||||
{
|
||||
handler (object, user_data);
|
||||
if (notify != NULL)
|
||||
notify (user_data);
|
||||
});
|
||||
}
|
||||
|
||||
gchar *
|
||||
_frida_xpc_object_to_string (xpc_object_t object)
|
||||
{
|
||||
gchar * result;
|
||||
char * str;
|
||||
|
||||
str = xpc_copy_description (object);
|
||||
result = g_strdup (str);
|
||||
free (str);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
gboolean
|
||||
_frida_xpc_dictionary_apply (xpc_object_t dict, FridaXpcDictionaryApplier applier, gpointer user_data)
|
||||
{
|
||||
return xpc_dictionary_apply (dict, ^bool (const char * key, xpc_object_t val)
|
||||
{
|
||||
return applier (key, val, user_data);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef __FRIDA_DARWIN_H__
|
||||
#define __FRIDA_DARWIN_H__
|
||||
|
||||
#ifdef HAVE_MACOS
|
||||
|
||||
#include <glib.h>
|
||||
#include <xpc/xpc.h>
|
||||
|
||||
typedef void (* FridaXpcHandler) (xpc_object_t object, gpointer user_data);
|
||||
typedef gboolean (* FridaXpcDictionaryApplier) (const gchar * key, xpc_object_t val, gpointer user_data);
|
||||
|
||||
gpointer _frida_dispatch_retain (gpointer object);
|
||||
|
||||
void _frida_xpc_connection_set_event_handler (xpc_connection_t connection, FridaXpcHandler handler, gpointer user_data);
|
||||
void _frida_xpc_connection_send_message_with_reply (xpc_connection_t connection, xpc_object_t message, dispatch_queue_t replyq,
|
||||
FridaXpcHandler handler, gpointer user_data, GDestroyNotify notify);
|
||||
gchar * _frida_xpc_object_to_string (xpc_object_t object);
|
||||
gboolean _frida_xpc_dictionary_apply (xpc_object_t dict, FridaXpcDictionaryApplier applier, gpointer user_data);
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,114 @@
|
||||
namespace Frida.FS {
|
||||
public void mkdirp (File dir, Cancellable? cancellable = null) throws Error {
|
||||
try {
|
||||
dir.make_directory_with_parents (cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
if (!(e is IOError.EXISTS))
|
||||
throw new Error.PERMISSION_DENIED ("%s", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public void rmtree (File dir, Cancellable? cancellable = null) throws Error {
|
||||
rmtree_worker (dir, 0, cancellable);
|
||||
}
|
||||
|
||||
private void rmtree_worker (File dir, uint depth, Cancellable? cancellable = null) throws Error {
|
||||
FileEnumerator enumerator;
|
||||
try {
|
||||
enumerator = dir.enumerate_children (FileAttribute.STANDARD_NAME, NOFOLLOW_SYMLINKS, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
if (depth == 0 && e is IOError.NOT_FOUND)
|
||||
return;
|
||||
throw new Error.PERMISSION_DENIED ("%s", e.message);
|
||||
}
|
||||
|
||||
try {
|
||||
FileInfo? info;
|
||||
File? child;
|
||||
while (enumerator.iterate (out info, out child, cancellable) && info != null) {
|
||||
if (info == null)
|
||||
continue;
|
||||
if (info.get_file_type () == DIRECTORY)
|
||||
rmtree (child, cancellable);
|
||||
else
|
||||
child.delete (cancellable);
|
||||
}
|
||||
|
||||
dir.delete (cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
if (!(e is IOError.EXISTS))
|
||||
throw new Error.PERMISSION_DENIED ("%s", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public async void rmtree_async (File dir, Cancellable? cancellable = null) throws Error, IOError {
|
||||
yield rmtree_async_worker (dir, 0, cancellable);
|
||||
}
|
||||
|
||||
private async void rmtree_async_worker (File dir, uint depth, Cancellable? cancellable = null) throws Error, IOError {
|
||||
int io_priority = Priority.DEFAULT;
|
||||
|
||||
FileEnumerator enumerator;
|
||||
try {
|
||||
enumerator = yield dir.enumerate_children_async (FileAttribute.STANDARD_NAME, NOFOLLOW_SYMLINKS, io_priority,
|
||||
cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
if (depth == 0 && e is IOError.NOT_FOUND)
|
||||
return;
|
||||
throw new Error.PERMISSION_DENIED ("%s", e.message);
|
||||
}
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
var batch = yield enumerator.next_files_async (1000, io_priority, cancellable);
|
||||
if (batch.is_empty ())
|
||||
break;
|
||||
foreach (FileInfo info in batch) {
|
||||
File child = dir.get_child (info.get_name ());
|
||||
if (info.get_file_type () == DIRECTORY)
|
||||
yield rmtree_async_worker (child, depth + 1, cancellable);
|
||||
else
|
||||
yield child.delete_async (io_priority, cancellable);
|
||||
}
|
||||
}
|
||||
|
||||
yield dir.delete_async (io_priority, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.PERMISSION_DENIED ("%s", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public async string read_all_text (File f, Cancellable? cancellable) throws Error, IOError {
|
||||
Bytes b = yield read_all_bytes (f, cancellable);
|
||||
string text = (string) b.get_data ();
|
||||
if (!text.validate ())
|
||||
throw new Error.PROTOCOL ("Unable to read '%s': invalid UTF-8", f.get_parse_name ());
|
||||
return text;
|
||||
}
|
||||
|
||||
public async void write_all_text (File f, string t, Cancellable? cancellable) throws Error, IOError {
|
||||
yield write_all_bytes (f, new Bytes (t.data), cancellable);
|
||||
}
|
||||
|
||||
public async Bytes read_all_bytes (File f, Cancellable? cancellable) throws Error, IOError {
|
||||
try {
|
||||
return yield f.load_bytes_async (cancellable, null);
|
||||
} catch (GLib.Error e) {
|
||||
if (e is IOError.CANCELLED)
|
||||
throw (IOError) e;
|
||||
if (e is IOError.NOT_FOUND)
|
||||
throw new Error.INVALID_ARGUMENT ("%s", e.message);
|
||||
throw new Error.PERMISSION_DENIED ("%s", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public async void write_all_bytes (File f, Bytes b, Cancellable? cancellable) throws Error, IOError {
|
||||
try {
|
||||
yield f.replace_contents_bytes_async (b, null, false, FileCreateFlags.NONE, cancellable, null);
|
||||
} catch (GLib.Error e) {
|
||||
if (e is IOError.CANCELLED)
|
||||
throw (IOError) e;
|
||||
throw new Error.PERMISSION_DENIED ("%s", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#ifndef __FRIDA_SYSCALL_H__
|
||||
#define __FRIDA_SYSCALL_H__
|
||||
#ifndef __FRIDA_LINUX_SYSCALL_H__
|
||||
#define __FRIDA_LINUX_SYSCALL_H__
|
||||
|
||||
#include <linux/unistd.h>
|
||||
#include <sys/syscall.h>
|
||||
|
||||
#undef SYS_process_vm_readv
|
||||
@@ -14,7 +14,7 @@ namespace Frida {
|
||||
[CCode (cheader_filename = "sys/mman.h", cname = "MAP_ANONYMOUS")]
|
||||
public const int MAP_ANONYMOUS;
|
||||
|
||||
[CCode (cheader_filename = "linux/frida-syscall.h", cprefix = "SYS_", has_type_id = false)]
|
||||
[CCode (cheader_filename = "linux-syscall.h", cprefix = "SYS_", has_type_id = false)]
|
||||
public enum SysCall {
|
||||
memfd_create,
|
||||
pidfd_getfd,
|
||||
@@ -0,0 +1,107 @@
|
||||
namespace Frida {
|
||||
private uint linux_major = 0;
|
||||
private uint linux_minor = 0;
|
||||
|
||||
public bool check_kernel_version (uint major, uint minor) {
|
||||
if (linux_major == 0) {
|
||||
var name = Posix.utsname ();
|
||||
name.release.scanf ("%u.%u", out linux_major, out linux_minor);
|
||||
}
|
||||
|
||||
return (linux_major == major && linux_minor >= minor) || linux_major > major;
|
||||
}
|
||||
|
||||
public class FileDescriptor : Object, FileDescriptorBased {
|
||||
public int handle;
|
||||
|
||||
public FileDescriptor (int handle) {
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
~FileDescriptor () {
|
||||
if (handle != -1)
|
||||
Posix.close (handle);
|
||||
}
|
||||
|
||||
public int steal () {
|
||||
int result = handle;
|
||||
handle = -1;
|
||||
return result;
|
||||
}
|
||||
|
||||
public int get_fd () {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PidFileDescriptor : FileDescriptor {
|
||||
private uint pid;
|
||||
|
||||
private PidFileDescriptor (int fd, uint pid) {
|
||||
base (fd);
|
||||
this.pid = pid;
|
||||
}
|
||||
|
||||
public static bool is_supported () {
|
||||
return check_kernel_version (5, 3);
|
||||
}
|
||||
|
||||
public static bool getfd_is_supported () {
|
||||
return check_kernel_version (5, 6);
|
||||
}
|
||||
|
||||
public static PidFileDescriptor from_pid (uint pid) throws Error {
|
||||
int fd = pidfd_open (pid, 0);
|
||||
if (fd == -1)
|
||||
throw_pidfd_error (pid, errno);
|
||||
return new PidFileDescriptor (fd, pid);
|
||||
}
|
||||
|
||||
public FileDescriptor getfd (int targetfd) throws Error {
|
||||
int fd = pidfd_getfd (handle, targetfd, 0);
|
||||
if (fd == -1)
|
||||
throw_pidfd_error (pid, errno);
|
||||
return new FileDescriptor (fd);
|
||||
}
|
||||
|
||||
private static int pidfd_open (uint pid, uint flags) {
|
||||
return Linux.syscall (SysCall.pidfd_open, pid, flags);
|
||||
}
|
||||
|
||||
private static int pidfd_getfd (int pidfd, int targetfd, uint flags) {
|
||||
return Linux.syscall (SysCall.pidfd_getfd, pidfd, targetfd, flags);
|
||||
}
|
||||
|
||||
[NoReturn]
|
||||
private static void throw_pidfd_error (uint pid, int err) throws Error {
|
||||
switch (err) {
|
||||
case Posix.ESRCH:
|
||||
throw new Error.PROCESS_NOT_FOUND ("Process not found");
|
||||
case Posix.EPERM:
|
||||
throw new Error.PERMISSION_DENIED ("Unable to use pidfd for pid %u: %s", pid, strerror (err));
|
||||
default:
|
||||
throw new Error.NOT_SUPPORTED ("Unable to use pidfd for pid %u: %s", pid, strerror (err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace MemoryFileDescriptor {
|
||||
public bool is_supported () {
|
||||
return check_kernel_version (3, 17);
|
||||
}
|
||||
|
||||
public static FileDescriptor from_bytes (string name, Bytes bytes) {
|
||||
assert (is_supported ());
|
||||
|
||||
var fd = new FileDescriptor (memfd_create (name, 0));
|
||||
unowned uint8[] data = bytes.get_data ();
|
||||
ssize_t n = Posix.write (fd.handle, data, data.length);
|
||||
assert (n == data.length);
|
||||
return fd;
|
||||
}
|
||||
|
||||
private int memfd_create (string name, uint flags) {
|
||||
return Linux.syscall (SysCall.memfd_create, name, flags);
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
-2
@@ -1,17 +1,44 @@
|
||||
base_sources = [
|
||||
'session.vala',
|
||||
'session-glue.c',
|
||||
'channel.vala',
|
||||
'service.vala',
|
||||
'stream.vala',
|
||||
'rpc.vala',
|
||||
'p2p.vala',
|
||||
'p2p-glue.c',
|
||||
'dbus.vala',
|
||||
'promise.vala',
|
||||
'fs.vala',
|
||||
'socket.vala',
|
||||
'socket-glue.c',
|
||||
'buffer.vala',
|
||||
'buffer-glue.c',
|
||||
'value.vala',
|
||||
]
|
||||
|
||||
extra_vala_args = []
|
||||
|
||||
if host_os == 'macos'
|
||||
base_sources += [
|
||||
'xpc.vala',
|
||||
'frida-darwin.c',
|
||||
]
|
||||
endif
|
||||
|
||||
if host_os_family == 'darwin'
|
||||
base_sources += 'corefoundation.vala'
|
||||
endif
|
||||
|
||||
if host_os_family == 'linux'
|
||||
base_sources += 'linux.vala'
|
||||
extra_vala_args += [
|
||||
'--pkg=linux',
|
||||
'--pkg=linux-system',
|
||||
'--pkg=posix',
|
||||
]
|
||||
endif
|
||||
|
||||
extra_deps = []
|
||||
if host_os_family != 'windows'
|
||||
extra_vala_args += '--pkg=gio-unix-2.0'
|
||||
@@ -22,21 +49,37 @@ base_vala_args = [gum_vala_args, '--pkg=gio-2.0', '--pkg=json-glib-1.0']
|
||||
if nice_dep.found()
|
||||
base_vala_args += '--pkg=nice'
|
||||
endif
|
||||
if host_os_family == 'darwin'
|
||||
base_vala_args += [
|
||||
'--pkg=corefoundation',
|
||||
'--pkg=darwin-gcd',
|
||||
'--pkg=darwin-xpc',
|
||||
]
|
||||
endif
|
||||
if host_os_family == 'linux'
|
||||
base_vala_args += [
|
||||
'--vapidir=' + meson.current_source_dir(),
|
||||
'--pkg=gio-unix-2.0',
|
||||
]
|
||||
endif
|
||||
|
||||
base_gir_name = f'FridaBase-@[email protected]'
|
||||
|
||||
base = static_library('frida-base-' + api_version, base_sources,
|
||||
c_args: frida_component_cflags,
|
||||
vala_args: [base_vala_args, '--pkg=libsoup-3.0'] + extra_vala_args,
|
||||
vala_header: 'frida-base.h',
|
||||
vala_gir: base_gir_name,
|
||||
vala_vapi: f'frida-base-@[email protected]',
|
||||
dependencies: [glib_dep, gobject_dep, gio_dep, libsoup_dep, nice_dep, usrsctp_dep, gee_dep, json_glib_dep, gum_dep, openssl_dep] + extra_deps,
|
||||
install: true,
|
||||
install_dir: [true, header_install_dir, true],
|
||||
install_dir: [true, header_install_dir, true, false],
|
||||
)
|
||||
|
||||
base_dep = declare_dependency(
|
||||
include_directories: include_directories('.'),
|
||||
link_with: base,
|
||||
dependencies: [nice_dep, json_glib_dep, gum_dep],
|
||||
dependencies: [nice_dep, json_glib_dep, gum_dep] + extra_deps,
|
||||
)
|
||||
|
||||
base_build_dir = meson.current_build_dir()
|
||||
|
||||
+37
-248
@@ -169,7 +169,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class PeerSocket : Object, DatagramBased {
|
||||
public sealed class PeerSocket : Object, DatagramBased {
|
||||
public Nice.Agent agent {
|
||||
get;
|
||||
construct;
|
||||
@@ -452,6 +452,8 @@ namespace Frida {
|
||||
if ((_pending_io & c) != 0)
|
||||
source.set_ready_time (0);
|
||||
}
|
||||
|
||||
notify_property ("pending-io");
|
||||
}
|
||||
|
||||
private void prepare_for_io (int64 timeout, Cancellable? cancellable, out int64 deadline) throws IOError {
|
||||
@@ -563,7 +565,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class SctpConnection : IOStream {
|
||||
public sealed class SctpConnection : VirtualStream {
|
||||
public DatagramBased transport_socket {
|
||||
get;
|
||||
construct;
|
||||
@@ -584,55 +586,14 @@ namespace Frida {
|
||||
construct;
|
||||
}
|
||||
|
||||
public State state {
|
||||
get {
|
||||
return _state;
|
||||
}
|
||||
}
|
||||
|
||||
public override InputStream input_stream {
|
||||
get {
|
||||
return _input_stream;
|
||||
}
|
||||
}
|
||||
|
||||
public override OutputStream output_stream {
|
||||
get {
|
||||
return _output_stream;
|
||||
}
|
||||
}
|
||||
|
||||
public IOCondition pending_io {
|
||||
get {
|
||||
lock (state)
|
||||
return sctp_events;
|
||||
}
|
||||
}
|
||||
|
||||
private State _state = CREATED;
|
||||
private SctpInputStream _input_stream;
|
||||
private SctpOutputStream _output_stream;
|
||||
|
||||
private DatagramBasedSource transport_source;
|
||||
private uint8[] transport_buffer = new uint8[65536];
|
||||
|
||||
private void * sctp_socket;
|
||||
private IOCondition sctp_events = 0;
|
||||
private SctpTimerSource sctp_source;
|
||||
private uint16 stream_id;
|
||||
private ByteArray dcep_message = new ByteArray ();
|
||||
|
||||
private Gee.Map<unowned Source, IOCondition> sources = new Gee.HashMap<unowned Source, IOCondition> ();
|
||||
|
||||
private Cancellable io_cancellable = new Cancellable ();
|
||||
|
||||
public enum State {
|
||||
CREATED,
|
||||
OPENING,
|
||||
OPENED,
|
||||
CLOSED
|
||||
}
|
||||
|
||||
public SctpConnection (DatagramBased transport_socket, PeerSetup setup, uint16 port, size_t max_message_size) {
|
||||
Object (
|
||||
transport_socket: transport_socket,
|
||||
@@ -649,14 +610,9 @@ namespace Frida {
|
||||
protected extern static void _initialize_sctp_backend ();
|
||||
|
||||
construct {
|
||||
_input_stream = new SctpInputStream (this);
|
||||
_output_stream = new SctpOutputStream (this);
|
||||
|
||||
sctp_socket = _create_sctp_socket ();
|
||||
_connect_sctp_socket (sctp_socket, port);
|
||||
|
||||
var main_context = MainContext.get_thread_default ();
|
||||
|
||||
transport_source = transport_socket.create_source (IOCondition.IN, io_cancellable);
|
||||
transport_source.set_callback (on_transport_socket_readable);
|
||||
transport_source.attach (main_context);
|
||||
@@ -669,17 +625,22 @@ namespace Frida {
|
||||
|
||||
protected extern void _connect_sctp_socket (void * sock, uint16 port);
|
||||
|
||||
public override bool close (GLib.Cancellable? cancellable) throws IOError {
|
||||
do_close ();
|
||||
return true;
|
||||
protected override VirtualStream.State query_initial_state () {
|
||||
return CREATED;
|
||||
}
|
||||
|
||||
public override async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws IOError {
|
||||
do_close ();
|
||||
return true;
|
||||
protected override IOCondition query_events () {
|
||||
return _query_sctp_socket_events (sctp_socket);
|
||||
}
|
||||
|
||||
private void do_close () {
|
||||
protected override void update_pending_io () {
|
||||
base.update_pending_io ();
|
||||
sctp_source.invalidate ();
|
||||
}
|
||||
|
||||
protected extern static IOCondition _query_sctp_socket_events (void * sock);
|
||||
|
||||
protected override void handle_close () {
|
||||
sctp_source.destroy ();
|
||||
transport_source.destroy ();
|
||||
|
||||
@@ -689,13 +650,17 @@ namespace Frida {
|
||||
|
||||
public extern static void _close (void * sock);
|
||||
|
||||
public void shutdown (SctpShutdownType type) throws IOError {
|
||||
_shutdown (sctp_socket, type);
|
||||
public override void shutdown_read () throws IOError {
|
||||
_shutdown (sctp_socket, READ);
|
||||
}
|
||||
|
||||
public override void shutdown_write () throws IOError {
|
||||
_shutdown (sctp_socket, WRITE);
|
||||
}
|
||||
|
||||
public extern static void _shutdown (void * sock, SctpShutdownType type) throws IOError;
|
||||
|
||||
public ssize_t recv (uint8[] buffer) throws IOError {
|
||||
public override ssize_t read (uint8[] buffer) throws IOError {
|
||||
ssize_t n = -1;
|
||||
|
||||
try {
|
||||
@@ -711,18 +676,18 @@ namespace Frida {
|
||||
handle_dcep_message (stream_id, dcep_message.steal ());
|
||||
}
|
||||
throw new IOError.WOULD_BLOCK ("Resource temporarily unavailable");
|
||||
} else if (protocol_id == NONE || _state != OPENED) {
|
||||
} else if (protocol_id == NONE || state != OPEN) {
|
||||
throw new IOError.WOULD_BLOCK ("Resource temporarily unavailable");
|
||||
}
|
||||
} finally {
|
||||
update_sctp_events ();
|
||||
update_pending_io ();
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
public ssize_t send (uint8[] buffer) throws IOError {
|
||||
if (_state != OPENED)
|
||||
public override ssize_t write (uint8[] buffer) throws IOError {
|
||||
if (state != OPEN)
|
||||
throw new IOError.WOULD_BLOCK ("Resource temporarily unavailable");
|
||||
|
||||
ssize_t n = ssize_t.min (buffer.length, (ssize_t) max_message_size);
|
||||
@@ -730,20 +695,10 @@ namespace Frida {
|
||||
try {
|
||||
return _send (sctp_socket, stream_id, WEBRTC_BINARY, buffer[0:n]);
|
||||
} finally {
|
||||
update_sctp_events ();
|
||||
update_pending_io ();
|
||||
}
|
||||
}
|
||||
|
||||
public void register_source (Source source, IOCondition condition) {
|
||||
lock (state)
|
||||
sources[source] = condition | IOCondition.ERR | IOCondition.HUP;
|
||||
}
|
||||
|
||||
public void unregister_source (Source source) {
|
||||
lock (state)
|
||||
sources.unset (source);
|
||||
}
|
||||
|
||||
private bool on_transport_socket_readable (DatagramBased datagram_based, IOCondition condition) {
|
||||
var v = InputVector ();
|
||||
v.buffer = transport_buffer;
|
||||
@@ -774,31 +729,18 @@ namespace Frida {
|
||||
protected extern void _handle_transport_packet (uint8[] data);
|
||||
|
||||
protected int _emit_transport_packet (uint8[] data) {
|
||||
var v = OutputVector ();
|
||||
v.buffer = data;
|
||||
v.size = data.length;
|
||||
|
||||
OutputVector[] vectors = { v };
|
||||
|
||||
var m = OutputMessage ();
|
||||
m.vectors = vectors;
|
||||
m.num_vectors = vectors.length;
|
||||
|
||||
OutputMessage[] messages = { m };
|
||||
|
||||
try {
|
||||
transport_socket.send_messages (messages, 0, 0, io_cancellable);
|
||||
Udp.send (data, transport_socket, io_cancellable);
|
||||
return 0;
|
||||
} catch (GLib.Error e) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected void _on_sctp_socket_events_changed () {
|
||||
update_sctp_events ();
|
||||
update_pending_io ();
|
||||
|
||||
if (_state == CREATED && setup == ACTIVE && (sctp_events & IOCondition.OUT) != 0) {
|
||||
if (state == CREATED && setup == ACTIVE && (pending_io & IOCondition.OUT) != 0) {
|
||||
stream_id = 1;
|
||||
|
||||
uint8[] open_message = {
|
||||
@@ -812,31 +754,12 @@ namespace Frida {
|
||||
};
|
||||
try {
|
||||
_send (sctp_socket, stream_id, WEBRTC_DCEP, open_message);
|
||||
_state = OPENING;
|
||||
state = OPENING;
|
||||
} catch (IOError e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void update_sctp_events () {
|
||||
IOCondition new_events = _query_sctp_socket_events (sctp_socket);
|
||||
|
||||
lock (state) {
|
||||
sctp_events = new_events;
|
||||
|
||||
foreach (var entry in sources.entries) {
|
||||
unowned Source source = entry.key;
|
||||
IOCondition c = entry.value;
|
||||
if ((new_events & c) != 0)
|
||||
source.set_ready_time (0);
|
||||
}
|
||||
|
||||
sctp_source.invalidate ();
|
||||
}
|
||||
}
|
||||
|
||||
protected extern static IOCondition _query_sctp_socket_events (void * sock);
|
||||
|
||||
protected extern static ssize_t _recv (void * sock, uint8[] buffer, out uint16 stream_id,
|
||||
out PayloadProtocolId protocol_id, out SctpMessageFlags message_flags) throws IOError;
|
||||
|
||||
@@ -848,7 +771,7 @@ namespace Frida {
|
||||
|
||||
switch (type) {
|
||||
case DATA_CHANNEL_OPEN: {
|
||||
if (_state != CREATED || setup == ACTIVE)
|
||||
if (state != CREATED || setup == ACTIVE)
|
||||
return;
|
||||
|
||||
this.stream_id = stream_id;
|
||||
@@ -856,15 +779,15 @@ namespace Frida {
|
||||
uint8[] reply = { DcepMessageType.DATA_CHANNEL_ACK };
|
||||
_send (sctp_socket, stream_id, WEBRTC_DCEP, reply);
|
||||
|
||||
_state = OPENED;
|
||||
state = OPEN;
|
||||
|
||||
break;
|
||||
}
|
||||
case DATA_CHANNEL_ACK:
|
||||
if (_state != OPENING)
|
||||
if (state != OPENING)
|
||||
return;
|
||||
|
||||
_state = OPENED;
|
||||
state = OPEN;
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -899,140 +822,6 @@ namespace Frida {
|
||||
DATA_CHANNEL_ACK = 0x02
|
||||
}
|
||||
|
||||
private class SctpInputStream : InputStream, PollableInputStream {
|
||||
public weak SctpConnection connection {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
public SctpInputStream (SctpConnection connection) {
|
||||
Object (connection: connection);
|
||||
}
|
||||
|
||||
public override bool close (Cancellable? cancellable) throws IOError {
|
||||
connection.shutdown (READ);
|
||||
return true;
|
||||
}
|
||||
|
||||
public override async bool close_async (int io_priority, Cancellable? cancellable) throws GLib.IOError {
|
||||
return close (cancellable);
|
||||
}
|
||||
|
||||
public override ssize_t read (uint8[] buffer, Cancellable? cancellable) throws IOError {
|
||||
assert_not_reached ();
|
||||
}
|
||||
|
||||
public bool can_poll () {
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool is_readable () {
|
||||
return (connection.pending_io & IOCondition.IN) != 0;
|
||||
}
|
||||
|
||||
public PollableSource create_source (Cancellable? cancellable) {
|
||||
return new PollableSource.full (this, new SctpIOSource (connection, IOCondition.IN), cancellable);
|
||||
}
|
||||
|
||||
public ssize_t read_nonblocking_fn (uint8[] buffer) throws GLib.Error {
|
||||
return connection.recv (buffer);
|
||||
}
|
||||
}
|
||||
|
||||
private class SctpOutputStream : OutputStream, PollableOutputStream {
|
||||
public weak SctpConnection connection {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
public SctpOutputStream (SctpConnection connection) {
|
||||
Object (connection: connection);
|
||||
}
|
||||
|
||||
public override bool close (Cancellable? cancellable) throws IOError {
|
||||
connection.shutdown (WRITE);
|
||||
return true;
|
||||
}
|
||||
|
||||
public override async bool close_async (int io_priority, Cancellable? cancellable) throws GLib.IOError {
|
||||
return close (cancellable);
|
||||
}
|
||||
|
||||
public override bool flush (GLib.Cancellable? cancellable) throws GLib.Error {
|
||||
return true;
|
||||
}
|
||||
|
||||
public override async bool flush_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error {
|
||||
return true;
|
||||
}
|
||||
|
||||
public override ssize_t write (uint8[] buffer, Cancellable? cancellable) throws IOError {
|
||||
assert_not_reached ();
|
||||
}
|
||||
|
||||
public bool can_poll () {
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool is_writable () {
|
||||
return (connection.pending_io & IOCondition.OUT) != 0;
|
||||
}
|
||||
|
||||
public PollableSource create_source (Cancellable? cancellable) {
|
||||
return new PollableSource.full (this, new SctpIOSource (connection, IOCondition.OUT), cancellable);
|
||||
}
|
||||
|
||||
public ssize_t write_nonblocking_fn (uint8[]? buffer) throws GLib.Error {
|
||||
return connection.send (buffer);
|
||||
}
|
||||
|
||||
public PollableReturn writev_nonblocking_fn (OutputVector[] vectors, out size_t bytes_written) throws GLib.Error {
|
||||
assert_not_reached ();
|
||||
}
|
||||
}
|
||||
|
||||
private class SctpIOSource : Source {
|
||||
public SctpConnection connection;
|
||||
public IOCondition condition;
|
||||
|
||||
public SctpIOSource (SctpConnection connection, IOCondition condition) {
|
||||
this.connection = connection;
|
||||
this.condition = condition;
|
||||
|
||||
connection.register_source (this, condition);
|
||||
}
|
||||
|
||||
~SctpIOSource () {
|
||||
connection.unregister_source (this);
|
||||
}
|
||||
|
||||
protected override bool prepare (out int timeout) {
|
||||
timeout = -1;
|
||||
return (connection.pending_io & condition) != 0;
|
||||
}
|
||||
|
||||
protected override bool check () {
|
||||
return (connection.pending_io & condition) != 0;
|
||||
}
|
||||
|
||||
protected override bool dispatch (SourceFunc? callback) {
|
||||
set_ready_time (-1);
|
||||
|
||||
if (callback == null)
|
||||
return Source.REMOVE;
|
||||
|
||||
return callback ();
|
||||
}
|
||||
|
||||
protected static bool closure_callback (Closure closure) {
|
||||
var return_value = Value (typeof (bool));
|
||||
|
||||
closure.invoke (ref return_value, {});
|
||||
|
||||
return return_value.get_boolean ();
|
||||
}
|
||||
}
|
||||
|
||||
private class SctpTimerSource : Source {
|
||||
private static int64 last_process_time = -1;
|
||||
|
||||
|
||||
+53
-13
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class Promise<T> {
|
||||
public sealed class Promise<T> {
|
||||
private Impl<T> impl;
|
||||
|
||||
public Future<T> future {
|
||||
@@ -46,7 +46,8 @@ namespace Frida {
|
||||
}
|
||||
private GLib.Error? _error;
|
||||
|
||||
private Gee.ArrayQueue<CompletionFuncEntry> on_complete;
|
||||
private Gee.ArrayQueue<CompletionFuncEntry>? on_complete;
|
||||
private Gee.ArrayQueue<ThenHandlerEntry<T>>? on_then;
|
||||
|
||||
public async T wait_async (Cancellable? cancellable) throws Frida.Error, IOError {
|
||||
if (_ready)
|
||||
@@ -74,7 +75,21 @@ namespace Frida {
|
||||
return get_result ();
|
||||
}
|
||||
|
||||
private T get_result () throws Frida.Error, IOError {
|
||||
public void then (owned FutureCompletionHandler<T> handler) {
|
||||
if (_ready) {
|
||||
schedule (() => {
|
||||
handler (this);
|
||||
return Source.REMOVE;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (on_then == null)
|
||||
on_then = new Gee.ArrayQueue<ThenHandlerEntry<T>> ();
|
||||
on_then.offer (new ThenHandlerEntry<T> ((owned) handler));
|
||||
}
|
||||
|
||||
public T get_result () throws Frida.Error, IOError {
|
||||
if (error != null) {
|
||||
if (error is Frida.Error)
|
||||
throw (Frida.Error) error;
|
||||
@@ -111,19 +126,32 @@ namespace Frida {
|
||||
internal void transition_to_ready () {
|
||||
_ready = true;
|
||||
|
||||
if (on_complete != null && !on_complete.is_empty) {
|
||||
var source = new IdleSource ();
|
||||
source.set_priority (Priority.HIGH);
|
||||
source.set_callback (() => {
|
||||
CompletionFuncEntry? entry;
|
||||
while ((entry = on_complete.poll ()) != null)
|
||||
entry.func ();
|
||||
on_complete = null;
|
||||
return false;
|
||||
if (on_complete != null || on_then != null) {
|
||||
schedule (() => {
|
||||
if (on_complete != null) {
|
||||
CompletionFuncEntry? entry;
|
||||
while ((entry = on_complete.poll ()) != null)
|
||||
entry.func ();
|
||||
on_complete = null;
|
||||
}
|
||||
|
||||
if (on_then != null) {
|
||||
ThenHandlerEntry? entry;
|
||||
while ((entry = on_then.poll ()) != null)
|
||||
entry.handler (this);
|
||||
on_then = null;
|
||||
}
|
||||
|
||||
return Source.REMOVE;
|
||||
});
|
||||
source.attach (MainContext.get_thread_default ());
|
||||
}
|
||||
}
|
||||
|
||||
private static void schedule (owned SourceFunc function) {
|
||||
var source = new IdleSource ();
|
||||
source.set_callback ((owned) function);
|
||||
source.attach (MainContext.get_thread_default ());
|
||||
}
|
||||
}
|
||||
|
||||
private class CompletionFuncEntry {
|
||||
@@ -133,6 +161,14 @@ namespace Frida {
|
||||
this.func = (owned) func;
|
||||
}
|
||||
}
|
||||
|
||||
private class ThenHandlerEntry<T> {
|
||||
public FutureCompletionHandler<T> handler;
|
||||
|
||||
public ThenHandlerEntry (owned FutureCompletionHandler<T> handler) {
|
||||
this.handler = (owned) handler;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface Future<T> : Object {
|
||||
@@ -140,5 +176,9 @@ namespace Frida {
|
||||
public abstract T? value { get; }
|
||||
public abstract GLib.Error? error { get; }
|
||||
public abstract async T wait_async (Cancellable? cancellable) throws Frida.Error, IOError;
|
||||
public abstract void then (owned FutureCompletionHandler<T> handler);
|
||||
public abstract T get_result () throws Frida.Error, IOError;
|
||||
}
|
||||
|
||||
public delegate void FutureCompletionHandler<T> (Future<T> future);
|
||||
}
|
||||
+4
-4
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class RpcClient : Object {
|
||||
public sealed class RpcClient : Object {
|
||||
public weak RpcPeer peer {
|
||||
get;
|
||||
construct;
|
||||
@@ -11,7 +11,7 @@ namespace Frida {
|
||||
Object (peer: peer);
|
||||
}
|
||||
|
||||
public async Json.Node call (string method, Json.Node[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
public async Json.Node call (string method, Json.Node[] args, Bytes? data, Cancellable? cancellable) throws Error, IOError {
|
||||
string request_id = Uuid.string_random ();
|
||||
|
||||
var request = new Json.Builder ();
|
||||
@@ -39,7 +39,7 @@ namespace Frida {
|
||||
pending_responses[request_id] = pending;
|
||||
|
||||
try {
|
||||
yield peer.post_rpc_message (raw_request, cancellable);
|
||||
yield peer.post_rpc_message (raw_request, data, cancellable);
|
||||
} catch (Error e) {
|
||||
if (pending_responses.unset (request_id))
|
||||
pending.complete_with_error (e);
|
||||
@@ -158,6 +158,6 @@ namespace Frida {
|
||||
}
|
||||
|
||||
public interface RpcPeer : Object {
|
||||
public abstract async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError;
|
||||
public abstract async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
namespace Frida {
|
||||
public sealed class ServiceSessionRegistry : Object {
|
||||
public signal void session_closed (ServiceSessionId id);
|
||||
|
||||
private Gee.Map<ServiceSessionId?, ServiceSession> sessions =
|
||||
new Gee.HashMap<ServiceSessionId?, ServiceSession> (ServiceSessionId.hash, ServiceSessionId.equal);
|
||||
|
||||
~ServiceSessionRegistry () {
|
||||
clear ();
|
||||
}
|
||||
|
||||
public void clear () {
|
||||
foreach (var session in sessions.values.to_array ())
|
||||
session.close ();
|
||||
sessions.clear ();
|
||||
}
|
||||
|
||||
public void register (ServiceSessionId id, ServiceSession session) {
|
||||
sessions[id] = session;
|
||||
|
||||
ServiceSessionId? boxed_id = id;
|
||||
session.set_data ("service-session-id", boxed_id);
|
||||
|
||||
session.close.connect (on_session_close);
|
||||
}
|
||||
|
||||
public ServiceSession link (ServiceSessionId id) throws Error {
|
||||
var session = sessions[id];
|
||||
if (session == null)
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid session ID");
|
||||
return session;
|
||||
}
|
||||
|
||||
public void unlink (ServiceSessionId id) {
|
||||
ServiceSession? session;
|
||||
if (sessions.unset (id, out session)) {
|
||||
session.close.disconnect (on_session_close);
|
||||
|
||||
session_closed (id);
|
||||
}
|
||||
}
|
||||
|
||||
private void on_session_close (ServiceSession session) {
|
||||
ServiceSessionId? id = session.get_data ("service-session-id");
|
||||
unlink (id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ _frida_query_windows_computer_name (void)
|
||||
return g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
|
||||
}
|
||||
|
||||
#elif defined (HAVE_IOS) || defined (HAVE_TVOS)
|
||||
#elif defined (HAVE_IOS) || defined (HAVE_TVOS) || defined (HAVE_XROS)
|
||||
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <dlfcn.h>
|
||||
|
||||
+132
-25
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
[DBus (name = "re.frida.HostSession16")]
|
||||
[DBus (name = "re.frida.HostSession17")]
|
||||
public interface HostSession : Object {
|
||||
public abstract async void ping (uint interval_seconds, Cancellable? cancellable) throws GLib.Error;
|
||||
|
||||
@@ -27,6 +27,10 @@ namespace Frida {
|
||||
public abstract async InjectorPayloadId inject_library_blob (uint pid, uint8[] blob, string entrypoint, string data,
|
||||
Cancellable? cancellable) throws GLib.Error;
|
||||
|
||||
public abstract async ChannelId open_channel (string address, Cancellable? cancellable) throws GLib.Error;
|
||||
|
||||
public abstract async ServiceSessionId open_service (string address, Cancellable? cancellable) throws GLib.Error;
|
||||
|
||||
public signal void spawn_added (HostSpawnInfo info);
|
||||
public signal void spawn_removed (HostSpawnInfo info);
|
||||
public signal void child_added (HostChildInfo info);
|
||||
@@ -34,10 +38,12 @@ namespace Frida {
|
||||
public signal void process_crashed (CrashInfo crash);
|
||||
public signal void output (uint pid, int fd, uint8[] data);
|
||||
public signal void agent_session_detached (AgentSessionId id, SessionDetachReason reason, CrashInfo crash);
|
||||
public signal void channel_closed (ChannelId id);
|
||||
public signal void service_session_closed (ServiceSessionId id);
|
||||
public signal void uninjected (InjectorPayloadId id);
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.AgentSessionProvider16")]
|
||||
[DBus (name = "re.frida.AgentSessionProvider17")]
|
||||
public interface AgentSessionProvider : Object {
|
||||
public abstract async void open (AgentSessionId id, HashTable<string, Variant> options,
|
||||
Cancellable? cancellable) throws GLib.Error;
|
||||
@@ -52,7 +58,7 @@ namespace Frida {
|
||||
public signal void child_gating_changed (uint subscriber_count);
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.AgentSession16")]
|
||||
[DBus (name = "re.frida.AgentSession17")]
|
||||
public interface AgentSession : Object {
|
||||
public abstract async void close (Cancellable? cancellable) throws GLib.Error;
|
||||
|
||||
@@ -94,7 +100,7 @@ namespace Frida {
|
||||
public signal void candidate_gathering_done ();
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.AgentController16")]
|
||||
[DBus (name = "re.frida.AgentController17")]
|
||||
public interface AgentController : Object {
|
||||
#if !WINDOWS
|
||||
public abstract async HostChildId prepare_to_fork (uint parent_pid, Cancellable? cancellable, out uint parent_injectee_id,
|
||||
@@ -115,7 +121,7 @@ namespace Frida {
|
||||
Cancellable? cancellable) throws GLib.Error;
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.AgentMessageSink16")]
|
||||
[DBus (name = "re.frida.AgentMessageSink17")]
|
||||
public interface AgentMessageSink : Object {
|
||||
public abstract async void post_messages (AgentMessage[] messages, uint batch_id,
|
||||
Cancellable? cancellable) throws GLib.Error;
|
||||
@@ -145,7 +151,7 @@ namespace Frida {
|
||||
DEBUGGER
|
||||
}
|
||||
|
||||
public class AgentMessageTransmitter : Object {
|
||||
public sealed class AgentMessageTransmitter : Object {
|
||||
public signal void closed ();
|
||||
public signal void new_candidates (string[] candidate_sdps);
|
||||
public signal void candidate_gathering_done ();
|
||||
@@ -743,13 +749,43 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.TransportBroker16")]
|
||||
[DBus (name = "re.frida.GadgetSession17")]
|
||||
public interface GadgetSession : Object {
|
||||
public abstract async void break_and_resume (Cancellable? cancellable) throws GLib.Error;
|
||||
public abstract async void break_and_detach (Cancellable? cancellable) throws GLib.Error;
|
||||
}
|
||||
|
||||
public enum GadgetBreakpointAction {
|
||||
INVOKE_RETURN,
|
||||
RESUME,
|
||||
DETACH,
|
||||
PAGE_PLAN,
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.Channel17")]
|
||||
public interface Channel : Object {
|
||||
public abstract async void close (Cancellable? cancellable) throws GLib.Error;
|
||||
public abstract async void input (uint8[] data, Cancellable? cancellable) throws GLib.Error;
|
||||
public signal void output (uint8[] data);
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.ServiceSession17")]
|
||||
public interface ServiceSession : Object {
|
||||
public signal void close ();
|
||||
public signal void message (Variant message);
|
||||
|
||||
public abstract async void activate (Cancellable? cancellable) throws GLib.Error;
|
||||
public abstract async void cancel (Cancellable? cancellable) throws GLib.Error;
|
||||
public abstract async Variant request (Variant parameters, Cancellable? cancellable) throws GLib.Error;
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.TransportBroker17")]
|
||||
public interface TransportBroker : Object {
|
||||
public abstract async void open_tcp_transport (AgentSessionId id, Cancellable? cancellable, out uint16 port,
|
||||
out string token) throws GLib.Error;
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.PortalSession16")]
|
||||
[DBus (name = "re.frida.PortalSession17")]
|
||||
public interface PortalSession : Object {
|
||||
public abstract async void join (HostApplicationInfo app, SpawnStartState current_state,
|
||||
AgentSessionId[] interrupted_sessions, HashTable<string, Variant> options, Cancellable? cancellable,
|
||||
@@ -758,19 +794,19 @@ namespace Frida {
|
||||
public signal void kill ();
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.BusSession16")]
|
||||
[DBus (name = "re.frida.BusSession17")]
|
||||
public interface BusSession : Object {
|
||||
public abstract async void attach (Cancellable? cancellable) throws GLib.Error;
|
||||
public abstract async void post (string json, bool has_data, uint8[] data, Cancellable? cancellable) throws GLib.Error;
|
||||
public signal void message (string json, bool has_data, uint8[] data);
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.AuthenticationService16")]
|
||||
[DBus (name = "re.frida.AuthenticationService17")]
|
||||
public interface AuthenticationService : Object {
|
||||
public abstract async string authenticate (string token, Cancellable? cancellable) throws GLib.Error;
|
||||
}
|
||||
|
||||
public class StaticAuthenticationService : Object, AuthenticationService {
|
||||
public sealed class StaticAuthenticationService : Object, AuthenticationService {
|
||||
public string token_hash {
|
||||
get;
|
||||
construct;
|
||||
@@ -795,13 +831,13 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class NullAuthenticationService : Object, AuthenticationService {
|
||||
public sealed class NullAuthenticationService : Object, AuthenticationService {
|
||||
public async string authenticate (string token, Cancellable? cancellable) throws Error, IOError {
|
||||
throw new Error.INVALID_OPERATION ("Authentication not expected");
|
||||
}
|
||||
}
|
||||
|
||||
public class UnauthorizedHostSession : Object, HostSession {
|
||||
public sealed class UnauthorizedHostSession : Object, HostSession {
|
||||
public async void ping (uint interval_seconds, Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_authorized ();
|
||||
}
|
||||
@@ -875,9 +911,17 @@ namespace Frida {
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_authorized ();
|
||||
}
|
||||
|
||||
public async ChannelId open_channel (string address, Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_authorized ();
|
||||
}
|
||||
|
||||
public async ServiceSessionId open_service (string address, Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_authorized ();
|
||||
}
|
||||
}
|
||||
|
||||
public class UnauthorizedPortalSession : Object, PortalSession {
|
||||
public sealed class UnauthorizedPortalSession : Object, PortalSession {
|
||||
public async void join (HostApplicationInfo app, SpawnStartState current_state,
|
||||
AgentSessionId[] interrupted_sessions, HashTable<string, Variant> options,
|
||||
Cancellable? cancellable, out SpawnStartState next_state) throws Error, IOError {
|
||||
@@ -885,7 +929,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class UnauthorizedBusSession : Object, BusSession {
|
||||
public sealed class UnauthorizedBusSession : Object, BusSession {
|
||||
public async void attach (Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_authorized ();
|
||||
}
|
||||
@@ -1083,7 +1127,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class FrontmostQueryOptions : Object {
|
||||
public sealed class FrontmostQueryOptions : Object {
|
||||
public Scope scope {
|
||||
get;
|
||||
set;
|
||||
@@ -1113,7 +1157,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class ApplicationQueryOptions : Object {
|
||||
public sealed class ApplicationQueryOptions : Object {
|
||||
public Scope scope {
|
||||
get;
|
||||
set;
|
||||
@@ -1171,7 +1215,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class ProcessQueryOptions : Object {
|
||||
public sealed class ProcessQueryOptions : Object {
|
||||
public Scope scope {
|
||||
get;
|
||||
set;
|
||||
@@ -1313,7 +1357,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class SessionOptions : Object {
|
||||
public sealed class SessionOptions : Object {
|
||||
public Realm realm {
|
||||
get;
|
||||
set;
|
||||
@@ -1502,6 +1546,46 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public struct ChannelId {
|
||||
public string handle;
|
||||
|
||||
public ChannelId (string handle) {
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
public ChannelId.generate () {
|
||||
this.handle = Uuid.string_random ().replace ("-", "");
|
||||
}
|
||||
|
||||
public static uint hash (ChannelId? id) {
|
||||
return id.handle.hash ();
|
||||
}
|
||||
|
||||
public static bool equal (ChannelId? a, ChannelId? b) {
|
||||
return a.handle == b.handle;
|
||||
}
|
||||
}
|
||||
|
||||
public struct ServiceSessionId {
|
||||
public string handle;
|
||||
|
||||
public ServiceSessionId (string handle) {
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
public ServiceSessionId.generate () {
|
||||
this.handle = Uuid.string_random ().replace ("-", "");
|
||||
}
|
||||
|
||||
public static uint hash (ServiceSessionId? id) {
|
||||
return id.handle.hash ();
|
||||
}
|
||||
|
||||
public static bool equal (ServiceSessionId? a, ServiceSessionId? b) {
|
||||
return a.handle == b.handle;
|
||||
}
|
||||
}
|
||||
|
||||
public struct AgentScriptId {
|
||||
public uint handle;
|
||||
|
||||
@@ -1518,7 +1602,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class ScriptOptions : Object {
|
||||
public sealed class ScriptOptions : Object {
|
||||
public string? name {
|
||||
get;
|
||||
set;
|
||||
@@ -1608,7 +1692,7 @@ namespace Frida {
|
||||
SHARED_MEMORY
|
||||
}
|
||||
|
||||
public class SnapshotOptions : Object {
|
||||
public sealed class SnapshotOptions : Object {
|
||||
public string? warmup_script {
|
||||
get;
|
||||
set;
|
||||
@@ -1683,7 +1767,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class PortalOptions : Object {
|
||||
public sealed class PortalOptions : Object {
|
||||
public TlsCertificate? certificate {
|
||||
get;
|
||||
set;
|
||||
@@ -1746,7 +1830,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class PeerOptions : Object {
|
||||
public sealed class PeerOptions : Object {
|
||||
public string? stun_server {
|
||||
get;
|
||||
set;
|
||||
@@ -1807,7 +1891,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class Relay : Object {
|
||||
public sealed class Relay : Object {
|
||||
public string address {
|
||||
get;
|
||||
construct;
|
||||
@@ -1881,6 +1965,8 @@ namespace Frida {
|
||||
id = "watchos";
|
||||
#elif TVOS
|
||||
id = "tvos";
|
||||
#elif XROS
|
||||
id = "xros";
|
||||
#elif ANDROID
|
||||
id = "android";
|
||||
#elif FREEBSD
|
||||
@@ -2048,7 +2134,9 @@ namespace Frida {
|
||||
public const string AGENT_SESSION = "/re/frida/AgentSession";
|
||||
public const string AGENT_CONTROLLER = "/re/frida/AgentController";
|
||||
public const string AGENT_MESSAGE_SINK = "/re/frida/AgentMessageSink";
|
||||
public const string CHILD_SESSION = "/re/frida/ChildSession";
|
||||
public const string GADGET_SESSION = "/re/frida/GadgetSession";
|
||||
public const string CHANNEL = "/re/frida/Channel";
|
||||
public const string SERVICE = "/re/frida/Service";
|
||||
public const string TRANSPORT_BROKER = "/re/frida/TransportBroker";
|
||||
public const string PORTAL_SESSION = "/re/frida/PortalSession";
|
||||
public const string BUS_SESSION = "/re/frida/BusSession";
|
||||
@@ -2061,6 +2149,14 @@ namespace Frida {
|
||||
public static string for_agent_message_sink (AgentSessionId id) {
|
||||
return AGENT_MESSAGE_SINK + "/" + id.handle;
|
||||
}
|
||||
|
||||
public static string for_channel (ChannelId id) {
|
||||
return CHANNEL + "/" + id.handle;
|
||||
}
|
||||
|
||||
public static string for_service_session (ServiceSessionId id) {
|
||||
return SERVICE + "/" + id.handle;
|
||||
}
|
||||
}
|
||||
|
||||
namespace Marshal {
|
||||
@@ -2079,6 +2175,17 @@ namespace Frida {
|
||||
}
|
||||
|
||||
namespace Numeric {
|
||||
public uint int64_hash (int64? val) {
|
||||
uint64 v = (uint64) val.abs ();
|
||||
return (uint) ((v >> 32) ^ (v & 0xffffffffU));
|
||||
}
|
||||
|
||||
public bool int64_equal (int64? val_a, int64? val_b) {
|
||||
int64 a = val_a;
|
||||
int64 b = val_b;
|
||||
return a == b;
|
||||
}
|
||||
|
||||
public uint uint64_hash (uint64? val) {
|
||||
uint64 v = val;
|
||||
return (uint) ((v >> 32) ^ (v & 0xffffffffU));
|
||||
|
||||
+610
-587
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,336 @@
|
||||
namespace Frida {
|
||||
public abstract class VirtualStream : IOStream {
|
||||
public override InputStream input_stream {
|
||||
get {
|
||||
return _input_stream;
|
||||
}
|
||||
}
|
||||
|
||||
public override OutputStream output_stream {
|
||||
get {
|
||||
return _output_stream;
|
||||
}
|
||||
}
|
||||
|
||||
public IOCondition pending_io {
|
||||
get {
|
||||
lock (state)
|
||||
return _pending_io;
|
||||
}
|
||||
}
|
||||
|
||||
protected State state = OPEN;
|
||||
|
||||
private VirtualInputStream _input_stream;
|
||||
private VirtualOutputStream _output_stream;
|
||||
|
||||
private IOCondition _pending_io;
|
||||
|
||||
private Gee.Map<unowned Source, IOCondition> sources = new Gee.HashMap<unowned Source, IOCondition> ();
|
||||
|
||||
protected Cancellable io_cancellable = new Cancellable ();
|
||||
|
||||
protected MainContext main_context;
|
||||
|
||||
protected enum State {
|
||||
CREATED,
|
||||
OPENING,
|
||||
OPEN,
|
||||
CLOSED
|
||||
}
|
||||
|
||||
protected delegate void WorkFunc ();
|
||||
|
||||
construct {
|
||||
_input_stream = new VirtualInputStream (this);
|
||||
_output_stream = new VirtualOutputStream (this);
|
||||
|
||||
main_context = MainContext.ref_thread_default ();
|
||||
|
||||
state = query_initial_state ();
|
||||
_pending_io = query_events ();
|
||||
}
|
||||
|
||||
public override void dispose () {
|
||||
_output_stream.detach ();
|
||||
_input_stream.detach ();
|
||||
|
||||
io_cancellable.cancel ();
|
||||
|
||||
base.dispose ();
|
||||
}
|
||||
|
||||
protected virtual State query_initial_state () {
|
||||
return OPEN;
|
||||
}
|
||||
|
||||
protected abstract IOCondition query_events ();
|
||||
|
||||
public override bool close (GLib.Cancellable? cancellable) throws IOError {
|
||||
_close ();
|
||||
return true;
|
||||
}
|
||||
|
||||
public override async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws IOError {
|
||||
_close ();
|
||||
return true;
|
||||
}
|
||||
|
||||
private void _close () {
|
||||
if (main_context.is_owner ()) {
|
||||
do_close ();
|
||||
} else {
|
||||
var source = new IdleSource ();
|
||||
source.set_callback (() => {
|
||||
do_close ();
|
||||
return Source.REMOVE;
|
||||
});
|
||||
source.attach (main_context);
|
||||
}
|
||||
}
|
||||
|
||||
private void do_close () {
|
||||
if (state == CLOSED)
|
||||
return;
|
||||
|
||||
handle_close ();
|
||||
}
|
||||
|
||||
protected abstract void handle_close ();
|
||||
|
||||
public virtual void shutdown_read () throws IOError {
|
||||
}
|
||||
|
||||
public virtual void shutdown_write () throws IOError {
|
||||
}
|
||||
|
||||
public abstract ssize_t read (uint8[] buffer) throws IOError;
|
||||
|
||||
public abstract ssize_t write (uint8[] buffer) throws IOError;
|
||||
|
||||
protected void with_state_lock (WorkFunc func) {
|
||||
lock (state)
|
||||
func ();
|
||||
}
|
||||
|
||||
public void register_source (Source source, IOCondition condition) {
|
||||
lock (state)
|
||||
sources[source] = condition | IOCondition.ERR | IOCondition.HUP;
|
||||
}
|
||||
|
||||
public void unregister_source (Source source) {
|
||||
lock (state)
|
||||
sources.unset (source);
|
||||
}
|
||||
|
||||
protected virtual void update_pending_io () {
|
||||
lock (state) {
|
||||
_pending_io = query_events ();
|
||||
|
||||
foreach (var entry in sources.entries) {
|
||||
unowned Source source = entry.key;
|
||||
IOCondition c = entry.value;
|
||||
if ((_pending_io & c) != 0)
|
||||
source.set_ready_time (0);
|
||||
}
|
||||
}
|
||||
|
||||
notify_property ("pending-io");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class VirtualInputStream : InputStream, PollableInputStream {
|
||||
private weak VirtualStream stream;
|
||||
|
||||
public VirtualInputStream (VirtualStream stream) {
|
||||
Object ();
|
||||
this.stream = stream;
|
||||
}
|
||||
|
||||
internal void detach () {
|
||||
stream = null;
|
||||
}
|
||||
|
||||
public override bool close (Cancellable? cancellable) throws IOError {
|
||||
if (stream != null)
|
||||
stream.shutdown_read ();
|
||||
return true;
|
||||
}
|
||||
|
||||
public override async bool close_async (int io_priority, Cancellable? cancellable) throws GLib.IOError {
|
||||
return close (cancellable);
|
||||
}
|
||||
|
||||
public override ssize_t read (uint8[] buffer, Cancellable? cancellable) throws IOError {
|
||||
if (stream == null)
|
||||
return 0;
|
||||
|
||||
if (!is_readable ()) {
|
||||
bool done = false;
|
||||
var mutex = Mutex ();
|
||||
var cond = Cond ();
|
||||
|
||||
ulong io_handler = stream.notify["pending-io"].connect ((obj, pspec) => {
|
||||
if (is_readable ()) {
|
||||
mutex.lock ();
|
||||
done = true;
|
||||
cond.signal ();
|
||||
mutex.unlock ();
|
||||
}
|
||||
});
|
||||
ulong cancellation_handler = 0;
|
||||
if (cancellable != null) {
|
||||
cancellation_handler = cancellable.connect (() => {
|
||||
mutex.lock ();
|
||||
done = true;
|
||||
cond.signal ();
|
||||
mutex.unlock ();
|
||||
});
|
||||
}
|
||||
|
||||
if (!is_readable ()) {
|
||||
mutex.lock ();
|
||||
while (!done)
|
||||
cond.wait (mutex);
|
||||
mutex.unlock ();
|
||||
}
|
||||
|
||||
if (cancellation_handler != 0)
|
||||
cancellable.disconnect (cancellation_handler);
|
||||
stream.disconnect (io_handler);
|
||||
|
||||
cancellable.set_error_if_cancelled ();
|
||||
}
|
||||
|
||||
return stream.read (buffer);
|
||||
}
|
||||
|
||||
public bool can_poll () {
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool is_readable () {
|
||||
if (stream == null)
|
||||
return true;
|
||||
return (stream.pending_io & IOCondition.IN) != 0;
|
||||
}
|
||||
|
||||
public PollableSource create_source (Cancellable? cancellable) {
|
||||
return new PollableSource.full (this, new VirtualIOSource (stream, IOCondition.IN), cancellable);
|
||||
}
|
||||
|
||||
public ssize_t read_nonblocking_fn (uint8[] buffer) throws GLib.Error {
|
||||
if (stream == null)
|
||||
return 0;
|
||||
return stream.read (buffer);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class VirtualOutputStream : OutputStream, PollableOutputStream {
|
||||
private weak VirtualStream? stream;
|
||||
|
||||
public VirtualOutputStream (VirtualStream stream) {
|
||||
Object ();
|
||||
this.stream = stream;
|
||||
}
|
||||
|
||||
internal void detach () {
|
||||
stream = null;
|
||||
}
|
||||
|
||||
public override bool close (Cancellable? cancellable) throws IOError {
|
||||
if (stream != null)
|
||||
stream.shutdown_write ();
|
||||
return true;
|
||||
}
|
||||
|
||||
public override async bool close_async (int io_priority, Cancellable? cancellable) throws GLib.IOError {
|
||||
return close (cancellable);
|
||||
}
|
||||
|
||||
public override bool flush (GLib.Cancellable? cancellable) throws GLib.Error {
|
||||
return true;
|
||||
}
|
||||
|
||||
public override async bool flush_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error {
|
||||
return true;
|
||||
}
|
||||
|
||||
public override ssize_t write (uint8[] buffer, Cancellable? cancellable) throws IOError {
|
||||
return stream.write (buffer);
|
||||
}
|
||||
|
||||
public bool can_poll () {
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool is_writable () {
|
||||
if (stream == null)
|
||||
return false;
|
||||
return (stream.pending_io & IOCondition.OUT) != 0;
|
||||
}
|
||||
|
||||
public PollableSource create_source (Cancellable? cancellable) {
|
||||
return new PollableSource.full (this, new VirtualIOSource (stream, IOCondition.OUT), cancellable);
|
||||
}
|
||||
|
||||
public ssize_t write_nonblocking_fn (uint8[]? buffer) throws GLib.Error {
|
||||
if (stream == null)
|
||||
throw new IOError.CLOSED ("Virtual is closed");
|
||||
return stream.write (buffer);
|
||||
}
|
||||
|
||||
public PollableReturn writev_nonblocking_fn (OutputVector[] vectors, out size_t bytes_written) throws GLib.Error {
|
||||
assert_not_reached ();
|
||||
}
|
||||
}
|
||||
|
||||
private class VirtualIOSource : Source {
|
||||
public VirtualStream? stream;
|
||||
public IOCondition condition;
|
||||
|
||||
public VirtualIOSource (VirtualStream stream, IOCondition condition) {
|
||||
this.stream = stream;
|
||||
this.condition = condition;
|
||||
|
||||
if (stream != null)
|
||||
stream.register_source (this, condition);
|
||||
}
|
||||
|
||||
~VirtualIOSource () {
|
||||
if (stream != null)
|
||||
stream.unregister_source (this);
|
||||
}
|
||||
|
||||
protected override bool prepare (out int timeout) {
|
||||
timeout = -1;
|
||||
return is_ready ();
|
||||
}
|
||||
|
||||
protected override bool check () {
|
||||
return is_ready ();
|
||||
}
|
||||
|
||||
private bool is_ready () {
|
||||
IOCondition pending_io = (stream != null) ? stream.pending_io : IOCondition.IN;
|
||||
return (pending_io & condition) != 0;
|
||||
}
|
||||
|
||||
protected override bool dispatch (SourceFunc? callback) {
|
||||
set_ready_time (-1);
|
||||
|
||||
if (callback == null)
|
||||
return Source.REMOVE;
|
||||
|
||||
return callback ();
|
||||
}
|
||||
|
||||
protected static bool closure_callback (Closure closure) {
|
||||
var return_value = Value (typeof (bool));
|
||||
|
||||
closure.invoke (ref return_value, {});
|
||||
|
||||
return return_value.get_boolean ();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
namespace Frida {
|
||||
public interface ObjectBuilder : Object {
|
||||
public abstract unowned ObjectBuilder begin_dictionary ();
|
||||
public abstract unowned ObjectBuilder set_member_name (string name);
|
||||
public abstract unowned ObjectBuilder end_dictionary ();
|
||||
|
||||
public abstract unowned ObjectBuilder begin_array ();
|
||||
public abstract unowned ObjectBuilder end_array ();
|
||||
|
||||
public abstract unowned ObjectBuilder add_null_value ();
|
||||
public abstract unowned ObjectBuilder add_bool_value (bool val);
|
||||
public abstract unowned ObjectBuilder add_int64_value (int64 val);
|
||||
public abstract unowned ObjectBuilder add_uint64_value (uint64 val);
|
||||
public abstract unowned ObjectBuilder add_data_value (Bytes val);
|
||||
public abstract unowned ObjectBuilder add_string_value (string val);
|
||||
public abstract unowned ObjectBuilder add_uuid_value (uint8[] val);
|
||||
public abstract unowned ObjectBuilder add_raw_value (Bytes val);
|
||||
|
||||
public abstract Bytes build ();
|
||||
}
|
||||
|
||||
public interface ObjectReader : Object {
|
||||
public abstract bool has_member (string name) throws Error;
|
||||
public abstract unowned ObjectReader read_member (string name) throws Error;
|
||||
public abstract unowned ObjectReader end_member ();
|
||||
|
||||
public abstract uint count_elements () throws Error;
|
||||
public abstract unowned ObjectReader read_element (uint index) throws Error;
|
||||
public abstract unowned ObjectReader end_element () throws Error;
|
||||
|
||||
public abstract bool get_bool_value () throws Error;
|
||||
public abstract uint8 get_uint8_value () throws Error;
|
||||
public abstract uint16 get_uint16_value () throws Error;
|
||||
public abstract int64 get_int64_value () throws Error;
|
||||
public abstract uint64 get_uint64_value () throws Error;
|
||||
public abstract Bytes get_data_value () throws Error;
|
||||
public abstract unowned string get_string_value () throws Error;
|
||||
public abstract unowned string get_uuid_value () throws Error;
|
||||
}
|
||||
|
||||
public sealed class VariantReader : Object, ObjectReader {
|
||||
public Variant root_object {
|
||||
get {
|
||||
return scopes.peek_head ().val;
|
||||
}
|
||||
}
|
||||
|
||||
public Variant current_object {
|
||||
get {
|
||||
return scopes.peek_tail ().val;
|
||||
}
|
||||
}
|
||||
|
||||
private Gee.Deque<Scope> scopes = new Gee.ArrayQueue<Scope> ();
|
||||
|
||||
public VariantReader (Variant v) {
|
||||
push_scope (v);
|
||||
}
|
||||
|
||||
public bool has_member (string name) throws Error {
|
||||
var scope = peek_scope ();
|
||||
if (scope.dict == null)
|
||||
throw new Error.PROTOCOL ("Dictionary expected, but at %s", scope.val.print (true));
|
||||
return scope.dict.contains (name);
|
||||
}
|
||||
|
||||
public unowned ObjectReader read_member (string name) throws Error {
|
||||
var scope = peek_scope ();
|
||||
if (scope.dict == null)
|
||||
throw new Error.PROTOCOL ("Dictionary expected, but at %s", scope.val.print (true));
|
||||
|
||||
Variant? v = scope.dict.lookup_value (name, null);
|
||||
if (v == null)
|
||||
throw new Error.PROTOCOL ("Key '%s' not found in dictionary: %s", name, scope.val.print (true));
|
||||
|
||||
push_scope (v);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectReader end_member () {
|
||||
pop_scope ();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public uint count_elements () throws Error {
|
||||
var scope = peek_scope ();
|
||||
scope.check_array ();
|
||||
return (uint) scope.val.n_children ();
|
||||
}
|
||||
|
||||
public unowned ObjectReader read_element (uint index) throws Error {
|
||||
var scope = peek_scope ();
|
||||
scope.check_array ();
|
||||
push_scope (scope.val.get_child_value (index).get_variant ());
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectReader end_element () throws Error {
|
||||
pop_scope ();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public bool get_bool_value () throws Error {
|
||||
return peek_scope ().get_value (VariantType.BOOLEAN).get_boolean ();
|
||||
}
|
||||
|
||||
public uint8 get_uint8_value () throws Error {
|
||||
return peek_scope ().get_value (VariantType.BYTE).get_byte ();
|
||||
}
|
||||
|
||||
public uint16 get_uint16_value () throws Error {
|
||||
return peek_scope ().get_value (VariantType.UINT16).get_uint16 ();
|
||||
}
|
||||
|
||||
public int64 get_int64_value () throws Error {
|
||||
return peek_scope ().get_value (VariantType.INT64).get_int64 ();
|
||||
}
|
||||
|
||||
public uint64 get_uint64_value () throws Error {
|
||||
return peek_scope ().get_value (VariantType.UINT64).get_uint64 ();
|
||||
}
|
||||
|
||||
public Bytes get_data_value () throws Error {
|
||||
return peek_scope ().get_value (new VariantType.array (VariantType.BYTE)).get_data_as_bytes ();
|
||||
}
|
||||
|
||||
public unowned string get_string_value () throws Error {
|
||||
return peek_scope ().get_value (VariantType.STRING).get_string ();
|
||||
}
|
||||
|
||||
public unowned string get_uuid_value () throws Error {
|
||||
return peek_scope ().get_value (VariantType.STRING).get_string (); // TODO: Use a tuple to avoid ambiguity.
|
||||
}
|
||||
|
||||
private void push_scope (Variant v) {
|
||||
scopes.offer_tail (new Scope (v));
|
||||
}
|
||||
|
||||
private Scope peek_scope () {
|
||||
return scopes.peek_tail ();
|
||||
}
|
||||
|
||||
private Scope pop_scope () {
|
||||
return scopes.poll_tail ();
|
||||
}
|
||||
|
||||
private class Scope {
|
||||
public Variant val;
|
||||
public VariantDict? dict;
|
||||
public bool is_array = false;
|
||||
|
||||
public Scope (Variant v) {
|
||||
val = v;
|
||||
|
||||
VariantType t = v.get_type ();
|
||||
if (t.equal (VariantType.VARDICT))
|
||||
dict = new VariantDict (v);
|
||||
else if (t.is_subtype_of (VariantType.ARRAY))
|
||||
is_array = true;
|
||||
}
|
||||
|
||||
public Variant get_value (VariantType expected_type) throws Error {
|
||||
if (!val.get_type ().equal (expected_type)) {
|
||||
throw new Error.PROTOCOL ("Expected type '%s', got '%s'",
|
||||
(string) expected_type.peek_string (),
|
||||
(string) val.get_type ().peek_string ());
|
||||
}
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
public void check_array () throws Error {
|
||||
if (!is_array)
|
||||
throw new Error.PROTOCOL ("Array expected, but at %s", val.print (true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class JsonObjectBuilder : Object, ObjectBuilder {
|
||||
private Json.Builder builder = new Json.Builder ();
|
||||
private Gee.Map<string, Bytes> raw_values = new Gee.HashMap<string, Bytes> ();
|
||||
|
||||
public unowned ObjectBuilder begin_dictionary () {
|
||||
builder.begin_object ();
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder set_member_name (string name) {
|
||||
builder.set_member_name (name);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder end_dictionary () {
|
||||
builder.end_object ();
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder begin_array () {
|
||||
builder.begin_array ();
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder end_array () {
|
||||
builder.end_array ();
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder add_null_value () {
|
||||
builder.add_null_value ();
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder add_bool_value (bool val) {
|
||||
builder.add_boolean_value (val);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder add_int64_value (int64 val) {
|
||||
builder.add_int_value (val);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder add_uint64_value (uint64 val) {
|
||||
builder.add_int_value ((int64) val);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder add_data_value (Bytes val) {
|
||||
builder.add_string_value (Base64.encode (val.get_data ()));
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder add_string_value (string val) {
|
||||
builder.add_string_value (val);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder add_uuid_value (uint8[] val) {
|
||||
assert_not_reached ();
|
||||
}
|
||||
|
||||
public unowned ObjectBuilder add_raw_value (Bytes val) {
|
||||
string uuid = Uuid.string_random ();
|
||||
builder.add_string_value (uuid);
|
||||
raw_values[uuid] = val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Bytes build () {
|
||||
string json = Json.to_string (builder.get_root (), false);
|
||||
|
||||
foreach (var e in raw_values.entries) {
|
||||
unowned string uuid = e.key;
|
||||
Bytes val = e.value;
|
||||
|
||||
unowned string raw_str = (string) val.get_data ();
|
||||
string str = raw_str[:(long) val.get_size ()];
|
||||
|
||||
json = json.replace ("\"" + uuid + "\"", str);
|
||||
}
|
||||
|
||||
return new Bytes (json.data);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class JsonObjectReader : Object, ObjectReader {
|
||||
private Json.Reader reader;
|
||||
|
||||
public JsonObjectReader (string json) throws Error {
|
||||
try {
|
||||
reader = new Json.Reader (Json.from_string (json));
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("%s", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public bool has_member (string name) throws Error {
|
||||
bool result = reader.read_member (name);
|
||||
reader.end_member ();
|
||||
return result;
|
||||
}
|
||||
|
||||
public unowned ObjectReader read_member (string name) throws Error {
|
||||
if (!reader.read_member (name))
|
||||
throw_dict_access_error ();
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectReader end_member () {
|
||||
reader.end_member ();
|
||||
return this;
|
||||
}
|
||||
|
||||
[NoReturn]
|
||||
private void throw_dict_access_error () throws Error {
|
||||
GLib.Error e = reader.get_error ();
|
||||
reader.end_member ();
|
||||
throw new Error.PROTOCOL ("%s", e.message);
|
||||
}
|
||||
|
||||
public uint count_elements () throws Error {
|
||||
int n = reader.count_elements ();
|
||||
if (n == -1)
|
||||
throw_array_access_error ();
|
||||
return n;
|
||||
}
|
||||
|
||||
public unowned ObjectReader read_element (uint index) throws Error {
|
||||
if (!reader.read_element (index)) {
|
||||
GLib.Error e = reader.get_error ();
|
||||
reader.end_element ();
|
||||
throw new Error.PROTOCOL ("%s", e.message);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned ObjectReader end_element () throws Error {
|
||||
reader.end_element ();
|
||||
return this;
|
||||
}
|
||||
|
||||
[NoReturn]
|
||||
private void throw_array_access_error () throws Error {
|
||||
GLib.Error e = reader.get_error ();
|
||||
reader.end_element ();
|
||||
throw new Error.PROTOCOL ("%s", e.message);
|
||||
}
|
||||
|
||||
public bool get_bool_value () throws Error {
|
||||
bool v = reader.get_boolean_value ();
|
||||
if (!v)
|
||||
maybe_throw_value_access_error ();
|
||||
return v;
|
||||
}
|
||||
|
||||
public uint8 get_uint8_value () throws Error {
|
||||
int64 v = get_int64_value ();
|
||||
if (v < 0 || v > uint8.MAX)
|
||||
throw new Error.PROTOCOL ("Invalid uint8");
|
||||
return (uint8) v;
|
||||
}
|
||||
|
||||
public uint16 get_uint16_value () throws Error {
|
||||
int64 v = get_int64_value ();
|
||||
if (v < 0 || v > uint16.MAX)
|
||||
throw new Error.PROTOCOL ("Invalid uint16");
|
||||
return (uint16) v;
|
||||
}
|
||||
|
||||
public int64 get_int64_value () throws Error {
|
||||
int64 v = reader.get_int_value ();
|
||||
if (v == 0)
|
||||
maybe_throw_value_access_error ();
|
||||
return v;
|
||||
}
|
||||
|
||||
public uint64 get_uint64_value () throws Error {
|
||||
int64 v = get_int64_value ();
|
||||
if (v < 0)
|
||||
throw new Error.PROTOCOL ("Invalid uint64");
|
||||
return v;
|
||||
}
|
||||
|
||||
public Bytes get_data_value () throws Error {
|
||||
return new Bytes (Base64.decode (get_string_value ()));
|
||||
}
|
||||
|
||||
public unowned string get_string_value () throws Error {
|
||||
unowned string? v = reader.get_string_value ();
|
||||
if (v == null)
|
||||
maybe_throw_value_access_error ();
|
||||
return v;
|
||||
}
|
||||
|
||||
public unowned string get_uuid_value () throws Error {
|
||||
return get_string_value ();
|
||||
}
|
||||
|
||||
private void maybe_throw_value_access_error () throws Error {
|
||||
GLib.Error? e = reader.get_error ();
|
||||
if (e == null)
|
||||
return;
|
||||
reader.end_member ();
|
||||
throw new Error.PROTOCOL ("%s", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
namespace Frida {
|
||||
public sealed class XpcClient : Object {
|
||||
public signal void message (Darwin.Xpc.Object obj);
|
||||
|
||||
public State state {
|
||||
get {
|
||||
return _state;
|
||||
}
|
||||
}
|
||||
|
||||
public Darwin.Xpc.Connection connection {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
public Darwin.GCD.DispatchQueue queue {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
private State _state;
|
||||
private string? close_reason;
|
||||
private MainContext main_context;
|
||||
|
||||
public enum State {
|
||||
OPEN,
|
||||
CLOSING,
|
||||
CLOSED,
|
||||
}
|
||||
|
||||
public static XpcClient make_for_mach_service (string name, Darwin.GCD.DispatchQueue queue) {
|
||||
return new XpcClient (Darwin.Xpc.Connection.create_mach_service (name, queue, 0), queue);
|
||||
}
|
||||
|
||||
public XpcClient (Darwin.Xpc.Connection connection, Darwin.GCD.DispatchQueue queue) {
|
||||
Object (connection: connection, queue: queue);
|
||||
}
|
||||
|
||||
construct {
|
||||
main_context = MainContext.ref_thread_default ();
|
||||
|
||||
connection.set_event_handler (on_event);
|
||||
connection.activate ();
|
||||
}
|
||||
|
||||
public override void dispose () {
|
||||
if (close_reason != null) {
|
||||
change_state (CLOSED);
|
||||
} else {
|
||||
change_state (CLOSING);
|
||||
this.ref ();
|
||||
connection.cancel ();
|
||||
}
|
||||
|
||||
base.dispose ();
|
||||
}
|
||||
|
||||
public async Darwin.Xpc.Object request (Darwin.Xpc.Object message, Cancellable? cancellable) throws Error, IOError {
|
||||
Darwin.Xpc.Object? reply = null;
|
||||
connection.send_message_with_reply (message, queue, r => {
|
||||
schedule_on_frida_thread (() => {
|
||||
reply = r;
|
||||
request.callback ();
|
||||
return Source.REMOVE;
|
||||
});
|
||||
});
|
||||
|
||||
var cancel_source = new CancellableSource (cancellable);
|
||||
cancel_source.set_callback (() => {
|
||||
connection.cancel ();
|
||||
return Source.REMOVE;
|
||||
});
|
||||
cancel_source.attach (main_context);
|
||||
|
||||
yield;
|
||||
|
||||
cancel_source.destroy ();
|
||||
|
||||
if (reply.type == Darwin.Xpc.Error.TYPE) {
|
||||
var e = (Darwin.Xpc.Error) reply;
|
||||
throw new Error.NOT_SUPPORTED ("%s", e.get_string (Darwin.Xpc.Error.KEY_DESCRIPTION));
|
||||
}
|
||||
|
||||
return reply;
|
||||
}
|
||||
|
||||
public void post (Darwin.Xpc.Object message) throws Error, IOError {
|
||||
connection.send_message (message);
|
||||
}
|
||||
|
||||
private void change_state (State new_state) {
|
||||
_state = new_state;
|
||||
notify_property ("state");
|
||||
}
|
||||
|
||||
private void on_event (Darwin.Xpc.Object obj) {
|
||||
schedule_on_frida_thread (() => {
|
||||
if (obj.type == Darwin.Xpc.Error.TYPE) {
|
||||
var e = (Darwin.Xpc.Error) obj;
|
||||
close_reason = e.get_string (Darwin.Xpc.Error.KEY_DESCRIPTION);
|
||||
switch (state) {
|
||||
case OPEN:
|
||||
change_state (CLOSED);
|
||||
break;
|
||||
case CLOSING:
|
||||
change_state (CLOSED);
|
||||
unref ();
|
||||
break;
|
||||
case CLOSED:
|
||||
assert_not_reached ();
|
||||
}
|
||||
} else {
|
||||
message (obj);
|
||||
}
|
||||
return Source.REMOVE;
|
||||
});
|
||||
}
|
||||
|
||||
private void schedule_on_frida_thread (owned SourceFunc function) {
|
||||
var source = new IdleSource ();
|
||||
source.set_callback ((owned) function);
|
||||
source.attach (main_context);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class XpcObjectReader {
|
||||
public Darwin.Xpc.Object root_object {
|
||||
get {
|
||||
return scopes.peek_head ().object;
|
||||
}
|
||||
}
|
||||
|
||||
public Darwin.Xpc.Object current_object {
|
||||
get {
|
||||
return scopes.peek_tail ().object;
|
||||
}
|
||||
}
|
||||
|
||||
public delegate int TranslateErrorFunc (string domain, int code, string description);
|
||||
|
||||
private Gee.Deque<Scope> scopes = new Gee.ArrayQueue<Scope> ();
|
||||
|
||||
public XpcObjectReader (Darwin.Xpc.Object obj) {
|
||||
push_scope (obj);
|
||||
}
|
||||
|
||||
public bool has_member (string name) throws Error {
|
||||
return peek_scope ().get_dictionary ().get_value (name) != null;
|
||||
}
|
||||
|
||||
public bool try_read_member (string name) throws Error {
|
||||
var scope = peek_scope ();
|
||||
var dict = scope.get_dictionary ();
|
||||
var val = dict.get_value (name);
|
||||
if (val == null)
|
||||
return false;
|
||||
|
||||
push_scope (val);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public unowned XpcObjectReader read_member (string name) throws Error {
|
||||
var scope = peek_scope ();
|
||||
var dict = scope.get_dictionary ();
|
||||
var val = dict.get_value (name);
|
||||
if (val == null)
|
||||
throw new Error.PROTOCOL ("Key '%s' not found in dictionary: %s", name, scope.object.to_string ());
|
||||
|
||||
push_scope (val);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned XpcObjectReader end_member () {
|
||||
pop_scope ();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public size_t count_elements () throws Error {
|
||||
return peek_scope ().get_array ().count;
|
||||
}
|
||||
|
||||
public unowned XpcObjectReader read_element (size_t index) throws Error {
|
||||
push_scope (peek_scope ().get_array ().get_value (index));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned XpcObjectReader end_element () throws Error {
|
||||
pop_scope ();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public bool get_bool_value () throws Error {
|
||||
return peek_scope ().get_object<Darwin.Xpc.Bool> (Darwin.Xpc.Bool.TYPE).get_value ();
|
||||
}
|
||||
|
||||
public int64 get_int64_value () throws Error {
|
||||
return peek_scope ().get_object<Darwin.Xpc.Int64> (Darwin.Xpc.Int64.TYPE).get_value ();
|
||||
}
|
||||
|
||||
public uint64 get_uint64_value () throws Error {
|
||||
return peek_scope ().get_object<Darwin.Xpc.UInt64> (Darwin.Xpc.UInt64.TYPE).get_value ();
|
||||
}
|
||||
|
||||
public unowned uint8[] get_data_value () throws Error {
|
||||
var data = peek_scope ().get_object<Darwin.Xpc.Data> (Darwin.Xpc.Data.TYPE);
|
||||
unowned uint8[] buf = (uint8[]) data.get_bytes_ptr ();
|
||||
buf.length = (int) data.get_length ();
|
||||
return buf;
|
||||
}
|
||||
|
||||
public unowned string get_string_value () throws Error {
|
||||
return peek_scope ().get_object<Darwin.Xpc.String> (Darwin.Xpc.String.TYPE).get_string_ptr ();
|
||||
}
|
||||
|
||||
public unowned uint8[] get_uuid_value () throws Error {
|
||||
return peek_scope ().get_object<Darwin.Xpc.Uuid> (Darwin.Xpc.Uuid.TYPE).get_bytes ()[:16];
|
||||
}
|
||||
|
||||
public unowned string get_error_description () throws Error {
|
||||
var error = peek_scope ().get_object<Darwin.Xpc.Error> (Darwin.Xpc.Error.TYPE);
|
||||
return error.get_string (Darwin.Xpc.Error.KEY_DESCRIPTION);
|
||||
}
|
||||
|
||||
public void check_nserror (TranslateErrorFunc translate_error) throws Error {
|
||||
if (!has_member ("error"))
|
||||
return;
|
||||
|
||||
read_member ("error");
|
||||
|
||||
unowned string domain = read_member ("domain").get_string_value ();
|
||||
end_member ();
|
||||
|
||||
var code = (int) read_member ("code").get_int64_value ();
|
||||
end_member ();
|
||||
|
||||
string description = read_member ("userInfo").read_member ("NSLocalizedDescription").get_string_value ();
|
||||
if (description.has_suffix ("."))
|
||||
description = description[:description.length - 1];
|
||||
|
||||
throw (Error) new GLib.Error.literal (
|
||||
Quark.from_string ("frida-error-quark"),
|
||||
translate_error (domain, code, description),
|
||||
description);
|
||||
}
|
||||
|
||||
public unowned Darwin.Xpc.Object get_object_value (Darwin.Xpc.Type expected_type) throws Error {
|
||||
return peek_scope ().get_object<Darwin.Xpc.Object> (expected_type);
|
||||
}
|
||||
|
||||
private void push_scope (Darwin.Xpc.Object obj) {
|
||||
scopes.offer_tail (new Scope (obj));
|
||||
}
|
||||
|
||||
private Scope peek_scope () {
|
||||
return scopes.peek_tail ();
|
||||
}
|
||||
|
||||
private Scope pop_scope () {
|
||||
return scopes.poll_tail ();
|
||||
}
|
||||
|
||||
private class Scope {
|
||||
public Darwin.Xpc.Object object;
|
||||
private unowned Darwin.Xpc.Type type;
|
||||
|
||||
public Scope (Darwin.Xpc.Object obj) {
|
||||
object = obj;
|
||||
type = obj.type;
|
||||
}
|
||||
|
||||
public unowned T get_object<T> (Darwin.Xpc.Type expected_type) throws Error {
|
||||
if (type != expected_type)
|
||||
throw new Error.PROTOCOL ("Expected type '%s', got '%s'", expected_type.name, type.name);
|
||||
return object;
|
||||
}
|
||||
|
||||
public unowned Darwin.Xpc.Array get_array () throws Error {
|
||||
return get_object<Darwin.Xpc.Array> (Darwin.Xpc.Array.TYPE);
|
||||
}
|
||||
|
||||
public unowned Darwin.Xpc.Dictionary get_dictionary () throws Error {
|
||||
return get_object<Darwin.Xpc.Dictionary> (Darwin.Xpc.Dictionary.TYPE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+166
-1
@@ -1,9 +1,25 @@
|
||||
#if defined (HAVE_TVOS) || defined (HAVE_WATCHOS)
|
||||
# include <Availability.h>
|
||||
# undef __TVOS_PROHIBITED
|
||||
# define __TVOS_PROHIBITED
|
||||
# undef __WATCHOS_PROHIBITED
|
||||
# define __WATCHOS_PROHIBITED
|
||||
#endif
|
||||
|
||||
#include "frida-gadget.h"
|
||||
|
||||
#include "frida-base.h"
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#include <gum/gumdarwin.h>
|
||||
#include <mach-o/loader.h>
|
||||
#include <objc/runtime.h>
|
||||
#include <pthread.h>
|
||||
|
||||
static void frida_on_breakpoints_steal_attempt (GumInvocationContext * ic, gpointer user_data);
|
||||
|
||||
static GumInvocationListener * frida_dont_steal_my_breakpoints;
|
||||
|
||||
gchar *
|
||||
frida_gadget_environment_detect_bundle_id (void)
|
||||
{
|
||||
@@ -27,7 +43,7 @@ frida_gadget_environment_detect_bundle_name (void)
|
||||
gchar *
|
||||
frida_gadget_environment_detect_documents_dir (void)
|
||||
{
|
||||
#if defined (HAVE_IOS) || defined (HAVE_TVOS)
|
||||
#if defined (HAVE_IOS) || defined (HAVE_TVOS) || defined (HAVE_XROS)
|
||||
@autoreleasepool
|
||||
{
|
||||
NSArray<NSString *> * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
|
||||
@@ -51,3 +67,152 @@ frida_gadget_environment_set_thread_name (const gchar * name)
|
||||
/* For now only implemented on i/macOS as Fruity.Injector relies on it there. */
|
||||
pthread_setname_np (name);
|
||||
}
|
||||
|
||||
void
|
||||
frida_gadget_environment_detect_darwin_location_fields (GumAddress our_address, gchar ** executable_name, gchar ** our_path,
|
||||
GumMemoryRange ** our_range)
|
||||
{
|
||||
mach_port_t task;
|
||||
GumDarwinModuleResolver * resolver;
|
||||
GPtrArray * modules;
|
||||
guint i;
|
||||
|
||||
task = mach_task_self ();
|
||||
|
||||
resolver = gum_darwin_module_resolver_new (task, NULL);
|
||||
if (resolver == NULL)
|
||||
return;
|
||||
|
||||
gum_darwin_module_resolver_fetch_modules (resolver, &modules, NULL);
|
||||
|
||||
for (i = 0; i != modules->len; i++)
|
||||
{
|
||||
GumModule * module;
|
||||
const GumMemoryRange * range;
|
||||
|
||||
module = g_ptr_array_index (modules, i);
|
||||
range = gum_module_get_range (module);
|
||||
|
||||
if (*executable_name == NULL)
|
||||
{
|
||||
gum_mach_header_t * header = GSIZE_TO_POINTER (range->base_address);
|
||||
if (header->filetype == MH_EXECUTE)
|
||||
*executable_name = g_strdup (gum_module_get_name (module));
|
||||
}
|
||||
|
||||
if (our_address >= range->base_address && our_address < range->base_address + range->size)
|
||||
{
|
||||
if (*our_path == NULL)
|
||||
*our_path = g_strdup (gum_module_get_path (module));
|
||||
|
||||
if (*our_range == NULL)
|
||||
*our_range = gum_memory_range_copy (range);
|
||||
}
|
||||
|
||||
if (*executable_name != NULL && *our_path != NULL && *our_range != NULL)
|
||||
break;
|
||||
}
|
||||
|
||||
g_ptr_array_unref (modules);
|
||||
|
||||
g_object_unref (resolver);
|
||||
}
|
||||
|
||||
void
|
||||
frida_gadget_environment_ensure_debugger_breakpoints_only (void)
|
||||
{
|
||||
task_set_exception_ports (
|
||||
mach_task_self (),
|
||||
EXC_MASK_ALL & ~EXC_MASK_BREAKPOINT,
|
||||
MACH_PORT_NULL,
|
||||
EXCEPTION_DEFAULT,
|
||||
THREAD_STATE_NONE
|
||||
);
|
||||
|
||||
if (gum_process_get_code_signing_policy () == GUM_CODE_SIGNING_OPTIONAL &&
|
||||
frida_dont_steal_my_breakpoints == NULL &&
|
||||
gum_darwin_is_debugger_mapping_enforced ())
|
||||
{
|
||||
gpointer exceptions_set, exceptions_swap;
|
||||
GumInterceptor * interceptor;
|
||||
|
||||
exceptions_set = &task_set_exception_ports;
|
||||
exceptions_swap = &task_swap_exception_ports;
|
||||
|
||||
frida_dont_steal_my_breakpoints = gum_make_call_listener (frida_on_breakpoints_steal_attempt,
|
||||
NULL, NULL, NULL);
|
||||
|
||||
interceptor = gum_interceptor_obtain ();
|
||||
|
||||
gum_interceptor_attach (interceptor, exceptions_set, frida_dont_steal_my_breakpoints,
|
||||
NULL, GUM_ATTACH_FLAGS_NONE);
|
||||
gum_interceptor_attach (interceptor, exceptions_swap, frida_dont_steal_my_breakpoints,
|
||||
NULL, GUM_ATTACH_FLAGS_NONE);
|
||||
|
||||
g_object_unref (interceptor);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
frida_gadget_environment_allow_stolen_breakpoints (void)
|
||||
{
|
||||
GumInterceptor * interceptor;
|
||||
|
||||
if (frida_dont_steal_my_breakpoints == NULL)
|
||||
return;
|
||||
|
||||
interceptor = gum_interceptor_obtain ();
|
||||
|
||||
gum_interceptor_detach (interceptor, frida_dont_steal_my_breakpoints);
|
||||
|
||||
g_object_unref (frida_dont_steal_my_breakpoints);
|
||||
frida_dont_steal_my_breakpoints = NULL;
|
||||
|
||||
g_object_unref (interceptor);
|
||||
}
|
||||
|
||||
static void
|
||||
frida_on_breakpoints_steal_attempt (GumInvocationContext * ic, gpointer user_data)
|
||||
{
|
||||
exception_mask_t exception_mask;
|
||||
|
||||
exception_mask = GPOINTER_TO_SIZE (gum_invocation_context_get_nth_argument (ic, 1));
|
||||
exception_mask &= ~EXC_MASK_BREAKPOINT;
|
||||
gum_invocation_context_replace_nth_argument (ic, 1, GSIZE_TO_POINTER (exception_mask));
|
||||
}
|
||||
|
||||
void
|
||||
frida_gadget_environment_break_and_resume (void)
|
||||
{
|
||||
#ifdef HAVE_ARM64
|
||||
asm volatile (
|
||||
"mov x1, #1337\n\t"
|
||||
"mov x2, #1337\n\t"
|
||||
"mov x3, %0\n\t"
|
||||
"brk #1337\n\t"
|
||||
:
|
||||
: "r" ((gsize) FRIDA_GADGET_BREAKPOINT_ACTION_RESUME)
|
||||
: "x1", "x2", "x3"
|
||||
);
|
||||
#else
|
||||
g_assert_not_reached ();
|
||||
#endif
|
||||
}
|
||||
|
||||
void
|
||||
frida_gadget_environment_break_and_detach (void)
|
||||
{
|
||||
#ifdef HAVE_ARM64
|
||||
asm volatile (
|
||||
"mov x1, #1337\n\t"
|
||||
"mov x2, #1337\n\t"
|
||||
"mov x3, %0\n\t"
|
||||
"brk #1337\n\t"
|
||||
:
|
||||
: "r" ((gsize) FRIDA_GADGET_BREAKPOINT_ACTION_DETACH)
|
||||
: "x1", "x2", "x3"
|
||||
);
|
||||
#else
|
||||
g_assert_not_reached ();
|
||||
#endif
|
||||
}
|
||||
+141
-111
@@ -1,5 +1,5 @@
|
||||
namespace Frida.Gadget {
|
||||
private class Config : Object, Json.Serializable {
|
||||
private sealed class Config : Object, Json.Serializable {
|
||||
public Object interaction {
|
||||
get;
|
||||
set;
|
||||
@@ -24,12 +24,6 @@ namespace Frida.Gadget {
|
||||
default = Gum.CodeSigningPolicy.OPTIONAL;
|
||||
}
|
||||
|
||||
private ObjectClass klass = (ObjectClass) typeof (Config).class_ref ();
|
||||
|
||||
public Json.Node serialize_property (string property_name, GLib.Value value, GLib.ParamSpec pspec) {
|
||||
return default_serialize_property (property_name, value, pspec);
|
||||
}
|
||||
|
||||
public bool deserialize_property (string property_name, out Value value, ParamSpec pspec, Json.Node property_node) {
|
||||
if (property_name == "interaction" && property_node.get_node_type () == Json.NodeType.OBJECT) {
|
||||
var interaction_node = property_node.get_object ();
|
||||
@@ -77,23 +71,9 @@ namespace Frida.Gadget {
|
||||
value = Value (pspec.value_type);
|
||||
return false;
|
||||
}
|
||||
|
||||
public unowned ParamSpec? find_property (string name) {
|
||||
return klass.find_property (name);
|
||||
}
|
||||
|
||||
public new Value get_property (ParamSpec pspec) {
|
||||
var val = Value (pspec.value_type);
|
||||
base.get_property (pspec.name, ref val);
|
||||
return val;
|
||||
}
|
||||
|
||||
public new void set_property (ParamSpec pspec, Value value) {
|
||||
base.set_property (pspec.name, value);
|
||||
}
|
||||
}
|
||||
|
||||
private class ScriptInteraction : Object, Json.Serializable {
|
||||
private sealed class ScriptInteraction : Object, Json.Serializable {
|
||||
public string path {
|
||||
get;
|
||||
set;
|
||||
@@ -112,12 +92,6 @@ namespace Frida.Gadget {
|
||||
default = Script.ChangeBehavior.IGNORE;
|
||||
}
|
||||
|
||||
private ObjectClass klass = (ObjectClass) typeof (ScriptInteraction).class_ref ();
|
||||
|
||||
public Json.Node serialize_property (string property_name, GLib.Value value, GLib.ParamSpec pspec) {
|
||||
return default_serialize_property (property_name, value, pspec);
|
||||
}
|
||||
|
||||
public bool deserialize_property (string property_name, out Value value, ParamSpec pspec, Json.Node property_node) {
|
||||
if (property_name == "parameters" && property_node.get_node_type () == Json.NodeType.OBJECT) {
|
||||
var v = Value (typeof (Json.Node));
|
||||
@@ -129,23 +103,9 @@ namespace Frida.Gadget {
|
||||
value = Value (pspec.value_type);
|
||||
return false;
|
||||
}
|
||||
|
||||
public unowned ParamSpec? find_property (string name) {
|
||||
return klass.find_property (name);
|
||||
}
|
||||
|
||||
public new Value get_property (ParamSpec pspec) {
|
||||
var val = Value (pspec.value_type);
|
||||
base.get_property (pspec.name, ref val);
|
||||
return val;
|
||||
}
|
||||
|
||||
public new void set_property (ParamSpec pspec, Value value) {
|
||||
base.set_property (pspec.name, value);
|
||||
}
|
||||
}
|
||||
|
||||
private class ScriptDirectoryInteraction : Object {
|
||||
private sealed class ScriptDirectoryInteraction : Object {
|
||||
public string path {
|
||||
get;
|
||||
set;
|
||||
@@ -164,7 +124,7 @@ namespace Frida.Gadget {
|
||||
}
|
||||
}
|
||||
|
||||
private class ScriptConfig : Object, Json.Serializable {
|
||||
private sealed class ScriptConfig : Object, Json.Serializable {
|
||||
public ProcessFilter? filter {
|
||||
get;
|
||||
set;
|
||||
@@ -183,12 +143,6 @@ namespace Frida.Gadget {
|
||||
default = Script.ChangeBehavior.IGNORE;
|
||||
}
|
||||
|
||||
private ObjectClass klass = (ObjectClass) typeof (ScriptConfig).class_ref ();
|
||||
|
||||
public Json.Node serialize_property (string property_name, GLib.Value value, GLib.ParamSpec pspec) {
|
||||
return default_serialize_property (property_name, value, pspec);
|
||||
}
|
||||
|
||||
public bool deserialize_property (string property_name, out Value value, ParamSpec pspec, Json.Node property_node) {
|
||||
if (property_name == "parameters" && property_node.get_node_type () == Json.NodeType.OBJECT) {
|
||||
var v = Value (typeof (Json.Node));
|
||||
@@ -200,23 +154,9 @@ namespace Frida.Gadget {
|
||||
value = Value (pspec.value_type);
|
||||
return false;
|
||||
}
|
||||
|
||||
public unowned ParamSpec? find_property (string name) {
|
||||
return klass.find_property (name);
|
||||
}
|
||||
|
||||
public new Value get_property (ParamSpec pspec) {
|
||||
var val = Value (pspec.value_type);
|
||||
base.get_property (pspec.name, ref val);
|
||||
return val;
|
||||
}
|
||||
|
||||
public new void set_property (ParamSpec pspec, Value value) {
|
||||
base.set_property (pspec.name, value);
|
||||
}
|
||||
}
|
||||
|
||||
private class ProcessFilter : Object {
|
||||
private sealed class ProcessFilter : Object {
|
||||
public string[] executables {
|
||||
get;
|
||||
set;
|
||||
@@ -258,7 +198,7 @@ namespace Frida.Gadget {
|
||||
}
|
||||
}
|
||||
|
||||
private class ListenInteraction : SocketInteraction {
|
||||
private sealed class ListenInteraction : SocketInteraction {
|
||||
public PortConflictBehavior on_port_conflict {
|
||||
get;
|
||||
set;
|
||||
@@ -287,7 +227,7 @@ namespace Frida.Gadget {
|
||||
}
|
||||
}
|
||||
|
||||
private class ConnectInteraction : SocketInteraction, Json.Serializable {
|
||||
private sealed class ConnectInteraction : SocketInteraction, Json.Serializable {
|
||||
public string[]? acl {
|
||||
get;
|
||||
set;
|
||||
@@ -299,8 +239,6 @@ namespace Frida.Gadget {
|
||||
default = make_empty_json_object ();
|
||||
}
|
||||
|
||||
private ObjectClass klass = (ObjectClass) typeof (ConnectInteraction).class_ref ();
|
||||
|
||||
public bool deserialize_property (string property_name, out Value value, ParamSpec pspec, Json.Node property_node) {
|
||||
if (property_name == "parameters" && property_node.get_node_type () == Json.NodeType.OBJECT) {
|
||||
var v = Value (typeof (Json.Node));
|
||||
@@ -312,23 +250,9 @@ namespace Frida.Gadget {
|
||||
value = Value (pspec.value_type);
|
||||
return false;
|
||||
}
|
||||
|
||||
public unowned ParamSpec? find_property (string name) {
|
||||
return klass.find_property (name);
|
||||
}
|
||||
|
||||
public new Value get_property (ParamSpec pspec) {
|
||||
var val = Value (pspec.value_type);
|
||||
base.get_property (pspec.name, ref val);
|
||||
return val;
|
||||
}
|
||||
|
||||
public new void set_property (ParamSpec pspec, Value value) {
|
||||
base.set_property (pspec.name, value);
|
||||
}
|
||||
}
|
||||
|
||||
private class Location : Object {
|
||||
private sealed class Location : Object {
|
||||
public string executable_name {
|
||||
get;
|
||||
construct;
|
||||
@@ -481,6 +405,12 @@ namespace Frida.Gadget {
|
||||
|
||||
interceptor = Gum.Interceptor.obtain ();
|
||||
interceptor.begin_transaction ();
|
||||
|
||||
#if DARWIN
|
||||
if (mapped_range != null)
|
||||
Environment.ensure_debugger_breakpoints_only ();
|
||||
#endif
|
||||
|
||||
exceptor = Gum.Exceptor.obtain ();
|
||||
|
||||
try {
|
||||
@@ -700,6 +630,11 @@ namespace Frida.Gadget {
|
||||
controller = null;
|
||||
|
||||
exceptor = null;
|
||||
|
||||
#if DARWIN
|
||||
Environment.allow_stolen_breakpoints ();
|
||||
#endif
|
||||
|
||||
interceptor = null;
|
||||
}
|
||||
}
|
||||
@@ -751,7 +686,7 @@ namespace Frida.Gadget {
|
||||
|
||||
string config_data;
|
||||
try {
|
||||
FileUtils.get_contents (config_path, out config_data);
|
||||
load_asset_text (config_path, out config_data);
|
||||
} catch (FileError e) {
|
||||
if (e is FileError.NOENT)
|
||||
return new Config ();
|
||||
@@ -759,7 +694,7 @@ namespace Frida.Gadget {
|
||||
}
|
||||
|
||||
try {
|
||||
return Json.gobject_from_data (typeof (Config), config_data) as Config;
|
||||
return (Config) Json.gobject_from_data (typeof (Config), config_data);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid config: %s", e.message);
|
||||
}
|
||||
@@ -767,7 +702,7 @@ namespace Frida.Gadget {
|
||||
|
||||
private Config parse_config (string config_data) throws Error {
|
||||
try {
|
||||
return Json.gobject_from_data (typeof (Config), config_data) as Config;
|
||||
return (Config) Json.gobject_from_data (typeof (Config), config_data);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid config: %s", e.message);
|
||||
}
|
||||
@@ -775,21 +710,20 @@ namespace Frida.Gadget {
|
||||
|
||||
private Location detect_location (Gum.MemoryRange? mapped_range) {
|
||||
string? executable_name = null;
|
||||
string? executable_path = null;
|
||||
Gum.MemoryRange? executable_range = null;
|
||||
string? our_path = null;
|
||||
Gum.MemoryRange? our_range = mapped_range;
|
||||
|
||||
Gum.Address our_address = Gum.Address.from_pointer (Gum.strip_code_pointer ((void *) detect_location));
|
||||
|
||||
#if DARWIN
|
||||
Environment.detect_darwin_location_fields (our_address, ref executable_name, ref our_path, ref our_range);
|
||||
#else
|
||||
var index = 0;
|
||||
Gum.Process.enumerate_modules ((details) => {
|
||||
var range = details.range;
|
||||
|
||||
if (index == 0) {
|
||||
executable_name = details.name;
|
||||
executable_path = details.path;
|
||||
executable_range = details.range;
|
||||
}
|
||||
|
||||
if (mapped_range != null)
|
||||
@@ -805,6 +739,7 @@ namespace Frida.Gadget {
|
||||
|
||||
return true;
|
||||
});
|
||||
#endif
|
||||
|
||||
assert (our_range != null);
|
||||
|
||||
@@ -988,7 +923,7 @@ namespace Frida.Gadget {
|
||||
}
|
||||
}
|
||||
|
||||
private class ScriptRunner : BaseController {
|
||||
private sealed class ScriptRunner : BaseController {
|
||||
private ScriptEngine engine;
|
||||
private Script script;
|
||||
|
||||
@@ -1036,7 +971,7 @@ namespace Frida.Gadget {
|
||||
}
|
||||
}
|
||||
|
||||
private class ScriptDirectoryRunner : BaseController {
|
||||
private sealed class ScriptDirectoryRunner : BaseController {
|
||||
public string directory_path {
|
||||
get;
|
||||
construct;
|
||||
@@ -1226,7 +1161,7 @@ namespace Frida.Gadget {
|
||||
private ScriptConfig load_config (string path) throws Error {
|
||||
string data;
|
||||
try {
|
||||
FileUtils.get_contents (path, out data);
|
||||
load_asset_text (path, out data);
|
||||
} catch (FileError e) {
|
||||
if (e is FileError.NOENT)
|
||||
return new ScriptConfig ();
|
||||
@@ -1234,15 +1169,21 @@ namespace Frida.Gadget {
|
||||
}
|
||||
|
||||
try {
|
||||
return Json.gobject_from_data (typeof (ScriptConfig), data) as ScriptConfig;
|
||||
return (ScriptConfig) Json.gobject_from_data (typeof (ScriptConfig), data);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid config: %s", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class Script : Object, RpcPeer {
|
||||
private const uint8 QUICKJS_BYTECODE_MAGIC = 0x02;
|
||||
private sealed class Script : Object, RpcPeer {
|
||||
private const uint8 QUICKJS_BYTECODE_MAGIC =
|
||||
#if BIG_ENDIAN
|
||||
0x42
|
||||
#else
|
||||
0x02
|
||||
#endif
|
||||
;
|
||||
|
||||
public enum ChangeBehavior {
|
||||
IGNORE,
|
||||
@@ -1349,9 +1290,9 @@ namespace Frida.Gadget {
|
||||
try {
|
||||
var path = this.path;
|
||||
|
||||
uint8[] contents;
|
||||
Bytes contents;
|
||||
try {
|
||||
FileUtils.get_data (path, out contents);
|
||||
load_asset_bytes (path, out contents);
|
||||
} catch (FileError e) {
|
||||
throw new Error.INVALID_ARGUMENT ("%s", e.message);
|
||||
}
|
||||
@@ -1360,11 +1301,10 @@ namespace Frida.Gadget {
|
||||
options.name = Path.get_basename (path).split (".", 2)[0];
|
||||
|
||||
ScriptEngine.ScriptInstance instance;
|
||||
if (contents.length > 0 && contents[0] == QUICKJS_BYTECODE_MAGIC) {
|
||||
instance = yield engine.create_script (null, new Bytes (contents), options);
|
||||
} else {
|
||||
instance = yield engine.create_script ((string) contents, null, options);
|
||||
}
|
||||
if (contents.length > 0 && contents[0] == QUICKJS_BYTECODE_MAGIC)
|
||||
instance = yield engine.create_script (null, contents, options);
|
||||
else
|
||||
instance = yield engine.create_script ((string) contents.get_data (), null, options);
|
||||
|
||||
if (id.handle != 0)
|
||||
yield engine.destroy_script (id);
|
||||
@@ -1381,7 +1321,7 @@ namespace Frida.Gadget {
|
||||
var stage = new Json.Node.alloc ().init_string ((peek_state () == State.CREATED) ? "early" : "late");
|
||||
|
||||
try {
|
||||
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, null);
|
||||
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, null, null);
|
||||
} catch (GLib.Error e) {
|
||||
}
|
||||
}
|
||||
@@ -1449,12 +1389,12 @@ namespace Frida.Gadget {
|
||||
return true;
|
||||
}
|
||||
|
||||
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
|
||||
engine.post_to_script (id, json);
|
||||
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
|
||||
engine.post_to_script (id, json, data);
|
||||
}
|
||||
}
|
||||
|
||||
private class ControlServer : BaseController {
|
||||
private sealed class ControlServer : BaseController {
|
||||
public EndpointParameters endpoint_params {
|
||||
get;
|
||||
construct;
|
||||
@@ -1497,7 +1437,8 @@ namespace Frida.Gadget {
|
||||
var endpoint_params = new EndpointParameters (interaction.address, interaction.port,
|
||||
parse_certificate (interaction.certificate, location), interaction.origin, auth_service, asset_root);
|
||||
|
||||
service = new WebService (endpoint_params, CONTROL, interaction.on_port_conflict);
|
||||
service = new WebService (endpoint_params, WebServiceFlavor.CONTROL, interaction.on_port_conflict,
|
||||
new TunnelInterfaceObserver ());
|
||||
service.incoming.connect (on_incoming_connection);
|
||||
yield service.start (io_cancellable);
|
||||
}
|
||||
@@ -1742,7 +1683,7 @@ namespace Frida.Gadget {
|
||||
}
|
||||
}
|
||||
|
||||
private class ControlChannel : Object, Peer, HostSession {
|
||||
private class ControlChannel : Object, Peer, HostSession, GadgetSession {
|
||||
public weak ControlServer parent {
|
||||
get;
|
||||
construct;
|
||||
@@ -1773,6 +1714,9 @@ namespace Frida.Gadget {
|
||||
HostSession host_session = this;
|
||||
registrations.add (connection.register_object (Frida.ObjectPath.HOST_SESSION, host_session));
|
||||
|
||||
GadgetSession gadget_session = this;
|
||||
registrations.add (connection.register_object (Frida.ObjectPath.GADGET_SESSION, gadget_session));
|
||||
|
||||
AuthenticationService null_auth = new NullAuthenticationService ();
|
||||
registrations.add (connection.register_object (Frida.ObjectPath.AUTHENTICATION_SERVICE, null_auth));
|
||||
} catch (IOError e) {
|
||||
@@ -1927,6 +1871,30 @@ namespace Frida.Gadget {
|
||||
throw new Error.NOT_SUPPORTED ("Unable to inject libraries when embedded");
|
||||
}
|
||||
|
||||
public async ChannelId open_channel (string address, Cancellable? cancellable) throws Error, IOError {
|
||||
throw new Error.NOT_SUPPORTED ("Unable to open channels when embedded");
|
||||
}
|
||||
|
||||
public async ServiceSessionId open_service (string address, Cancellable? cancellable) throws Error, IOError {
|
||||
throw new Error.NOT_SUPPORTED ("Unable to open services when embedded");
|
||||
}
|
||||
|
||||
public async void break_and_resume (Cancellable? cancellable) throws Error, IOError {
|
||||
#if DARWIN
|
||||
Environment.break_and_resume ();
|
||||
#else
|
||||
throw new Error.NOT_SUPPORTED ("This API is only applicable on Darwin");
|
||||
#endif
|
||||
}
|
||||
|
||||
public async void break_and_detach (Cancellable? cancellable) throws Error, IOError {
|
||||
#if DARWIN
|
||||
Environment.break_and_detach ();
|
||||
#else
|
||||
throw new Error.NOT_SUPPORTED ("This API is only applicable on Darwin");
|
||||
#endif
|
||||
}
|
||||
|
||||
private void validate_pid (uint pid) throws Error {
|
||||
if (pid != this_process.pid)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to act on other processes when embedded");
|
||||
@@ -1958,7 +1926,7 @@ namespace Frida.Gadget {
|
||||
}
|
||||
}
|
||||
|
||||
private class ClusterClient : BaseController {
|
||||
private sealed class ClusterClient : BaseController {
|
||||
public SocketConnectable connectable {
|
||||
get;
|
||||
construct;
|
||||
@@ -2075,6 +2043,60 @@ namespace Frida.Gadget {
|
||||
}
|
||||
#endif
|
||||
|
||||
private void load_asset_text (string filename, out string text) throws FileError {
|
||||
Bytes raw_contents;
|
||||
load_asset_bytes (filename, out raw_contents);
|
||||
|
||||
unowned string str = (string) raw_contents.get_data ();
|
||||
if (!str.validate ())
|
||||
throw new FileError.FAILED ("%s: invalid UTF-8", filename);
|
||||
|
||||
text = str;
|
||||
}
|
||||
|
||||
private void load_asset_bytes (string filename, out Bytes bytes) throws FileError {
|
||||
#if ANDROID
|
||||
if (maybe_load_asset_bytes_from_apk (filename, out bytes))
|
||||
return;
|
||||
#endif
|
||||
|
||||
uint8[] data;
|
||||
FileUtils.get_data (filename, out data);
|
||||
bytes = new Bytes.take ((owned) data);
|
||||
}
|
||||
|
||||
#if ANDROID
|
||||
private bool maybe_load_asset_bytes_from_apk (string filename, out Bytes contents) throws FileError {
|
||||
contents = null;
|
||||
|
||||
var tokens = filename.split ("!", 2);
|
||||
if (tokens.length != 2 || !tokens[0].has_suffix (".apk"))
|
||||
return false;
|
||||
unowned string apk_path = tokens[0];
|
||||
unowned string file_path = tokens[1];
|
||||
|
||||
var reader = Minizip.Reader.create ();
|
||||
try {
|
||||
if (reader.open_file (apk_path) != OK)
|
||||
throw new FileError.FAILED ("Unable to open APK");
|
||||
|
||||
if (reader.locate_entry (file_path[1:], true) != OK)
|
||||
throw new FileError.FAILED ("Unable to locate %s inside APK", file_path);
|
||||
|
||||
var size = reader.entry_save_buffer_length ();
|
||||
var data = new uint8[size + 1];
|
||||
if (reader.entry_save_buffer (data[:size]) != OK)
|
||||
throw new FileError.FAILED ("Unable to extract %s from APK", file_path);
|
||||
|
||||
contents = new Bytes.take ((owned) data);
|
||||
return true;
|
||||
} finally {
|
||||
reader.close ();
|
||||
Minizip.Reader.destroy (ref reader);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private Json.Node make_empty_json_object () {
|
||||
return new Json.Node.alloc ().init_object (new Json.Object ());
|
||||
}
|
||||
@@ -2108,6 +2130,14 @@ namespace Frida.Gadget {
|
||||
private extern bool has_objc_class (string name);
|
||||
|
||||
private extern void set_thread_name (string name);
|
||||
#if DARWIN
|
||||
private extern void detect_darwin_location_fields (Gum.Address our_address, ref string? executable_name,
|
||||
ref string? our_path, ref Gum.MemoryRange? our_range);
|
||||
private extern void ensure_debugger_breakpoints_only ();
|
||||
private extern void allow_stolen_breakpoints ();
|
||||
private extern void break_and_resume ();
|
||||
private extern void break_and_detach ();
|
||||
#endif
|
||||
}
|
||||
|
||||
private extern void log_info (string message);
|
||||
|
||||
@@ -29,6 +29,11 @@ if host_os_family == 'darwin'
|
||||
extra_link_args += '-Wl,-framework,Foundation'
|
||||
endif
|
||||
|
||||
if host_os == 'android'
|
||||
extra_vala_args += '--pkg=minizip'
|
||||
platform_deps += minizip_dep
|
||||
endif
|
||||
|
||||
if host_os_family == 'windows'
|
||||
if host_toolchain != 'microsoft'
|
||||
symfile = 'frida-gadget.symbols'
|
||||
@@ -60,7 +65,7 @@ raw_gadget = shared_library('frida-gadget-raw', gadget_sources,
|
||||
link_depends: extra_link_depends,
|
||||
vs_module_defs: 'frida-gadget.def',
|
||||
override_options: ['b_asneeded=true'],
|
||||
dependencies: [gio_dep, gee_dep, json_glib_dep, gum_dep, gumjs_dep, base_dep, tls_provider_dep, payload_dep] + platform_deps,
|
||||
dependencies: [gio_dep, gee_dep, json_glib_dep, gum_dep, gumjs_dep, base_dep, netif_dep, tls_provider_dep, payload_dep] + platform_deps,
|
||||
)
|
||||
|
||||
operations = [
|
||||
|
||||
@@ -2,6 +2,7 @@ if host_os == 'android'
|
||||
subdir('selinux')
|
||||
endif
|
||||
subdir('base')
|
||||
subdir('netif')
|
||||
subdir('pipe')
|
||||
subdir('payload')
|
||||
if have_local_backend
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
netif_sources = [
|
||||
'tunnel-interface-observer.vala',
|
||||
]
|
||||
|
||||
extra_vala_args = []
|
||||
extra_link_args = []
|
||||
|
||||
if host_os in ['ios', 'tvos']
|
||||
extra_vala_args += [
|
||||
'--pkg=corefoundation',
|
||||
'--pkg=darwin-gcd',
|
||||
'--pkg=darwin-systemconfiguration',
|
||||
]
|
||||
extra_link_args += '-Wl,-framework,SystemConfiguration'
|
||||
endif
|
||||
|
||||
netif = static_library('frida-netif', netif_sources,
|
||||
c_args: frida_component_cflags,
|
||||
vala_args: [base_vala_args, extra_vala_args],
|
||||
dependencies: [base_dep, gee_dep],
|
||||
)
|
||||
|
||||
netif_dep = declare_dependency(
|
||||
include_directories: include_directories('.'),
|
||||
link_args: extra_link_args,
|
||||
link_with: netif,
|
||||
dependencies: base_dep,
|
||||
)
|
||||
@@ -0,0 +1,99 @@
|
||||
public sealed class Frida.TunnelInterfaceObserver : Object, DynamicInterfaceObserver {
|
||||
#if IOS || TVOS
|
||||
private Gee.Map<string, DynamicInterface> interfaces = new Gee.HashMap<string, DynamicInterface> ();
|
||||
|
||||
private Darwin.SystemConfiguration.DynamicStore? store;
|
||||
private Darwin.GCD.DispatchQueue event_queue =
|
||||
new Darwin.GCD.DispatchQueue ("re.frida.endpoint-enumerator", Darwin.GCD.DispatchQueueAttr.SERIAL);
|
||||
|
||||
private MainContext? main_context;
|
||||
|
||||
public override void dispose () {
|
||||
if (store != null) {
|
||||
store.set_dispatch_queue (null);
|
||||
store = null;
|
||||
ref ();
|
||||
event_queue.dispatch_async (do_dispose);
|
||||
}
|
||||
|
||||
base.dispose ();
|
||||
}
|
||||
|
||||
private void do_dispose () {
|
||||
unref ();
|
||||
}
|
||||
|
||||
public void start () {
|
||||
main_context = MainContext.ref_thread_default ();
|
||||
|
||||
Darwin.SystemConfiguration.DynamicStoreContext context = { 0, };
|
||||
context.info = this;
|
||||
store = new Darwin.SystemConfiguration.DynamicStore (null, CoreFoundation.String.make ("Frida"),
|
||||
on_interfaces_changed_wrapper, context);
|
||||
|
||||
var pattern = CoreFoundation.String.make ("State:/Network/Interface/utun.*/IPv6");
|
||||
var patterns = new CoreFoundation.Array (null, ((CoreFoundation.Type[]) &pattern)[:1]);
|
||||
store.set_notification_keys (null, patterns);
|
||||
|
||||
store.set_dispatch_queue (event_queue);
|
||||
|
||||
var initial_keys = store.copy_key_list (pattern);
|
||||
if (initial_keys != null)
|
||||
handle_interface_changes (initial_keys);
|
||||
}
|
||||
|
||||
private static void on_interfaces_changed_wrapper (Darwin.SystemConfiguration.DynamicStore store,
|
||||
CoreFoundation.Array changed_keys, void * info) {
|
||||
unowned TunnelInterfaceObserver enumerator = (TunnelInterfaceObserver) info;
|
||||
enumerator.on_interfaces_changed (changed_keys);
|
||||
}
|
||||
|
||||
private void on_interfaces_changed (CoreFoundation.Array changed_keys) {
|
||||
schedule_on_frida_thread (() => {
|
||||
if (store != null)
|
||||
handle_interface_changes (changed_keys);
|
||||
return Source.REMOVE;
|
||||
});
|
||||
}
|
||||
|
||||
private void handle_interface_changes (CoreFoundation.Array changed_keys) {
|
||||
var addresses_str = CoreFoundation.String.make ("Addresses");
|
||||
|
||||
foreach (var key in CFArray.wrap<CoreFoundation.String> (changed_keys)) {
|
||||
string name = key.to_string ().split ("/")[3];
|
||||
|
||||
var val = (CoreFoundation.Dictionary) store.copy_value (key);
|
||||
if (val != null) {
|
||||
InetAddress? address = null;
|
||||
foreach (var raw_address in CFArray.wrap<CoreFoundation.String> (val[addresses_str])) {
|
||||
var str = raw_address.to_string ();
|
||||
bool is_reserved_ipv6_range = str.has_prefix ("fc") || str.has_prefix ("fd");
|
||||
bool is_tunnel = is_reserved_ipv6_range && str.has_suffix ("::1");
|
||||
if (is_tunnel) {
|
||||
address = new InetAddress.from_string (str);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (address != null && !interfaces.has_key (name)) {
|
||||
var iface = new DynamicInterface (name, address);
|
||||
interfaces[name] = iface;
|
||||
interface_attached (iface);
|
||||
}
|
||||
} else {
|
||||
DynamicInterface iface;
|
||||
if (interfaces.unset (name, out iface))
|
||||
interface_detached (iface);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void schedule_on_frida_thread (owned SourceFunc function) {
|
||||
var source = new IdleSource ();
|
||||
source.set_callback ((owned) function);
|
||||
source.attach (main_context);
|
||||
}
|
||||
#else
|
||||
public void start () {
|
||||
}
|
||||
#endif
|
||||
}
|
||||
+90
-52
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class ThreadIgnoreScope {
|
||||
public sealed class ThreadIgnoreScope {
|
||||
public enum Kind {
|
||||
APPLICATION_THREAD,
|
||||
FRIDA_THREAD
|
||||
@@ -43,49 +43,83 @@ namespace Frida {
|
||||
}
|
||||
|
||||
#if ANDROID
|
||||
public class ThreadCountCloaker : Object {
|
||||
public sealed class ThreadCountCloaker : Object {
|
||||
private GetOsThreadStat * get_os_thread_stat_slot;
|
||||
private static GetOsThreadStat old_get_os_thread_stat_impl;
|
||||
|
||||
private ReadFunc * read_slot;
|
||||
private static ReadFunc old_read_impl;
|
||||
|
||||
private static string expected_magic = "%u (".printf (Posix.getpid ());
|
||||
|
||||
[CCode (has_target = false)]
|
||||
private delegate ssize_t GetOsThreadStat (Posix.pid_t tid, void * buf, size_t count);
|
||||
|
||||
[CCode (has_target = false)]
|
||||
private delegate ssize_t ReadFunc (int fd, void * buf, size_t count);
|
||||
|
||||
construct {
|
||||
Gum.Module.enumerate_imports ("libart.so", imp => {
|
||||
if (imp.name == "read") {
|
||||
read_slot = (ReadFunc *) imp.slot;
|
||||
return false;
|
||||
var art = Gum.Process.find_module_by_name ("libart.so");
|
||||
if (art != null) {
|
||||
art.enumerate_imports (imp => {
|
||||
if (imp.name == "_ZN3art15GetOsThreadStatEiPcm" || imp.name == "_ZN3art15GetOsThreadStatEiPcj") {
|
||||
get_os_thread_stat_slot = (GetOsThreadStat *) imp.slot;
|
||||
} else if (imp.name == "read") {
|
||||
read_slot = (ReadFunc *) imp.slot;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (get_os_thread_stat_slot != null) {
|
||||
old_get_os_thread_stat_impl = (GetOsThreadStat) update_slot ((void **) get_os_thread_stat_slot,
|
||||
(void *) on_get_os_thread_stat);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (read_slot != null)
|
||||
old_read_impl = update_read_slot (on_read);
|
||||
if (read_slot != null) {
|
||||
old_read_impl = (ReadFunc) update_slot ((void **) read_slot, (void *) on_read);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
~ThreadCountCloaker () {
|
||||
if (read_slot != null)
|
||||
update_read_slot (old_read_impl);
|
||||
public override void dispose () {
|
||||
if (get_os_thread_stat_slot != null) {
|
||||
update_slot ((void **) get_os_thread_stat_slot, (void *) old_get_os_thread_stat_impl);
|
||||
}
|
||||
if (read_slot != null) {
|
||||
update_slot ((void **) read_slot, (void *) old_read_impl);
|
||||
}
|
||||
|
||||
base.dispose ();
|
||||
}
|
||||
|
||||
private ReadFunc update_read_slot (ReadFunc new_impl) {
|
||||
private static void * update_slot (void ** orig, void * new_impl) {
|
||||
Gum.PageProtection old_prot = READ;
|
||||
Gum.Memory.query_protection (read_slot, out old_prot);
|
||||
Gum.Memory.query_protection (orig, out old_prot);
|
||||
|
||||
bool is_writable = (old_prot & Gum.PageProtection.WRITE) != 0;
|
||||
if (!is_writable)
|
||||
Gum.mprotect (read_slot, sizeof (void *), old_prot | WRITE);
|
||||
Gum.mprotect (orig, sizeof (void *), old_prot | WRITE);
|
||||
|
||||
ReadFunc old_impl = *read_slot;
|
||||
*read_slot = new_impl;
|
||||
void * old_impl = *orig;
|
||||
*orig = new_impl;
|
||||
|
||||
if (!is_writable)
|
||||
Gum.mprotect (read_slot, sizeof (void *), old_prot);
|
||||
Gum.mprotect (orig, sizeof (void *), old_prot);
|
||||
|
||||
return old_impl;
|
||||
}
|
||||
|
||||
private static ssize_t on_get_os_thread_stat (Posix.pid_t tid, void * buf, size_t count) {
|
||||
ssize_t n = old_get_os_thread_stat_impl (tid, buf, count);
|
||||
|
||||
if (tid == Posix.getpid ()) {
|
||||
try {
|
||||
n = adjust_thread_count (buf, n, count);
|
||||
} catch (FileError e) {
|
||||
}
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
private static ssize_t on_read (int fd, void * buf, size_t count) {
|
||||
var n = old_read_impl (fd, buf, count);
|
||||
if (n <= 0)
|
||||
@@ -98,32 +132,36 @@ namespace Frida {
|
||||
if (!file_descriptor_is_proc_self_stat (fd))
|
||||
return n;
|
||||
|
||||
unowned string raw_str = (string) buf;
|
||||
string str = raw_str.substring (0, n);
|
||||
|
||||
MatchInfo info;
|
||||
if (!/^(\d+ \(.+\)(?: [^ ]+){17}) \d+ (.+)/s.match (str, 0, out info))
|
||||
return n;
|
||||
string fields_before = info.fetch (1);
|
||||
string fields_after = info.fetch (2);
|
||||
|
||||
// We cannot simply use the value we got from the kernel and subtract the number of cloaked threads,
|
||||
// as there's a chance the total may have changed in the last moment.
|
||||
uint num_uncloaked_threads = query_num_uncloaked_threads ();
|
||||
|
||||
string adjusted_str = "%s %u %s".printf (fields_before, num_uncloaked_threads, fields_after);
|
||||
|
||||
var adjusted_length = adjusted_str.length;
|
||||
if (adjusted_length > count)
|
||||
return n;
|
||||
Memory.copy (buf, adjusted_str, adjusted_length);
|
||||
n = adjusted_length;
|
||||
n = adjust_thread_count (buf, n, count);
|
||||
} catch (FileError e) {
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
private static ssize_t adjust_thread_count (void * buf, ssize_t n, size_t count) throws FileError {
|
||||
unowned string raw_str = (string) buf;
|
||||
string str = raw_str.substring (0, n);
|
||||
|
||||
MatchInfo info;
|
||||
if (!/^(\d+ \(.+\)(?: [^ ]+){17}) \d+ (.+)/s.match (str, 0, out info))
|
||||
return n;
|
||||
string fields_before = info.fetch (1);
|
||||
string fields_after = info.fetch (2);
|
||||
|
||||
// We cannot simply use the value we got from the kernel and subtract the number of cloaked threads,
|
||||
// as there's a chance the total may have changed in the last moment.
|
||||
uint num_uncloaked_threads = query_num_uncloaked_threads ();
|
||||
|
||||
string adjusted_str = "%s %u %s".printf (fields_before, num_uncloaked_threads, fields_after);
|
||||
|
||||
var adjusted_length = adjusted_str.length;
|
||||
if (adjusted_length > count)
|
||||
return n;
|
||||
Memory.copy (buf, adjusted_str, adjusted_length);
|
||||
return adjusted_length;
|
||||
}
|
||||
|
||||
private static bool file_content_might_be_from_proc_self_stat (void * content, ssize_t size) {
|
||||
if (size < expected_magic.length)
|
||||
return false;
|
||||
@@ -153,12 +191,12 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
#else
|
||||
public class ThreadCountCloaker : Object {
|
||||
public sealed class ThreadCountCloaker : Object {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if LINUX
|
||||
public class ThreadListCloaker : Object, DirListFilter {
|
||||
public sealed class ThreadListCloaker : Object, DirListFilter {
|
||||
private string our_dir_by_pid;
|
||||
private DirListCloaker cloaker;
|
||||
|
||||
@@ -177,7 +215,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
public class FDListCloaker : Object, DirListFilter {
|
||||
public sealed class FDListCloaker : Object, DirListFilter {
|
||||
private string our_dir_by_pid;
|
||||
private DirListCloaker cloaker;
|
||||
|
||||
@@ -196,7 +234,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
private class DirListCloaker : Object {
|
||||
private sealed class DirListCloaker : Object {
|
||||
public weak DirListFilter filter {
|
||||
get;
|
||||
construct;
|
||||
@@ -212,34 +250,34 @@ namespace Frida {
|
||||
construct {
|
||||
var interceptor = Gum.Interceptor.obtain ();
|
||||
|
||||
unowned string libc = Gum.Process.query_libc_name ();
|
||||
var libc = Gum.Process.get_libc_module ();
|
||||
|
||||
var open_listener = new OpenDirListener (this);
|
||||
listeners.add (open_listener);
|
||||
interceptor.attach ((void *) Gum.Module.find_export_by_name (libc, "opendir"), open_listener);
|
||||
interceptor.attach ((void *) libc.find_export_by_name ("opendir"), open_listener);
|
||||
|
||||
var close_listener = new CloseDirListener (this);
|
||||
listeners.add (close_listener);
|
||||
interceptor.attach ((void *) Gum.Module.find_export_by_name (libc, "closedir"), close_listener);
|
||||
interceptor.attach ((void *) libc.find_export_by_name ("closedir"), close_listener);
|
||||
|
||||
var readdir_impl = Gum.Module.find_export_by_name (libc, "readdir");
|
||||
var readdir_impl = libc.find_export_by_name ("readdir");
|
||||
var readdir_listener = new ReadDirListener (this, LEGACY);
|
||||
listeners.add (readdir_listener);
|
||||
interceptor.attach ((void *) readdir_impl, readdir_listener);
|
||||
|
||||
var readdir64_impl = Gum.Module.find_export_by_name (libc, "readdir64");
|
||||
var readdir64_impl = libc.find_export_by_name ("readdir64");
|
||||
if (readdir64_impl != 0 && readdir64_impl != readdir_impl) {
|
||||
var listener = new ReadDirListener (this, MODERN);
|
||||
listeners.add (listener);
|
||||
interceptor.attach ((void *) readdir64_impl, listener);
|
||||
}
|
||||
|
||||
var readdir_r_impl = Gum.Module.find_export_by_name (libc, "readdir_r");
|
||||
var readdir_r_impl = libc.find_export_by_name ("readdir_r");
|
||||
var readdir_r_listener = new ReadDirRListener (this, LEGACY);
|
||||
listeners.add (readdir_r_listener);
|
||||
interceptor.attach ((void *) readdir_r_impl, readdir_r_listener);
|
||||
|
||||
var readdir64_r_impl = Gum.Module.find_export_by_name (libc, "readdir64_r");
|
||||
var readdir64_r_impl = libc.find_export_by_name ("readdir64_r");
|
||||
if (readdir64_r_impl != 0 && readdir64_r_impl != readdir_r_impl) {
|
||||
var listener = new ReadDirRListener (this, MODERN);
|
||||
listeners.add (listener);
|
||||
@@ -464,10 +502,10 @@ namespace Frida {
|
||||
public abstract bool matches_file (string name);
|
||||
}
|
||||
#else
|
||||
public class ThreadListCloaker : Object {
|
||||
public sealed class ThreadListCloaker : Object {
|
||||
}
|
||||
|
||||
public class FDListCloaker : Object {
|
||||
public sealed class FDListCloaker : Object {
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class ExitMonitor : Object, Gum.InvocationListener {
|
||||
public sealed class ExitMonitor : Object, Gum.InvocationListener {
|
||||
public weak ExitHandler handler {
|
||||
get;
|
||||
construct;
|
||||
@@ -32,16 +32,17 @@ namespace Frida {
|
||||
unowned Gum.InvocationListener listener = this;
|
||||
|
||||
#if WINDOWS
|
||||
interceptor.attach ((void *) Gum.Module.find_export_by_name ("kernel32.dll", "ExitProcess"), listener);
|
||||
interceptor.attach ((void *) Gum.Process.find_module_by_name ("kernel32.dll").find_export_by_name ("ExitProcess"),
|
||||
listener);
|
||||
#else
|
||||
unowned string libc = Gum.Process.query_libc_name ();
|
||||
var libc = Gum.Process.get_libc_module ();
|
||||
const string[] apis = {
|
||||
"exit",
|
||||
"_exit",
|
||||
"abort",
|
||||
};
|
||||
foreach (var symbol in apis) {
|
||||
interceptor.attach ((void *) Gum.Module.find_export_by_name (libc, symbol), listener);
|
||||
interceptor.attach ((void *) libc.find_export_by_name (symbol), listener);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace Frida {
|
||||
#if WINDOWS
|
||||
public class FileDescriptorGuard : Object {
|
||||
public sealed class FileDescriptorGuard : Object {
|
||||
public Gum.MemoryRange agent_range {
|
||||
get;
|
||||
construct;
|
||||
@@ -11,7 +11,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
#else
|
||||
public class FileDescriptorGuard : Object {
|
||||
public sealed class FileDescriptorGuard : Object {
|
||||
public Gum.MemoryRange agent_range {
|
||||
get;
|
||||
construct;
|
||||
@@ -26,7 +26,7 @@ namespace Frida {
|
||||
construct {
|
||||
var interceptor = Gum.Interceptor.obtain ();
|
||||
|
||||
var close = Gum.Module.find_export_by_name (Gum.Process.query_libc_name (), "close");
|
||||
var close = Gum.Process.get_libc_module ().find_export_by_name ("close");
|
||||
close_listener = new CloseListener (this);
|
||||
interceptor.attach ((void *) close, close_listener);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace Frida {
|
||||
#if WINDOWS
|
||||
public class FileDescriptorTablePadder {
|
||||
public sealed class FileDescriptorTablePadder {
|
||||
public static FileDescriptorTablePadder obtain () {
|
||||
return new FileDescriptorTablePadder ();
|
||||
}
|
||||
@@ -9,7 +9,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
#else
|
||||
public class FileDescriptorTablePadder {
|
||||
public sealed class FileDescriptorTablePadder {
|
||||
private const int MIN_TABLE_SIZE = 32;
|
||||
|
||||
private static unowned FileDescriptorTablePadder shared_instance = null;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace Frida {
|
||||
#if WINDOWS
|
||||
public class ForkMonitor : Object {
|
||||
public sealed class ForkMonitor : Object {
|
||||
public weak ForkHandler handler {
|
||||
get;
|
||||
construct;
|
||||
@@ -11,7 +11,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
#else
|
||||
public class ForkMonitor : Object, Gum.InvocationListener {
|
||||
public sealed class ForkMonitor : Object, Gum.InvocationListener {
|
||||
public weak ForkHandler handler {
|
||||
get;
|
||||
construct;
|
||||
@@ -45,9 +45,9 @@ namespace Frida {
|
||||
}
|
||||
|
||||
static construct {
|
||||
unowned string libc = Gum.Process.query_libc_name ();
|
||||
fork_impl = (void *) Gum.Module.find_export_by_name (libc, "fork");
|
||||
vfork_impl = (void *) Gum.Module.find_export_by_name (libc, "vfork");
|
||||
var libc = Gum.Process.get_libc_module ();
|
||||
fork_impl = (void *) libc.find_export_by_name ("fork");
|
||||
vfork_impl = (void *) libc.find_export_by_name ("vfork");
|
||||
}
|
||||
|
||||
construct {
|
||||
@@ -61,15 +61,21 @@ namespace Frida {
|
||||
string cmdline;
|
||||
FileUtils.get_contents ("/proc/self/cmdline", out cmdline);
|
||||
if (cmdline == "zygote" || cmdline == "zygote64" || cmdline == "usap32" || cmdline == "usap64") {
|
||||
var set_argv0 = (void *) Gum.Module.find_export_by_name ("libandroid_runtime.so", "_Z27android_os_Process_setArgV0P7_JNIEnvP8_jobjectP8_jstring");
|
||||
if (set_argv0 != null) {
|
||||
interceptor.attach (set_argv0, listener, (void *) HookId.SET_ARGV0);
|
||||
child_recovery_behavior = DEFERRED_UNTIL_SET_ARGV0;
|
||||
var runtime = Gum.Process.find_module_by_name ("libandroid_runtime.so");
|
||||
if (runtime != null) {
|
||||
var set_argv0 = (void *) runtime.find_export_by_name ("_Z27android_os_Process_setArgV0P7_JNIEnvP8_jobjectP8_jstring");
|
||||
if (set_argv0 != null) {
|
||||
interceptor.attach (set_argv0, listener, (void *) HookId.SET_ARGV0);
|
||||
child_recovery_behavior = DEFERRED_UNTIL_SET_ARGV0;
|
||||
}
|
||||
}
|
||||
|
||||
var setcontext = (void *) Gum.Module.find_export_by_name ("libselinux.so", "selinux_android_setcontext");
|
||||
if (setcontext != null)
|
||||
interceptor.attach (setcontext, listener, (void *) HookId.SET_CTX);
|
||||
var selinux = Gum.Process.find_module_by_name ("libselinux.so");
|
||||
if (selinux != null) {
|
||||
var setcontext = (void *) selinux.find_export_by_name ("selinux_android_setcontext");
|
||||
if (setcontext != null)
|
||||
interceptor.attach (setcontext, listener, (void *) HookId.SET_CTX);
|
||||
}
|
||||
}
|
||||
} catch (FileError e) {
|
||||
}
|
||||
|
||||
@@ -25,6 +25,24 @@ frida_run_atexit_handlers (void)
|
||||
{
|
||||
}
|
||||
|
||||
# ifdef HAVE_ASAN
|
||||
|
||||
__attribute__ ((constructor)) static void
|
||||
frida_init_memory (void)
|
||||
{
|
||||
asm volatile ("");
|
||||
}
|
||||
|
||||
# ifndef HAVE_DARWIN
|
||||
__attribute__ ((destructor)) static void
|
||||
frida_deinit_memory (void)
|
||||
{
|
||||
asm volatile ("");
|
||||
}
|
||||
# endif
|
||||
|
||||
# endif
|
||||
|
||||
#else
|
||||
|
||||
#define FRIDA_SHIM_LOCK() gum_spinlock_acquire (&frida_shim_lock)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class PortalClient : Object, AgentSessionProvider {
|
||||
public sealed class PortalClient : Object, AgentSessionProvider {
|
||||
public signal void resume ();
|
||||
public signal void kill ();
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class ScriptEngine : Object {
|
||||
public sealed class ScriptEngine : Object {
|
||||
public signal void message_from_script (AgentScriptId script_id, string json, Bytes? data);
|
||||
public signal void message_from_debugger (AgentScriptId script_id, string message);
|
||||
|
||||
@@ -223,7 +223,7 @@ namespace Frida {
|
||||
source.attach (Gum.ScriptBackend.get_scheduler ().get_js_context ());
|
||||
}
|
||||
|
||||
public class ScriptInstance : Object, RpcPeer {
|
||||
public sealed class ScriptInstance : Object, RpcPeer {
|
||||
public signal void closed ();
|
||||
public signal void message (string json, Bytes? data);
|
||||
public signal void debug_message (string message);
|
||||
@@ -420,7 +420,7 @@ namespace Frida {
|
||||
var reason_value = new Json.Node.alloc ().init_string (reason.to_nick ());
|
||||
|
||||
try {
|
||||
yield rpc_client.call ("dispose", new Json.Node[] { reason_value }, null);
|
||||
yield rpc_client.call ("dispose", new Json.Node[] { reason_value }, null, null);
|
||||
} catch (GLib.Error e) {
|
||||
}
|
||||
|
||||
@@ -467,10 +467,10 @@ namespace Frida {
|
||||
this.debug_message (message);
|
||||
}
|
||||
|
||||
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
|
||||
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
|
||||
if (script == null)
|
||||
throw new Error.INVALID_OPERATION ("Script is destroyed");
|
||||
script.post (json);
|
||||
script.post (json, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class SpawnMonitor : Object, Gum.InvocationListener {
|
||||
public sealed class SpawnMonitor : Object, Gum.InvocationListener {
|
||||
public weak SpawnHandler handler {
|
||||
get;
|
||||
construct;
|
||||
@@ -38,21 +38,24 @@ namespace Frida {
|
||||
var interceptor = Gum.Interceptor.obtain ();
|
||||
|
||||
#if WINDOWS
|
||||
var create_process_internal = Gum.Module.find_export_by_name ("kernelbase.dll", "CreateProcessInternalW");
|
||||
if (create_process_internal == 0)
|
||||
create_process_internal = Gum.Module.find_export_by_name ("kernel32.dll", "CreateProcessInternalW");
|
||||
var kernelbase = Gum.Process.find_module_by_name ("kernelbase.dll");
|
||||
var create_process_internal = (kernelbase != null) ? kernelbase.find_export_by_name ("CreateProcessInternalW") : 0;
|
||||
if (create_process_internal == 0) {
|
||||
create_process_internal = Gum.Process.find_module_by_name ("kernel32.dll")
|
||||
.find_export_by_name ("CreateProcessInternalW");
|
||||
}
|
||||
assert (create_process_internal != 0);
|
||||
interceptor.attach ((void *) create_process_internal, this);
|
||||
#else
|
||||
unowned string libc = Gum.Process.query_libc_name ();
|
||||
var libc = Gum.Process.get_libc_module ();
|
||||
#if DARWIN
|
||||
posix_spawn = (PosixSpawnFunc) Gum.Module.find_export_by_name (libc, "posix_spawn");
|
||||
posix_spawnattr_init = (PosixSpawnAttrInitFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_init");
|
||||
posix_spawnattr_destroy = (PosixSpawnAttrDestroyFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_destroy");
|
||||
posix_spawnattr_getflags = (PosixSpawnAttrSetFlagsFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_getflags");
|
||||
posix_spawnattr_setflags = (PosixSpawnAttrSetFlagsFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_setflags");
|
||||
posix_spawn = (PosixSpawnFunc) libc.find_export_by_name ("posix_spawn");
|
||||
posix_spawnattr_init = (PosixSpawnAttrInitFunc) libc.find_export_by_name ("posix_spawnattr_init");
|
||||
posix_spawnattr_destroy = (PosixSpawnAttrDestroyFunc) libc.find_export_by_name ("posix_spawnattr_destroy");
|
||||
posix_spawnattr_getflags = (PosixSpawnAttrSetFlagsFunc) libc.find_export_by_name ("posix_spawnattr_getflags");
|
||||
posix_spawnattr_setflags = (PosixSpawnAttrSetFlagsFunc) libc.find_export_by_name ("posix_spawnattr_setflags");
|
||||
|
||||
execve = (void *) Gum.Module.find_export_by_name (libc, "execve");
|
||||
execve = (void *) libc.find_export_by_name ("execve");
|
||||
|
||||
interceptor.attach ((void *) posix_spawn, this);
|
||||
|
||||
@@ -60,10 +63,10 @@ namespace Frida {
|
||||
#else
|
||||
Gum.Address execve = 0;
|
||||
#if ANDROID
|
||||
execve = Gum.Module.find_symbol_by_name (libc, "__execve");
|
||||
execve = libc.find_symbol_by_name ("__execve");
|
||||
#endif
|
||||
if (execve == 0)
|
||||
execve = Gum.Module.find_export_by_name (libc, "execve");
|
||||
execve = libc.find_export_by_name ("execve");
|
||||
interceptor.attach ((void *) execve, this);
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace Frida {
|
||||
#if DARWIN
|
||||
public class ThreadSuspendMonitor : Object {
|
||||
public sealed class ThreadSuspendMonitor : Object {
|
||||
public weak ProcessInvader invader {
|
||||
get;
|
||||
construct;
|
||||
@@ -26,9 +26,10 @@ namespace Frida {
|
||||
construct {
|
||||
var interceptor = Gum.Interceptor.obtain ();
|
||||
|
||||
task_threads = (TaskThreadsFunc) Gum.Module.find_export_by_name (LIBSYSTEM_KERNEL, "task_threads");
|
||||
thread_suspend = (ThreadSuspendFunc) Gum.Module.find_export_by_name (LIBSYSTEM_KERNEL, "thread_suspend");
|
||||
thread_resume = (ThreadResumeFunc) Gum.Module.find_export_by_name (LIBSYSTEM_KERNEL, "thread_resume");
|
||||
var kernel = Gum.Process.find_module_by_name (LIBSYSTEM_KERNEL);
|
||||
task_threads = (TaskThreadsFunc) kernel.find_export_by_name ("task_threads");
|
||||
thread_suspend = (ThreadSuspendFunc) kernel.find_export_by_name ("thread_suspend");
|
||||
thread_resume = (ThreadResumeFunc) kernel.find_export_by_name ("thread_resume");
|
||||
|
||||
interceptor.replace ((void *) task_threads, (void *) replacement_task_threads, this);
|
||||
interceptor.replace ((void *) thread_suspend, (void *) replacement_thread_suspend, this);
|
||||
@@ -130,7 +131,7 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
#else
|
||||
public class ThreadSuspendMonitor : Object {
|
||||
public sealed class ThreadSuspendMonitor : Object {
|
||||
public weak ProcessInvader invader {
|
||||
get;
|
||||
construct;
|
||||
|
||||
@@ -55,6 +55,7 @@ struct _FridaUnwindHookState
|
||||
gpointer set_info_original;
|
||||
void (* set_info) (gpointer cursor, gint is_return_address);
|
||||
gpointer (* get_reg) (gpointer cursor, gint reg);
|
||||
GumInterceptor * interceptor;
|
||||
};
|
||||
|
||||
#if __has_feature (ptrauth_calls)
|
||||
@@ -97,7 +98,6 @@ _frida_unwind_sitter_hook_libunwind (void)
|
||||
#if GLIB_SIZEOF_VOID_P == 8
|
||||
gpointer * set_info_slot;
|
||||
gpointer get_reg_impl;
|
||||
GumInterceptor * interceptor;
|
||||
|
||||
if (state != NULL)
|
||||
return;
|
||||
@@ -121,8 +121,9 @@ _frida_unwind_sitter_hook_libunwind (void)
|
||||
state->set_info = FRIDA_RESIGN_PTR (state->set_info_original);
|
||||
state->get_reg = FRIDA_RESIGN_PTR (get_reg_impl);
|
||||
|
||||
interceptor = gum_interceptor_obtain ();
|
||||
if (gum_interceptor_replace (interceptor, state->set_info_original, frida_unwind_cursor_set_info_replacement, NULL, NULL)
|
||||
state->interceptor = gum_interceptor_obtain ();
|
||||
|
||||
if (gum_interceptor_replace (state->interceptor, state->set_info_original, frida_unwind_cursor_set_info_replacement, NULL, NULL)
|
||||
!= GUM_REPLACE_OK)
|
||||
goto unsupported_version;
|
||||
|
||||
@@ -137,13 +138,12 @@ unsupported_version:
|
||||
void
|
||||
_frida_unwind_sitter_unhook_libunwind (void)
|
||||
{
|
||||
GumInterceptor * interceptor;
|
||||
|
||||
if (state == NULL)
|
||||
return;
|
||||
|
||||
interceptor = gum_interceptor_obtain ();
|
||||
gum_interceptor_revert (interceptor, state->set_info_original);
|
||||
gum_interceptor_revert (state->interceptor, state->set_info_original);
|
||||
|
||||
g_object_unref (state->interceptor);
|
||||
|
||||
g_slice_free (FridaUnwindHookState, state);
|
||||
state = NULL;
|
||||
@@ -300,6 +300,7 @@ static gpointer
|
||||
frida_find_vtable (void)
|
||||
{
|
||||
GumAddress result = 0;
|
||||
GumModule * libunwind;
|
||||
GumAddress export;
|
||||
uint64_t address;
|
||||
G_GNUC_UNUSED cs_err err;
|
||||
@@ -309,11 +310,15 @@ frida_find_vtable (void)
|
||||
size_t size;
|
||||
const size_t max_size = 2048;
|
||||
|
||||
export = gum_module_find_export_by_name (FRIDA_LIBUNWIND_PATH, "unw_init_local");
|
||||
libunwind = gum_process_find_module_by_name (FRIDA_LIBUNWIND_PATH);
|
||||
if (libunwind == NULL)
|
||||
goto beach;
|
||||
|
||||
export = gum_module_find_export_by_name (libunwind, "unw_init_local");
|
||||
if (export == 0)
|
||||
export = gum_module_find_export_by_name (FRIDA_LIBUNWIND_PATH, "_Unwind_RaiseException");
|
||||
export = gum_module_find_export_by_name (libunwind, "_Unwind_RaiseException");
|
||||
if (export == 0)
|
||||
return NULL;
|
||||
goto beach;
|
||||
export = gum_strip_code_address (export);
|
||||
address = export;
|
||||
|
||||
@@ -340,7 +345,7 @@ frida_find_vtable (void)
|
||||
GumMemoryRange bss_range;
|
||||
|
||||
bss_range.base_address = 0;
|
||||
gum_module_enumerate_sections (FRIDA_LIBUNWIND_PATH, (GumFoundSectionFunc) frida_find_bss_range, &bss_range);
|
||||
gum_module_enumerate_sections (libunwind, (GumFoundSectionFunc) frida_find_bss_range, &bss_range);
|
||||
|
||||
while (cs_disasm_iter (capstone, &code, &size, &address, insn))
|
||||
{
|
||||
@@ -404,6 +409,9 @@ frida_find_vtable (void)
|
||||
cs_free (insn, 1);
|
||||
cs_close (&capstone);
|
||||
|
||||
beach:
|
||||
g_clear_object (&libunwind);
|
||||
|
||||
return GSIZE_TO_POINTER (result);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace Frida {
|
||||
#if DARWIN
|
||||
public class UnwindSitter : Object {
|
||||
public sealed class UnwindSitter : Object {
|
||||
public weak ProcessInvader invader {
|
||||
get;
|
||||
construct;
|
||||
@@ -21,7 +21,7 @@ namespace Frida {
|
||||
var interceptor = Gum.Interceptor.obtain ();
|
||||
|
||||
dyld_find_unwind_sections = (DyldFindUnwindSectionsFunc)
|
||||
Gum.Module.find_export_by_name (LIBDYLD, "_dyld_find_unwind_sections");
|
||||
Gum.Process.find_module_by_name (LIBDYLD).find_export_by_name ("_dyld_find_unwind_sections");
|
||||
|
||||
interceptor.replace ((void *) dyld_find_unwind_sections, (void *) replacement_dyld_find_unwind_sections, this);
|
||||
|
||||
@@ -62,7 +62,7 @@ namespace Frida {
|
||||
public extern static void _unhook_libunwind ();
|
||||
}
|
||||
#else
|
||||
public class UnwindSitter : Object {
|
||||
public sealed class UnwindSitter : Object {
|
||||
public weak ProcessInvader invader {
|
||||
get;
|
||||
construct;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#include "pipe-glue.h"
|
||||
|
||||
#include "frida-tvos.h"
|
||||
|
||||
#include "pipe-glue.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class PipeTransport : Object {
|
||||
public sealed class PipeTransport : Object {
|
||||
public string local_address {
|
||||
get;
|
||||
construct;
|
||||
@@ -42,7 +42,7 @@ namespace Frida {
|
||||
}
|
||||
|
||||
#if WINDOWS
|
||||
public class WindowsPipe : IOStream {
|
||||
public sealed class WindowsPipe : IOStream {
|
||||
public string address {
|
||||
get;
|
||||
construct;
|
||||
|
||||
+216
-76
@@ -6,13 +6,17 @@ project('frida-core', 'vala', 'c', 'cpp',
|
||||
default_options: ['c_std=gnu99,c99', 'cpp_std=c++17'],
|
||||
)
|
||||
|
||||
fs = import('fs')
|
||||
|
||||
if not meson.get_compiler('vala').version().endswith('-frida')
|
||||
error('''Incompatible Vala compiler detected.
|
||||
|
||||
Frida currently relies on features not yet upstream. Grab the Frida-optimized
|
||||
Vala compiler from:
|
||||
Vala sources from:
|
||||
|
||||
https://github.com/frida/vala''')
|
||||
https://github.com/frida/vala
|
||||
|
||||
and compile them with Meson.''')
|
||||
endif
|
||||
|
||||
c_languages = ['c', 'cpp']
|
||||
@@ -20,7 +24,7 @@ cc = meson.get_compiler('c')
|
||||
cpp = meson.get_compiler('cpp')
|
||||
|
||||
releng = meson.global_source_root() / 'releng'
|
||||
if not import('fs').exists(releng)
|
||||
if not fs.exists(releng)
|
||||
releng = meson.project_source_root() / 'releng'
|
||||
endif
|
||||
|
||||
@@ -92,11 +96,12 @@ else
|
||||
host_arch = host_machine.cpu_family()
|
||||
host_abi = host_arch
|
||||
endif
|
||||
gumjs_archs = {
|
||||
'x86': 'ia32',
|
||||
'x86_64': 'x64',
|
||||
}
|
||||
host_arch_gumjs = gumjs_archs.get(host_arch, host_arch)
|
||||
if cc.sizeof('void *') == 8
|
||||
host_cpu_mode = '64'
|
||||
else
|
||||
host_cpu_mode = '32'
|
||||
endif
|
||||
host_docks_mobile_devices = host_os in ['windows', 'macos', 'linux'] and host_cpu_mode == '64'
|
||||
|
||||
if host_os_family == 'darwin'
|
||||
c_languages += ['objc', 'objcpp']
|
||||
@@ -156,10 +161,12 @@ if host_os_family == 'darwin'
|
||||
endif
|
||||
endif
|
||||
|
||||
if cc.sizeof('void *') == 8
|
||||
host_cpu_mode = '64'
|
||||
else
|
||||
host_cpu_mode = '32'
|
||||
if host_machine.endian() == 'big'
|
||||
if host_abi in ['arm', 'armhf']
|
||||
host_abi = 'armbe8'
|
||||
elif host_abi == 'arm64'
|
||||
host_abi = 'arm64be'
|
||||
endif
|
||||
endif
|
||||
|
||||
if host_os_family == 'darwin' and host_arch == 'arm64'
|
||||
@@ -264,12 +271,14 @@ if host_os == 'linux'
|
||||
#endif
|
||||
'''
|
||||
if cc.compiles(glibc_src, name: 'compiling for glibc')
|
||||
cdata.set('HAVE_GLIBC', 1)
|
||||
libc = 'glibc'
|
||||
elif cc.compiles(uclibc_src, name: 'compiling for uClibc')
|
||||
cdata.set('HAVE_UCLIBC', 1)
|
||||
libc = 'uclibc'
|
||||
else
|
||||
cdata.set('HAVE_MUSL', 1)
|
||||
libc = 'musl'
|
||||
endif
|
||||
cdata.set('HAVE_' + libc.to_upper(), 1)
|
||||
vala_flags += '--define=' + libc.to_upper()
|
||||
endif
|
||||
|
||||
if get_option('b_sanitize') == 'address'
|
||||
@@ -311,7 +320,7 @@ gobject_dep = dependency('gobject-2.0')
|
||||
gmodule_dep = dependency('gmodule-2.0')
|
||||
gio_dep = dependency('gio-2.0')
|
||||
gee_dep = dependency('gee-0.8', default_options: gee_options)
|
||||
json_glib_dep = dependency('json-glib-1.0', default_options: [
|
||||
json_glib_dep = dependency('json-glib-1.0', version: '>=1.8', default_options: [
|
||||
'introspection=disabled',
|
||||
'gtk_doc=disabled',
|
||||
'tests=false',
|
||||
@@ -335,6 +344,7 @@ quickjs_dep = dependency('quickjs', required: get_option('barebone_backend'), de
|
||||
'atomics=disabled',
|
||||
'stack_check=disabled',
|
||||
])
|
||||
lzfse_dep = dependency('lzfse', required: get_option('barebone_backend'))
|
||||
|
||||
native_glib_dep = dependency('glib-2.0', version: '>=2.74', native: true, default_options: glib_options)
|
||||
native_gio_dep = dependency('gio-2.0', native: true)
|
||||
@@ -347,15 +357,112 @@ else
|
||||
gio_unix_dep = dependency('gio-unix-2.0')
|
||||
endif
|
||||
|
||||
if host_os == 'android'
|
||||
minizip_dep = dependency('minizip', required: false, default_options: [
|
||||
'zlib=enabled',
|
||||
'lzma=disabled',
|
||||
])
|
||||
endif
|
||||
|
||||
if host_toolchain == 'microsoft'
|
||||
lib = find_program('lib')
|
||||
ar = ''
|
||||
nm = ''
|
||||
ranlib = ''
|
||||
strip = ''
|
||||
else
|
||||
lib = ''
|
||||
ar = find_program('ar')
|
||||
nm = find_program('nm')
|
||||
ranlib = find_program('ranlib')
|
||||
strip = find_program('strip')
|
||||
endif
|
||||
if host_os_family != 'windows'
|
||||
if host_os_family == 'darwin'
|
||||
readelf = ''
|
||||
otool = find_program('otool')
|
||||
libtool = find_program('libtool')
|
||||
else
|
||||
readelf = find_program('readelf')
|
||||
otool = ''
|
||||
libtool = ''
|
||||
endif
|
||||
else
|
||||
readelf = ''
|
||||
otool = ''
|
||||
libtool = ''
|
||||
endif
|
||||
if host_os_family == 'darwin'
|
||||
install_name_tool = find_program('install_name_tool')
|
||||
lipo = find_program('lipo')
|
||||
codesign = find_program('codesign')
|
||||
else
|
||||
install_name_tool = ''
|
||||
lipo = ''
|
||||
codesign = ''
|
||||
endif
|
||||
|
||||
have_local_backend = get_option('local_backend').allowed()
|
||||
have_fruity_backend = get_option('fruity_backend').allowed()
|
||||
have_droidy_backend = get_option('droidy_backend').allowed()
|
||||
have_socket_backend = get_option('socket_backend').allowed()
|
||||
have_barebone_backend = quickjs_dep.found()
|
||||
have_compiler_backend = get_option('compiler_backend') \
|
||||
.disable_if(not have_local_backend, error_message: 'compiler backend requires the local backend for script execution') \
|
||||
.disable_auto_if(host_os == 'watchos') \
|
||||
have_fruity_backend = get_option('fruity_backend') \
|
||||
.disable_auto_if(not host_docks_mobile_devices) \
|
||||
.allowed()
|
||||
have_droidy_backend = get_option('droidy_backend') \
|
||||
.disable_auto_if(not host_docks_mobile_devices) \
|
||||
.allowed()
|
||||
have_socket_backend = get_option('socket_backend').allowed()
|
||||
have_barebone_backend = get_option('barebone_backend') \
|
||||
.disable_if(not (quickjs_dep.found() and lzfse_dep.found())) \
|
||||
.disable_auto_if(not host_docks_mobile_devices) \
|
||||
.allowed()
|
||||
compiler_backend_opt = get_option('compiler_backend') \
|
||||
.disable_auto_if(host_os == 'watchos')
|
||||
have_compiler_backend = false
|
||||
if compiler_backend_opt.allowed()
|
||||
go = find_program('go', native: true, required: false)
|
||||
if go.found()
|
||||
message('Detecting cgo availability')
|
||||
detect_output = run_command(
|
||||
[
|
||||
python,
|
||||
files('tools' / 'cgo' / 'detect.py'),
|
||||
go,
|
||||
host_os,
|
||||
host_abi,
|
||||
shlib_suffix,
|
||||
cc.get_id(),
|
||||
'>>>', cc.cmd_array(), '<<<',
|
||||
'>>>', ar, '<<<',
|
||||
'>>>', nm, '<<<',
|
||||
'>>>', ranlib, '<<<',
|
||||
],
|
||||
capture: true,
|
||||
check: true
|
||||
).stdout()
|
||||
lines = detect_output.split('\n')
|
||||
status = lines[0]
|
||||
if status == 'ok'
|
||||
have_compiler_backend = true
|
||||
tokens = lines[1].split(' ')
|
||||
go_mode = tokens[0]
|
||||
go_config = tokens[1]
|
||||
compiler_backend_static_compilation = go_mode == 'c-archive'
|
||||
if compiler_backend_static_compilation
|
||||
vala_flags += '--define=COMPILER_BACKEND_STATIC_COMPILATION'
|
||||
endif
|
||||
else
|
||||
error_message = lines[1]
|
||||
if compiler_backend_opt.enabled()
|
||||
error(error_message)
|
||||
else
|
||||
warning(f'Building without Compiler backend: @error_message@')
|
||||
endif
|
||||
endif
|
||||
elif compiler_backend_opt.enabled()
|
||||
error('Need Go >= 1.24 to build the Compiler backend powered by ESBuild and typescript-go')
|
||||
else
|
||||
warning('Building without Compiler backend: Go >= 1.24 not found')
|
||||
endif
|
||||
endif
|
||||
|
||||
build_gadget = get_option('gadget') \
|
||||
.disable_auto_if(meson.is_subproject()) \
|
||||
@@ -394,7 +501,7 @@ foreach b : [['local', have_local_backend],
|
||||
endif
|
||||
endforeach
|
||||
|
||||
if have_barebone_backend or have_compiler_backend
|
||||
if host_os_family == 'darwin' or host_os == 'android' or have_barebone_backend or have_compiler_backend
|
||||
node = find_program('node', version: '>=18.0.0', native: true, required: false)
|
||||
if not node.found()
|
||||
error('Need Node.js >= 18.0.0 to process JavaScript code at build time')
|
||||
@@ -411,9 +518,8 @@ if gi_dep.found()
|
||||
else
|
||||
girdir = get_option('prefix') / get_option('datadir') / 'gir-1.0'
|
||||
endif
|
||||
uninstalled_girdir = meson.current_build_dir() / 'src'
|
||||
|
||||
vapidir = get_option('datadir') / 'vala' / 'vapi'
|
||||
vapidir = get_option('prefix') / get_option('datadir') / 'vala' / 'vapi'
|
||||
|
||||
gum_vala_args = [
|
||||
'--pkg=frida-gum-1.0',
|
||||
@@ -425,23 +531,56 @@ gumjs_inspector_vala_args = ['--pkg=frida-gumjs-inspector-1.0', gum_vala_args]
|
||||
have_v8 = gumjs_dep.get_variable('gumjs_v8') == 'enabled'
|
||||
if have_v8
|
||||
vala_flags += ['--define=HAVE_V8']
|
||||
v8_mksnapshot = find_program('v8-mksnapshot-@0@-@1@'.format(host_os, host_abi), required: false)
|
||||
if not v8_mksnapshot.found()
|
||||
v8_mksnapshot = ''
|
||||
endif
|
||||
else
|
||||
v8_mksnapshot = ''
|
||||
endif
|
||||
|
||||
backend_deps_private = []
|
||||
backend_reqs_private = []
|
||||
backend_libs_private = []
|
||||
|
||||
openssl_options = [
|
||||
'cli=disabled',
|
||||
]
|
||||
if host_os_family == 'windows' and cc.get_argument_syntax() != 'msvc'
|
||||
openssl_options += 'asm=disabled'
|
||||
endif
|
||||
openssl_dep = dependency('openssl',
|
||||
required: have_fruity_backend or get_option('connectivity').enabled(),
|
||||
modules: cc.get_argument_syntax() == 'msvc' ? ['OpenSSL::SSL'] : [],
|
||||
default_options: openssl_options,
|
||||
)
|
||||
|
||||
if have_fruity_backend
|
||||
foreach dep : ['libnghttp2', 'libngtcp2', 'libngtcp2_crypto_quictls', 'libusb-1.0']
|
||||
backend_deps_private += dependency(dep)
|
||||
backend_reqs_private += dep
|
||||
endforeach
|
||||
|
||||
lwip_options = [
|
||||
'ipv4=disabled',
|
||||
'ipv6=enabled',
|
||||
'dns=disabled',
|
||||
'arp=disabled',
|
||||
'ethernet=enabled',
|
||||
]
|
||||
if optimize_for_prod
|
||||
lwip_options += 'lwip_debug=disabled'
|
||||
else
|
||||
lwip_options += 'lwip_debug=enabled'
|
||||
endif
|
||||
backend_deps_private += dependency('lwip', default_options: lwip_options)
|
||||
backend_reqs_private += 'lwip'
|
||||
endif
|
||||
|
||||
if quickjs_dep.found()
|
||||
backend_deps_private += quickjs_dep
|
||||
backend_reqs_private += 'quickjs'
|
||||
endif
|
||||
|
||||
if lzfse_dep.found()
|
||||
backend_deps_private += lzfse_dep
|
||||
backend_reqs_private += 'lzfse'
|
||||
endif
|
||||
|
||||
if host_os_family == 'linux' and cc.has_function('openpty', prefix: '#include <pty.h>')
|
||||
vala_flags += '--define=HAVE_OPENPTY'
|
||||
endif
|
||||
@@ -456,8 +595,19 @@ else
|
||||
termux_elf_cleaner = []
|
||||
endif
|
||||
|
||||
tls_provider_dep = dependency('gioopenssl', required: get_option('connectivity'))
|
||||
tls_provider_dep = dependency('gioopenssl', required: get_option('connectivity'), default_options: [
|
||||
'gnutls=disabled',
|
||||
'openssl=enabled',
|
||||
'libproxy=disabled',
|
||||
'gnome_proxy=disabled',
|
||||
'tests=false',
|
||||
])
|
||||
tls_provider_vala_args = []
|
||||
if tls_provider_dep.found()
|
||||
tls_provider_vala_args += [
|
||||
'--pkg=gioopenssl',
|
||||
'--vapidir=' + tls_provider_dep.get_variable('vapidir'),
|
||||
]
|
||||
cdata.set('HAVE_GIOOPENSSL', 1)
|
||||
vala_flags += ['--define=HAVE_GIOOPENSSL']
|
||||
backend_deps_private += tls_provider_dep
|
||||
@@ -473,7 +623,6 @@ nice_dep = dependency('nice', required: get_option('connectivity'), default_opti
|
||||
'introspection=disabled',
|
||||
])
|
||||
if nice_dep.found()
|
||||
openssl_dep = dependency('openssl')
|
||||
usrsctp_dep = dependency('usrsctp', default_options: [
|
||||
'sctp_inet=false',
|
||||
'sctp_inet6=false',
|
||||
@@ -489,7 +638,6 @@ if nice_dep.found()
|
||||
cdata.set('HAVE_SCONN_LEN', 1)
|
||||
endif
|
||||
else
|
||||
openssl_dep = []
|
||||
usrsctp_dep = []
|
||||
endif
|
||||
|
||||
@@ -506,42 +654,6 @@ if host_os in ['ios', 'tvos']
|
||||
backend_libs_private += ['-Wl,-framework,CoreGraphics', '-Wl,-framework,UIKit']
|
||||
endif
|
||||
|
||||
if host_toolchain == 'microsoft'
|
||||
lib = find_program('lib')
|
||||
ar = ''
|
||||
nm = ''
|
||||
strip = ''
|
||||
else
|
||||
lib = ''
|
||||
ar = find_program('ar')
|
||||
nm = find_program('nm')
|
||||
strip = find_program('strip')
|
||||
endif
|
||||
if host_os_family != 'windows'
|
||||
if host_os_family == 'darwin'
|
||||
readelf = ''
|
||||
otool = find_program('otool')
|
||||
libtool = find_program('libtool')
|
||||
else
|
||||
readelf = find_program('readelf')
|
||||
otool = ''
|
||||
libtool = ''
|
||||
endif
|
||||
else
|
||||
readelf = ''
|
||||
otool = ''
|
||||
libtool = ''
|
||||
endif
|
||||
if host_os_family == 'darwin'
|
||||
install_name_tool = find_program('install_name_tool')
|
||||
lipo = find_program('lipo')
|
||||
codesign = find_program('codesign')
|
||||
else
|
||||
install_name_tool = ''
|
||||
lipo = ''
|
||||
codesign = ''
|
||||
endif
|
||||
|
||||
if get_option('devkits').length() != 0
|
||||
if get_option('default_library') != 'static'
|
||||
error('Devkits can only be generated from static libraries')
|
||||
@@ -549,6 +661,7 @@ if get_option('devkits').length() != 0
|
||||
mkdevkit = [python, releng / 'mkdevkit.py']
|
||||
uninstalled_dir = meson.global_build_root() / 'meson-uninstalled'
|
||||
devkit_options = [
|
||||
'--dep-symbol-scope', get_option('devkit_symbol_scope'),
|
||||
'--cc', '>>>', cc.cmd_array(), '<<<',
|
||||
'--c-args', '>>>', get_option('c_args'), '<<<',
|
||||
'--pkg-config', '>>>', find_program('pkg-config'), '<<<',
|
||||
@@ -599,6 +712,8 @@ post_process = [
|
||||
'@INPUT0@',
|
||||
]
|
||||
|
||||
compile_js_agent = files('tools' / 'compile-js-agent.py')
|
||||
|
||||
mapper_opt = get_option('mapper')
|
||||
if mapper_opt.auto()
|
||||
have_mapper = host_os_family == 'darwin'
|
||||
@@ -627,25 +742,29 @@ if cc.get_id() == 'gcc' and cc.compiles('#if __GNUC__ >= 5\n#error NOTNEEDED\n#e
|
||||
add_project_arguments('-w', language: 'c')
|
||||
endif
|
||||
|
||||
vapidir = meson.current_source_dir() / 'vapi'
|
||||
vala_flags += [
|
||||
'--vapidir=' + meson.current_source_dir() / 'vapi',
|
||||
'--vapidir=' + vapidir,
|
||||
'--pkg', 'config',
|
||||
]
|
||||
|
||||
vala_flags += ['--define=' + host_os_family.to_upper()]
|
||||
vala_flags += '--define=' + host_os_family.to_upper()
|
||||
if host_os != host_os_family
|
||||
vala_flags += ['--define=' + host_os.to_upper()]
|
||||
vala_flags += '--define=' + host_os.to_upper()
|
||||
endif
|
||||
vala_flags += ['--define=' + host_arch.to_upper()]
|
||||
vala_flags += '--define=' + host_arch.to_upper()
|
||||
if host_abi != host_arch
|
||||
vala_flags += ['--define=' + host_abi.to_upper()]
|
||||
vala_flags += '--define=' + host_abi.to_upper()
|
||||
endif
|
||||
vala_flags += '--define=' + host_machine.endian().to_upper() + '_ENDIAN'
|
||||
add_project_arguments(vala_flags, language: 'vala')
|
||||
add_project_arguments('-I' + vapidir, language: 'c')
|
||||
|
||||
native_vala_flags = [
|
||||
'--vapidir=' + meson.current_source_dir() / 'vapi',
|
||||
]
|
||||
add_project_arguments(native_vala_flags, language: 'vala', native: true)
|
||||
add_project_arguments('-I' + vapidir, language: 'c', native: true)
|
||||
|
||||
subdir('compat')
|
||||
subdir('tools')
|
||||
@@ -664,9 +783,30 @@ if build_tests
|
||||
subdir('tests')
|
||||
endif
|
||||
|
||||
summary(
|
||||
{
|
||||
'local': have_local_backend,
|
||||
'fruity': have_fruity_backend,
|
||||
'droidy': have_droidy_backend,
|
||||
'socket': have_socket_backend,
|
||||
'barebone': have_barebone_backend,
|
||||
'compiler': have_compiler_backend,
|
||||
},
|
||||
section: 'Backends',
|
||||
bool_yn: true,
|
||||
)
|
||||
summary(
|
||||
{
|
||||
'compat': compat_summary,
|
||||
'assets': get_option('assets'),
|
||||
'mapper': have_mapper,
|
||||
'connectivity': tls_provider_dep.found(),
|
||||
'gadget': build_gadget,
|
||||
'server': build_server,
|
||||
'portal': build_portal,
|
||||
'inject': build_inject,
|
||||
'tests': build_tests,
|
||||
},
|
||||
section: 'Features',
|
||||
bool_yn: true,
|
||||
)
|
||||
+25
-20
@@ -37,13 +37,7 @@ option('barebone_backend',
|
||||
option('compiler_backend',
|
||||
type: 'feature',
|
||||
value: 'auto',
|
||||
description: 'Include frida-compile backend powered by GumJS',
|
||||
)
|
||||
|
||||
option('compiler_snapshot',
|
||||
type: 'feature',
|
||||
value: 'auto',
|
||||
description: 'Speed up compiler startup by using a snapshot'
|
||||
description: 'Include frida-compile backend powered by ESBuild and typescript-go',
|
||||
)
|
||||
|
||||
option('assets',
|
||||
@@ -68,13 +62,25 @@ option('compat',
|
||||
option('helper_modern',
|
||||
type: 'string',
|
||||
value: 'auto',
|
||||
description: 'Prebuilt frida-helper to embed for use on modern systems'
|
||||
description: 'Prebuilt frida-helper to embed for supporting modern targets'
|
||||
)
|
||||
|
||||
option('helper_legacy',
|
||||
type: 'string',
|
||||
value: 'auto',
|
||||
description: 'Prebuilt frida-helper to embed for use on legacy systems'
|
||||
description: 'Prebuilt frida-helper to embed for supporting legacy targets'
|
||||
)
|
||||
|
||||
option('helper_emulated_modern',
|
||||
type: 'string',
|
||||
value: 'auto',
|
||||
description: 'Prebuilt frida-helper to embed for supporting modern emulated targets'
|
||||
)
|
||||
|
||||
option('helper_emulated_legacy',
|
||||
type: 'string',
|
||||
value: 'auto',
|
||||
description: 'Prebuilt frida-helper to embed for supporting legacy emulated targets'
|
||||
)
|
||||
|
||||
option('agent_modern',
|
||||
@@ -101,16 +107,6 @@ option('agent_emulated_legacy',
|
||||
description: 'Prebuilt agent to embed for use on legacy emulated targets'
|
||||
)
|
||||
|
||||
option('agent_dbghelp_prefix',
|
||||
type: 'string',
|
||||
description: 'Location of DbgHelp binaries to embed alongside agent (Windows only)'
|
||||
)
|
||||
|
||||
option('agent_symsrv_prefix',
|
||||
type: 'string',
|
||||
description: 'Location of SymSrv binaries to embed alongside agent (Windows only)'
|
||||
)
|
||||
|
||||
option('gadget',
|
||||
type: 'feature',
|
||||
value: 'auto',
|
||||
@@ -137,7 +133,7 @@ option('inject',
|
||||
|
||||
option('connectivity',
|
||||
type: 'feature',
|
||||
value: 'auto',
|
||||
value: 'enabled',
|
||||
description: 'Internet connectivity features (TLS and ICE support)'
|
||||
)
|
||||
|
||||
@@ -154,6 +150,15 @@ option('devkits',
|
||||
description: 'Devkits to build'
|
||||
)
|
||||
|
||||
option('devkit_symbol_scope',
|
||||
type: 'combo',
|
||||
choices: ['prefixed', 'original'],
|
||||
value: 'prefixed',
|
||||
description : 'How devkit generation treats third-party symbols:\n'
|
||||
+ ' - prefixed: add the \'_frida_\' prefix\n'
|
||||
+ ' - original: keep symbols exactly as upstream\n'
|
||||
)
|
||||
|
||||
option('tests',
|
||||
type: 'feature',
|
||||
value: 'auto',
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ if tls_provider_dep.found()
|
||||
endif
|
||||
|
||||
raw_portal = executable('frida-portal-raw', portal_sources,
|
||||
vala_args: [core_vala_args, '--pkg=posix'],
|
||||
vala_args: [core_vala_args, tls_provider_vala_args, '--pkg=posix'],
|
||||
link_args: extra_link_args,
|
||||
link_depends: extra_link_depends,
|
||||
dependencies: [core_dep] + extra_deps,
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@ namespace Frida.Portal {
|
||||
return application.run ();
|
||||
}
|
||||
|
||||
private class Application : Object {
|
||||
private sealed class Application : Object {
|
||||
public signal void ready (bool success);
|
||||
|
||||
public PortalService service {
|
||||
|
||||
+1
-1
Submodule releng updated: 56b262207c...c24becede0.
+1
-1
@@ -6,7 +6,7 @@ server_sources = [
|
||||
if host_os_family == 'darwin'
|
||||
server_sources += ['server-darwin.m']
|
||||
endif
|
||||
if host_os in ['ios', 'tvos']
|
||||
if host_os in ['ios', 'tvos', 'xros']
|
||||
server_sources += [
|
||||
'server-ios-tvos.c',
|
||||
]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#include "server-glue.h"
|
||||
|
||||
#include "frida-core.h"
|
||||
#if defined (HAVE_IOS) || defined (HAVE_TVOS)
|
||||
#if defined (HAVE_IOS) || defined (HAVE_TVOS) || defined (HAVE_XROS)
|
||||
# include "server-ios-tvos.h"
|
||||
#endif
|
||||
#ifdef HAVE_ANDROID
|
||||
@@ -54,7 +54,7 @@ frida_server_environment_set_verbose_logging_enabled (gboolean enabled)
|
||||
void
|
||||
frida_server_environment_configure (void)
|
||||
{
|
||||
#if defined (HAVE_IOS) || defined (HAVE_TVOS)
|
||||
#if defined (HAVE_IOS) || defined (HAVE_TVOS) || defined (HAVE_XROS)
|
||||
_frida_server_ios_tvos_configure ();
|
||||
#endif
|
||||
|
||||
|
||||
+52
-9
@@ -3,6 +3,7 @@ namespace Frida.Server {
|
||||
|
||||
private const string DEFAULT_DIRECTORY = "re.frida.server";
|
||||
private static bool output_version = false;
|
||||
private static string? device_id = null;
|
||||
private static string? listen_address = null;
|
||||
private static string? certpath = null;
|
||||
private static string? origin = null;
|
||||
@@ -30,6 +31,7 @@ namespace Frida.Server {
|
||||
|
||||
const OptionEntry[] option_entries = {
|
||||
{ "version", 0, 0, OptionArg.NONE, ref output_version, "Output version information and exit", null },
|
||||
{ "device", 0, 0, OptionArg.STRING, ref device_id, "Serve device with the given ID", "ID" },
|
||||
{ "listen", 'l', 0, OptionArg.STRING, ref listen_address, "Listen on ADDRESS", "ADDRESS" },
|
||||
{ "certificate", 0, 0, OptionArg.FILENAME, ref certpath, "Enable TLS using CERTIFICATE", "CERTIFICATE" },
|
||||
{ "origin", 0, 0, OptionArg.STRING, ref origin, "Only accept requests with “Origin” header matching ORIGIN " +
|
||||
@@ -178,7 +180,7 @@ namespace Frida.Server {
|
||||
|
||||
#if DARWIN
|
||||
var worker = new Thread<int> ("frida-server-main-loop", () => {
|
||||
var exit_code = run_application (endpoint_params, options, on_ready);
|
||||
var exit_code = run_application (device_id, endpoint_params, options, on_ready);
|
||||
|
||||
_stop_run_loop ();
|
||||
|
||||
@@ -190,15 +192,16 @@ namespace Frida.Server {
|
||||
|
||||
return exit_code;
|
||||
#else
|
||||
return run_application (endpoint_params, options, on_ready);
|
||||
return run_application (device_id, endpoint_params, options, on_ready);
|
||||
#endif
|
||||
}
|
||||
|
||||
private static int run_application (EndpointParameters endpoint_params, ControlServiceOptions options, ReadyHandler on_ready) {
|
||||
private static int run_application (string? device_id, EndpointParameters endpoint_params, ControlServiceOptions options,
|
||||
ReadyHandler on_ready) {
|
||||
TemporaryDirectory.always_use ((directory != null) ? directory : DEFAULT_DIRECTORY);
|
||||
TemporaryDirectory.use_sysroot (options.sysroot);
|
||||
|
||||
application = new Application (new ControlService (endpoint_params, options));
|
||||
application = new Application (device_id, endpoint_params, options);
|
||||
|
||||
Posix.signal (Posix.Signal.INT, (sig) => {
|
||||
application.stop ();
|
||||
@@ -232,22 +235,39 @@ namespace Frida.Server {
|
||||
}
|
||||
#endif
|
||||
|
||||
private class Application : Object {
|
||||
private sealed class Application : Object {
|
||||
public signal void ready (bool success);
|
||||
|
||||
public ControlService service {
|
||||
public string? device_id {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
public EndpointParameters endpoint_params {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
public ControlServiceOptions options {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
private DeviceManager? manager;
|
||||
private ControlService? service;
|
||||
|
||||
private Cancellable io_cancellable = new Cancellable ();
|
||||
|
||||
private MainLoop loop = new MainLoop ();
|
||||
private int exit_code;
|
||||
private bool stopping;
|
||||
|
||||
public Application (ControlService service) {
|
||||
Object (service: service);
|
||||
public Application (string? device_id, EndpointParameters endpoint_params, ControlServiceOptions options) {
|
||||
Object (
|
||||
device_id: device_id,
|
||||
endpoint_params: endpoint_params,
|
||||
options: options
|
||||
);
|
||||
}
|
||||
|
||||
public int run () {
|
||||
@@ -265,6 +285,17 @@ namespace Frida.Server {
|
||||
|
||||
private async void start () {
|
||||
try {
|
||||
if (device_id != null && device_id != "local") {
|
||||
manager = new DeviceManager.with_nonlocal_backends_only ();
|
||||
|
||||
var device = yield manager.get_device_by_id (device_id, 0, io_cancellable);
|
||||
device.lost.connect (on_device_lost);
|
||||
|
||||
service = yield new ControlService.with_device (device, endpoint_params, options);
|
||||
} else {
|
||||
service = new ControlService (endpoint_params, options);
|
||||
}
|
||||
|
||||
yield service.start (io_cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
if (e is IOError.CANCELLED)
|
||||
@@ -297,7 +328,15 @@ namespace Frida.Server {
|
||||
io_cancellable.cancel ();
|
||||
|
||||
try {
|
||||
yield service.stop ();
|
||||
if (service != null) {
|
||||
yield service.stop ();
|
||||
service = null;
|
||||
}
|
||||
|
||||
if (manager != null) {
|
||||
yield manager.close ();
|
||||
manager = null;
|
||||
}
|
||||
} catch (GLib.Error e) {
|
||||
}
|
||||
|
||||
@@ -306,6 +345,10 @@ namespace Frida.Server {
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
private void on_device_lost () {
|
||||
stop ();
|
||||
}
|
||||
}
|
||||
|
||||
private TlsCertificate? parse_certificate (string? path) throws GLib.Error {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
namespace Frida {
|
||||
public class AgentContainer : Object, AgentSessionProvider {
|
||||
public sealed class AgentContainer : Object, AgentSessionProvider {
|
||||
public DBusConnection connection {
|
||||
get;
|
||||
private set;
|
||||
|
||||
+91284
File diff suppressed because it is too large.
Load diff
+29500
File diff suppressed because it is too large.
Load diff
+141723
File diff suppressed because it is too large.
Load diff
+174
-39
@@ -1,42 +1,71 @@
|
||||
from __future__ import annotations
|
||||
import argparse
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from typing import List, Set
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
CORE_NAMESPACE = "http://www.gtk.org/introspection/core/1.0"
|
||||
C_NAMESPACE = "http://www.gtk.org/introspection/c/1.0"
|
||||
GLIB_NAMESPACE = "http://www.gtk.org/introspection/glib/1.0"
|
||||
GIR_NAMESPACES = {
|
||||
"": CORE_NAMESPACE,
|
||||
"c": C_NAMESPACE,
|
||||
"glib": GLIB_NAMESPACE,
|
||||
}
|
||||
|
||||
CORE_TAG_IMPLEMENTS = f"{{{CORE_NAMESPACE}}}implements"
|
||||
CORE_TAG_FIELD = f"{{{CORE_NAMESPACE}}}field"
|
||||
CORE_TAG_CONSTRUCTOR = f"{{{CORE_NAMESPACE}}}constructor"
|
||||
CORE_TAG_METHOD = f"{{{CORE_NAMESPACE}}}method"
|
||||
|
||||
OBJECT_TYPE_PATTERN = re.compile(r"\bpublic\s+(sealed )?(class|interface)\s+(\w+)\b")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Generate refined Frida API definitions")
|
||||
parser.add_argument('--output', dest='output_type', choices=['bundle', 'header', 'gir', 'vapi', 'vapi-stamp'], default='bundle')
|
||||
parser.add_argument('frida_version', metavar='frida-version', type=str)
|
||||
parser.add_argument('frida_major_version', metavar='frida-major-version', type=str)
|
||||
parser.add_argument('frida_minor_version', metavar='frida-minor-version', type=str)
|
||||
parser.add_argument('frida_micro_version', metavar='frida-micro-version', type=str)
|
||||
parser.add_argument('frida_nano_version', metavar='frida-nano-version', type=str)
|
||||
parser.add_argument('api_version', metavar='api-version', type=str)
|
||||
parser.add_argument('core_header', metavar='/path/to/frida-core.h', type=argparse.FileType('r', encoding='utf-8'))
|
||||
parser.add_argument('core_gir', metavar='/path/to/Frida-x.y.gir', type=argparse.FileType('r', encoding='utf-8'))
|
||||
parser.add_argument('core_vapi', metavar='/path/to/frida-core.vapi', type=argparse.FileType('r', encoding='utf-8'))
|
||||
parser.add_argument('core_header', metavar='/path/to/frida-core.h', type=argparse.FileType('r', encoding='utf-8'))
|
||||
parser.add_argument('base_vapi', metavar='/path/to/frida-base.vapi', type=argparse.FileType('r', encoding='utf-8'))
|
||||
parser.add_argument('base_header', metavar='/path/to/frida-base.h', type=argparse.FileType('r', encoding='utf-8'))
|
||||
parser.add_argument('base_gir', metavar='/path/to/FridaBase-x.y.gir', type=argparse.FileType('r', encoding='utf-8'))
|
||||
parser.add_argument('base_vapi', metavar='/path/to/frida-base.vapi', type=argparse.FileType('r', encoding='utf-8'))
|
||||
parser.add_argument('output_dir', metavar='/output/dir')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
output_type = args.output_type
|
||||
frida_version = args.frida_version
|
||||
frida_version_components = (
|
||||
args.frida_major_version,
|
||||
args.frida_minor_version,
|
||||
args.frida_micro_version,
|
||||
args.frida_nano_version,
|
||||
)
|
||||
api_version = args.api_version
|
||||
core_header = args.core_header.read()
|
||||
core_gir = args.core_gir.read()
|
||||
core_vapi = args.core_vapi.read()
|
||||
core_header = args.core_header.read()
|
||||
base_vapi = args.base_vapi.read()
|
||||
base_header = args.base_header.read()
|
||||
base_gir = args.base_gir.read()
|
||||
base_vapi = args.base_vapi.read()
|
||||
output_dir = Path(args.output_dir)
|
||||
|
||||
if output_type == 'gir':
|
||||
(output_dir / f"Frida-{api_version}.gir").write_text(core_gir, encoding='utf-8')
|
||||
return
|
||||
|
||||
if output_type == 'vapi-stamp':
|
||||
(output_dir / f"frida-core-{api_version}.vapi.stamp").write_bytes(b"")
|
||||
return
|
||||
|
||||
toplevel_names = [
|
||||
"frida.vala",
|
||||
"package-manager.vala",
|
||||
"control-service.vala",
|
||||
"portal-service.vala",
|
||||
"file-monitor.vala",
|
||||
@@ -45,33 +74,58 @@ def main():
|
||||
toplevel_sources = []
|
||||
src_dir = Path(__file__).parent.parent.resolve()
|
||||
for name in toplevel_names:
|
||||
with open(src_dir / name, 'r', encoding='utf-8') as f:
|
||||
toplevel_sources.append(f.read())
|
||||
toplevel_sources.append((src_dir / name).read_text(encoding='utf-8'))
|
||||
toplevel_code = "\n".join(toplevel_sources)
|
||||
|
||||
enable_header = False
|
||||
enable_gir = False
|
||||
enable_vapi = False
|
||||
if output_type == 'bundle':
|
||||
enable_header = True
|
||||
enable_gir = True
|
||||
enable_vapi = True
|
||||
elif output_type == 'header':
|
||||
enable_header = True
|
||||
elif output_type == 'gir':
|
||||
enable_gir = True
|
||||
elif output_type == 'vapi':
|
||||
enable_vapi = True
|
||||
|
||||
api = parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, base_header)
|
||||
api = parse_api(frida_version, frida_version_components, api_version, toplevel_code, core_header, core_vapi, base_header, base_vapi)
|
||||
|
||||
if enable_header:
|
||||
emit_header(api, output_dir)
|
||||
|
||||
if enable_gir:
|
||||
emit_gir(api, core_gir, base_gir, output_dir)
|
||||
|
||||
if enable_vapi:
|
||||
emit_vapi(api, output_dir)
|
||||
|
||||
def emit_header(api, output_dir):
|
||||
with open(output_dir / 'frida-core.h', 'w', encoding='utf-8') as output_header_file:
|
||||
with OutputFile(output_dir / 'frida-core.h') as output_header_file:
|
||||
output_header_file.write("#ifndef __FRIDA_CORE_H__\n#define __FRIDA_CORE_H__\n\n")
|
||||
|
||||
output_header_file.write("#include <glib.h>\n#include <glib-object.h>\n#include <gio/gio.h>\n#include <json-glib/json-glib.h>\n")
|
||||
output_header_file.write("#include <glib.h>\n#include <glib-object.h>\n#include <gio/gio.h>\n#include <json-glib/json-glib.h>\n\n")
|
||||
|
||||
output_header_file.write(f"#define FRIDA_VERSION \"{api.frida_version}\"\n\n")
|
||||
|
||||
for name, value in zip(['MAJOR', 'MINOR', 'MICRO', 'NANO'], api.frida_version_components):
|
||||
output_header_file.write(f"#define FRIDA_{name}_VERSION {value}\n")
|
||||
|
||||
output_header_file.write("""
|
||||
#define FRIDA_CHECK_VERSION(maj, min, mic) \\
|
||||
(FRIDA_CURRENT_VERSION >= FRIDA_VERSION_ENCODE ((maj), (min), (mic)))
|
||||
|
||||
#define FRIDA_CURRENT_VERSION \\
|
||||
FRIDA_VERSION_ENCODE ( \\
|
||||
FRIDA_MAJOR_VERSION, \\
|
||||
FRIDA_MINOR_VERSION, \\
|
||||
FRIDA_MICRO_VERSION)
|
||||
|
||||
#define FRIDA_VERSION_ENCODE(maj, min, mic) \\
|
||||
(((maj) * 1000000U) + ((min) * 1000U) + (mic))
|
||||
""")
|
||||
|
||||
output_header_file.write("\nG_BEGIN_DECLS\n")
|
||||
|
||||
@@ -79,7 +133,6 @@ def emit_header(api, output_dir):
|
||||
output_header_file.write("\ntypedef struct _%s %s;" % (object_type.c_name, object_type.c_name))
|
||||
if object_type.c_iface_definition is not None:
|
||||
output_header_file.write("\ntypedef struct _%sIface %sIface;" % (object_type.c_name, object_type.c_name))
|
||||
output_header_file.write("\ntypedef struct _FridaHostSession FridaHostSession;")
|
||||
|
||||
for enum in api.enum_types:
|
||||
output_header_file.write("\n\n" + enum.c_definition)
|
||||
@@ -150,8 +203,64 @@ def emit_header(api, output_dir):
|
||||
|
||||
output_header_file.write("\n\n#endif\n")
|
||||
|
||||
def emit_gir(api: ApiSpec, core_gir: str, base_gir: str, output_dir: Path) -> str:
|
||||
ET.register_namespace("", CORE_NAMESPACE)
|
||||
ET.register_namespace("c", C_NAMESPACE)
|
||||
ET.register_namespace("glib", GLIB_NAMESPACE)
|
||||
|
||||
core_tree = ET.ElementTree(ET.fromstring(core_gir))
|
||||
base_tree = ET.ElementTree(ET.fromstring(base_gir))
|
||||
|
||||
core_root = core_tree.getroot()
|
||||
base_root = base_tree.getroot()
|
||||
|
||||
merged_root = ET.Element(core_root.tag, core_root.attrib)
|
||||
|
||||
for elem in core_root.findall("include", GIR_NAMESPACES):
|
||||
name = elem.get("name")
|
||||
if name in {"GLib", "GObject", "Gio"}:
|
||||
merged_root.append(elem)
|
||||
|
||||
for tag in ["package", "c:include"]:
|
||||
for elem in core_root.findall(tag, GIR_NAMESPACES):
|
||||
merged_root.append(elem)
|
||||
|
||||
core_namespace = core_root.find("namespace", GIR_NAMESPACES)
|
||||
merged_namespace = ET.SubElement(merged_root, core_namespace.tag, core_namespace.attrib)
|
||||
|
||||
object_type_names = {obj.name for obj in api.object_types}
|
||||
enum_type_names = {enum.name for enum in api.enum_types}
|
||||
error_type_names = {error.name for error in api.error_types}
|
||||
|
||||
def merge_and_transform_elements(tag_name: str, spec_set: Set[str]):
|
||||
core_elements = filter_elements(core_root.findall(f".//{tag_name}", GIR_NAMESPACES), spec_set)
|
||||
base_elements = filter_elements(base_root.findall(f".//{tag_name}", GIR_NAMESPACES), spec_set)
|
||||
for elem in core_elements + base_elements:
|
||||
if tag_name == "class":
|
||||
for child in list(elem):
|
||||
if (child.tag == CORE_TAG_IMPLEMENTS and child.get("name") == "FridaBase.AgentMessageSink") \
|
||||
or child.tag == CORE_TAG_FIELD \
|
||||
or child.get("name").startswith("_"):
|
||||
elem.remove(child)
|
||||
merged_namespace.append(elem)
|
||||
|
||||
merge_and_transform_elements("class", object_type_names)
|
||||
merge_and_transform_elements("interface", object_type_names)
|
||||
merge_and_transform_elements("enumeration", enum_type_names | error_type_names)
|
||||
|
||||
ET.indent(merged_root, space=" ")
|
||||
result = ET.tostring(merged_root,
|
||||
encoding="unicode",
|
||||
xml_declaration=True)
|
||||
result = result.replace("FridaBase.", "Frida.")
|
||||
with OutputFile(output_dir / f"Frida-{api.version}.gir") as output_gir:
|
||||
output_gir.write(result)
|
||||
|
||||
def filter_elements(elements: List[ET.Element], spec_set: Set[str]):
|
||||
return [elem for elem in elements if elem.get("name") in spec_set]
|
||||
|
||||
def emit_vapi(api, output_dir):
|
||||
with open(output_dir / "frida-core-{0}.vapi".format(api.version), "w", encoding='utf-8') as output_vapi_file:
|
||||
with OutputFile(output_dir / f"frida-core-{api.version}.vapi") as output_vapi_file:
|
||||
output_vapi_file.write("[CCode (cheader_filename = \"frida-core.h\", cprefix = \"Frida\", lower_case_cprefix = \"frida_\")]")
|
||||
output_vapi_file.write("\nnamespace Frida {")
|
||||
output_vapi_file.write("\n\tpublic static void init ();")
|
||||
@@ -189,12 +298,12 @@ def emit_vapi(api, output_dir):
|
||||
|
||||
output_vapi_file.write("\n}\n")
|
||||
|
||||
with open(output_dir / "frida-core-{0}.deps".format(api.version), "w", encoding='utf-8') as output_deps_file:
|
||||
with OutputFile(output_dir / f"frida-core-{api.version}.deps") as output_deps_file:
|
||||
output_deps_file.write("glib-2.0\n")
|
||||
output_deps_file.write("gobject-2.0\n")
|
||||
output_deps_file.write("gio-2.0\n")
|
||||
|
||||
def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, base_header):
|
||||
def parse_api(frida_version, frida_version_components, api_version, toplevel_code, core_header, core_vapi, base_header, base_vapi):
|
||||
all_headers = core_header + "\n" + base_header
|
||||
|
||||
all_enum_names = [m.group(1) for m in re.finditer(r"^\t+public\s+enum\s+(\w+)\s+", toplevel_code + "\n" + base_vapi, re.MULTILINE)]
|
||||
@@ -217,12 +326,18 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
|
||||
"StaticAuthenticationService": "AuthenticationService",
|
||||
}
|
||||
internal_type_prefixes = [
|
||||
"AgentMessageKind",
|
||||
"Fruity",
|
||||
"HostSession",
|
||||
"MessageType",
|
||||
"PeerSetup",
|
||||
"PortConflictBehavior",
|
||||
"ResultCode",
|
||||
"SpawnStartState",
|
||||
"State",
|
||||
"StringTerminator",
|
||||
"UnloadPolicy",
|
||||
"WebService",
|
||||
"Winjector"
|
||||
]
|
||||
seen_enum_names = set()
|
||||
@@ -287,8 +402,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
|
||||
method_cname_lc = object_type.c_name_lc + '_' + method_name
|
||||
if method_cname_lc not in seen_cfunctions:
|
||||
seen_cfunctions.add(method_cname_lc)
|
||||
if method_name not in ('construct', 'construct_with_host_session', 'get_main_context', 'get_provider', 'get_session') \
|
||||
and not (object_type.name in ("Session", "Script") and method_name == 'get_id'):
|
||||
if method_name != 'construct':
|
||||
if (object_type.c_name + '*') in m.group(0):
|
||||
if method_name == 'new' or method_name.startswith('new_'):
|
||||
object_type.c_constructors.append(method_cprototype)
|
||||
@@ -305,7 +419,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
|
||||
if delegate_cname not in seen_cdelegates:
|
||||
seen_cdelegates.add(delegate_cname)
|
||||
object_type.c_delegate_typedefs.append(beautify_cprototype(d.group(0)))
|
||||
if object_type.kind == 'interface' and object_type.name != "Injector":
|
||||
if object_type.kind == 'interface':
|
||||
for m in re.finditer("^(struct _" + object_type.c_name + "Iface {[^}]+};)$", all_headers, re.MULTILINE):
|
||||
object_type.c_iface_definition = beautify_cinterface(m.group(1))
|
||||
|
||||
@@ -327,8 +441,10 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
|
||||
if stripped_line == "}":
|
||||
ignoring = False
|
||||
else:
|
||||
if stripped_line.startswith("public abstract") or stripped_line.startswith("public class Promise") \
|
||||
or stripped_line.startswith("public interface Future"):
|
||||
if stripped_line.startswith("public abstract") \
|
||||
or stripped_line.startswith("public class Promise") \
|
||||
or stripped_line.startswith("public interface Future") \
|
||||
or stripped_line.startswith("public class CF"):
|
||||
ignoring = True
|
||||
elif stripped_line.startswith("public enum") or stripped_line.startswith("public errordomain"):
|
||||
name = re.match(r"^public (?:enum|errordomain) (\w+) ", stripped_line).group(1)
|
||||
@@ -340,8 +456,8 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
|
||||
current_enum.vapi_declaration = stripped_line
|
||||
else:
|
||||
ignoring = True
|
||||
elif stripped_line.startswith("public class") or stripped_line.startswith("public interface"):
|
||||
name = re.match(r"^public (class|interface) (\w+) ", stripped_line).group(2)
|
||||
elif (match := OBJECT_TYPE_PATTERN.match(stripped_line)) is not None:
|
||||
name = match.group(3)
|
||||
if name not in object_type_by_name:
|
||||
ignoring = True
|
||||
else:
|
||||
@@ -360,8 +476,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
|
||||
current_object_type.vapi_signals.append(stripped_line)
|
||||
elif "{ get" in stripped_line:
|
||||
name = re.match(r".+?(\w+)\s+{", stripped_line).group(1)
|
||||
if name not in ('main_context', 'provider', 'session'):
|
||||
current_object_type.vapi_properties.append(stripped_line)
|
||||
current_object_type.vapi_properties.append(stripped_line)
|
||||
else:
|
||||
m = re.match(r".+?(\w+)\s+\(", stripped_line)
|
||||
if m is not None:
|
||||
@@ -381,7 +496,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
|
||||
m = re.search(r"^[\w\*]+ frida_{}.+?;".format(f.name), all_headers, re.MULTILINE | re.DOTALL)
|
||||
f.c_prototype = beautify_cprototype(m.group(0))
|
||||
|
||||
return ApiSpec(api_version, object_types, functions, enum_types, error_types)
|
||||
return ApiSpec(frida_version, frida_version_components, api_version, object_types, functions, enum_types, error_types)
|
||||
|
||||
def function_is_public(name):
|
||||
return not name.startswith("_") and \
|
||||
@@ -395,22 +510,25 @@ def function_is_public(name):
|
||||
"parse_control_address",
|
||||
"parse_cluster_address",
|
||||
"parse_socket_address",
|
||||
"negotiate_connection"
|
||||
"negotiate_connection",
|
||||
"check_kernel_version",
|
||||
]
|
||||
|
||||
def parse_vala_object_types(source):
|
||||
return [ApiObjectType(m.group(2), m.group(1)) for m in re.finditer(r"^\t+public\s+(class|interface)\s+(\w+)\s+", source, re.MULTILINE)]
|
||||
def parse_vala_object_types(source) -> List[ApiObjectType]:
|
||||
return [ApiObjectType(m.group(3), m.group(2)) for m in OBJECT_TYPE_PATTERN.finditer(source, re.MULTILINE)]
|
||||
|
||||
def parse_vapi_functions(vapi):
|
||||
def parse_vapi_functions(vapi) -> List[ApiFunction]:
|
||||
return [ApiFunction(m.group(1), m.group(0)) for m in re.finditer(r"^\tpublic static .+ (\w+) \(.+;", vapi, re.MULTILINE)]
|
||||
|
||||
@dataclass
|
||||
class ApiSpec:
|
||||
def __init__(self, version, object_types, functions, enum_types, error_types):
|
||||
self.version = version
|
||||
self.object_types = object_types
|
||||
self.functions = functions
|
||||
self.enum_types = enum_types
|
||||
self.error_types = error_types
|
||||
frida_version: str
|
||||
frida_version_components: List[int]
|
||||
version: str
|
||||
object_types: List[ApiObjectType]
|
||||
functions: List[ApiFunction]
|
||||
enum_types: List[ApiEnum]
|
||||
error_types: List[ApiEnum]
|
||||
|
||||
class ApiEnum:
|
||||
def __init__(self, name):
|
||||
@@ -512,6 +630,23 @@ def fuzzysort(items, keys):
|
||||
result.extend(remaining)
|
||||
return result
|
||||
|
||||
class OutputFile:
|
||||
def __init__(self, output_path):
|
||||
self._output_path = output_path
|
||||
self._io = StringIO()
|
||||
|
||||
def __enter__(self):
|
||||
return self._io
|
||||
|
||||
def __exit__(self, *exc):
|
||||
result = self._io.getvalue()
|
||||
if self._output_path.exists():
|
||||
existing_contents = self._output_path.read_text(encoding='utf-8')
|
||||
if existing_contents == result:
|
||||
return False
|
||||
self._output_path.write_text(result, encoding='utf-8')
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+42
-48
@@ -1,55 +1,50 @@
|
||||
fs = import('fs')
|
||||
|
||||
generate_api = [python, files('generate.py')]
|
||||
|
||||
generate_api_args = [
|
||||
frida_version,
|
||||
frida_major_version.to_string(),
|
||||
frida_minor_version.to_string(),
|
||||
frida_micro_version.to_string(),
|
||||
frida_nano_version.to_string(),
|
||||
api_version,
|
||||
core_build_dir / 'frida-core.h',
|
||||
core_build_dir / core_gir_name,
|
||||
core_build_dir / 'frida-core.vapi',
|
||||
core_build_dir / 'frida-core.h',
|
||||
base_build_dir / f'frida-base-@[email protected]',
|
||||
base_build_dir / 'frida-base.h',
|
||||
base_build_dir / base_gir_name,
|
||||
base_build_dir / f'frida-base-@[email protected]',
|
||||
meson.current_build_dir(),
|
||||
]
|
||||
|
||||
core_public_h = custom_target('frida-core-header',
|
||||
input: [core, base],
|
||||
output: ['frida-core.h'],
|
||||
command: [
|
||||
generate_api,
|
||||
'--output=header',
|
||||
generate_api_args,
|
||||
],
|
||||
install: true,
|
||||
install_dir: header_install_dir,
|
||||
)
|
||||
|
||||
core_public_gir = custom_target('frida-core-gir',
|
||||
input: [core, base],
|
||||
output: [core_gir_name],
|
||||
command: [
|
||||
generate_api,
|
||||
'--output=gir',
|
||||
generate_api_args,
|
||||
],
|
||||
install: true,
|
||||
install_dir: girdir,
|
||||
)
|
||||
|
||||
core_public_vapi = custom_target('frida-core-vapi',
|
||||
core_api = custom_target('frida-core-api',
|
||||
input: [core, base],
|
||||
output: [
|
||||
'frida-core.h',
|
||||
core_gir_name,
|
||||
f'frida-core-@[email protected]',
|
||||
f'frida-core-@[email protected]',
|
||||
],
|
||||
command: [
|
||||
generate_api,
|
||||
'--output=vapi',
|
||||
'--output=bundle',
|
||||
generate_api_args,
|
||||
],
|
||||
install: true,
|
||||
install_dir: vapidir,
|
||||
install_dir: [header_install_dir, girdir, vapidir, vapidir],
|
||||
)
|
||||
|
||||
core_public_vapi_stamp = custom_target('frida-core-vapi-stamp',
|
||||
core_public_h = core_api[0]
|
||||
core_public_gir = core_api[1]
|
||||
core_public_vapi = [core_api[2], core_api[3]]
|
||||
|
||||
install_glib_girs = not gi_dep.found() and not fs.exists(girdir / 'GLib-2.0.gir')
|
||||
glib_gir = fs.copyfile('GLib-2.0.gir', install: install_glib_girs, install_dir: girdir)
|
||||
gobject_gir = fs.copyfile('GObject-2.0.gir', install: install_glib_girs, install_dir: girdir)
|
||||
gio_gir = fs.copyfile('Gio-2.0.gir', install: install_glib_girs, install_dir: girdir)
|
||||
|
||||
core_public_vapi_stamp = custom_target('frida-core-vapi-stamp',
|
||||
input: core_public_vapi,
|
||||
output: f'frida-core-@[email protected]',
|
||||
command: [
|
||||
@@ -76,8 +71,6 @@ core_public_lib = custom_target('frida-core-library',
|
||||
install_dir: get_option('libdir'),
|
||||
)
|
||||
|
||||
fs = import('fs')
|
||||
|
||||
core_public_extra_headers = []
|
||||
if host_os == 'android'
|
||||
core_public_extra_headers += fs.copyfile(frida_selinux_h)
|
||||
@@ -88,19 +81,28 @@ if build_machine.system() == 'windows'
|
||||
else
|
||||
uninstalled_incdir = meson.current_build_dir()
|
||||
endif
|
||||
uninstalled_girdir = uninstalled_incdir
|
||||
uninstalled_vapidir = uninstalled_incdir
|
||||
|
||||
uninstalled_variables = {
|
||||
'frida_includedir': uninstalled_incdir,
|
||||
'frida_girdir': uninstalled_girdir,
|
||||
'frida_vapidir': uninstalled_vapidir,
|
||||
}
|
||||
|
||||
installed_variables = {
|
||||
'frida_includedir': '${includedir}',
|
||||
'frida_girdir': girdir,
|
||||
'frida_vapidir': vapidir,
|
||||
}
|
||||
|
||||
core_public_dep = declare_dependency(
|
||||
sources: [core_public_h, core_public_gir, core_public_vapi_stamp, core_public_extra_headers],
|
||||
sources: [core_public_h, core_public_gir, glib_gir, gobject_gir, gio_gir, core_public_vapi_stamp, core_public_extra_headers],
|
||||
include_directories: include_directories('.'),
|
||||
link_args: backend_libs_private,
|
||||
link_with: core_public_lib,
|
||||
dependencies: core_deps,
|
||||
variables: {
|
||||
'frida_includedir': uninstalled_incdir,
|
||||
'frida_girdir': uninstalled_girdir,
|
||||
'frida_vapidir': uninstalled_vapidir,
|
||||
},
|
||||
variables: uninstalled_variables,
|
||||
)
|
||||
|
||||
pkg = import('pkgconfig')
|
||||
@@ -115,16 +117,8 @@ pkg.generate(
|
||||
libraries: core_public_lib,
|
||||
libraries_private: backend_libs_private,
|
||||
extra_cflags: ['-I${frida_includedir}'],
|
||||
variables: {
|
||||
'frida_includedir': '${includedir}',
|
||||
'frida_girdir': girdir,
|
||||
'frida_vapidir': vapidir,
|
||||
},
|
||||
uninstalled_variables: {
|
||||
'frida_includedir': uninstalled_incdir,
|
||||
'frida_girdir': uninstalled_girdir,
|
||||
'frida_vapidir': uninstalled_vapidir,
|
||||
},
|
||||
variables: installed_variables,
|
||||
uninstalled_variables: uninstalled_variables,
|
||||
)
|
||||
|
||||
meson.override_dependency(f'frida-core-@api_version@', core_public_dep)
|
||||
@@ -0,0 +1,503 @@
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public sealed class AgentConnection : Object, AsyncInitable {
|
||||
public signal void script_message (AgentScriptId id, string json, Bytes? data);
|
||||
|
||||
private Cancellable io_cancellable = new Cancellable ();
|
||||
|
||||
private SocketConnection hostlink;
|
||||
private BufferedInputStream input;
|
||||
private OutputStream output;
|
||||
|
||||
private AgentConfig agent_config;
|
||||
private ImageConfig? image_config;
|
||||
private Machine machine;
|
||||
private Allocator allocator;
|
||||
|
||||
private Allocation elf_allocation;
|
||||
private Allocation config_allocation;
|
||||
private Callback mprotect_callback;
|
||||
private Callback remap_writable_pages_callback;
|
||||
|
||||
private Gee.Map<uint16, Promise<Variant>> pending_requests = new Gee.HashMap<uint16, Promise<Variant>> ();
|
||||
private uint16 next_request_id = 1;
|
||||
|
||||
private const int COMMAND_TIMEOUT_MS = 25000;
|
||||
|
||||
public static async AgentConnection open (AgentConfig agent_config, ImageConfig? image_config, Machine machine,
|
||||
Allocator allocator, Cancellable? cancellable) throws Error, IOError {
|
||||
var connection = new AgentConnection () {
|
||||
agent_config = agent_config,
|
||||
image_config = image_config,
|
||||
machine = machine,
|
||||
allocator = allocator,
|
||||
};
|
||||
|
||||
try {
|
||||
yield connection.init_async (Priority.DEFAULT, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
private async bool init_async (int io_priority, Cancellable? cancellable) throws Error, IOError {
|
||||
HostlinkTransportConfig? transport_config = agent_config.transport as HostlinkTransportConfig;
|
||||
if (transport_config == null)
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported transport config: only hostlink is supported for now");
|
||||
|
||||
var qmp = yield QmpClient.open (transport_config.qmp, 0, cancellable);
|
||||
var link = yield qmp.open_hostlink (cancellable);
|
||||
hostlink = link.connection;
|
||||
input = (BufferedInputStream) Object.new (typeof (BufferedInputStream),
|
||||
"base-stream", hostlink.get_input_stream (),
|
||||
"close-base-stream", false,
|
||||
"buffer-size", 128 * 1024);
|
||||
output = hostlink.get_output_stream ();
|
||||
|
||||
var gdb = machine.gdb;
|
||||
ByteOrder byte_order = gdb.byte_order;
|
||||
uint pointer_size = gdb.pointer_size;
|
||||
|
||||
uint64 kernel_base;
|
||||
Layout layout;
|
||||
if (image_config != null) {
|
||||
kernel_base = image_config.base.address;
|
||||
layout = yield Layout.load_from_symbol_source (File.new_for_path (image_config.file), kernel_base,
|
||||
byte_order, pointer_size, cancellable);
|
||||
} else {
|
||||
kernel_base = 0;
|
||||
layout = new Layout.empty ();
|
||||
}
|
||||
if (kernel_base == 0)
|
||||
throw new Error.NOT_SUPPORTED ("Missing kernel_base");
|
||||
|
||||
var symbols = new Gee.HashMap<string, SymbolInfo> ();
|
||||
var hash_builder = new SymbolHashBuilder ();
|
||||
foreach (var s in layout.symbols) {
|
||||
symbols[s.name] = s;
|
||||
hash_builder.add_symbol (s);
|
||||
}
|
||||
if (image_config != null) {
|
||||
foreach (var e in image_config.symbols.entries) {
|
||||
unowned string name = e.key;
|
||||
if (!symbols.has_key (name)) {
|
||||
var s = new SymbolInfo () {
|
||||
name = name,
|
||||
offset = (uint32) e.value,
|
||||
symbol_type = 0xf,
|
||||
section = 0x10, // FIXME
|
||||
};
|
||||
symbols[name] = s;
|
||||
hash_builder.add_symbol (s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SymbolInfo? thread_block = symbols["thread_block"];
|
||||
if (thread_block == null)
|
||||
throw new Error.NOT_SUPPORTED ("Missing symbol for thread_block");
|
||||
|
||||
var config_builder = new VariantBuilder (new VariantType ("(tuta(ssuuuu)ay)"));
|
||||
config_builder.add ("t", link.mmio);
|
||||
config_builder.add ("u", link.irq);
|
||||
config_builder.add ("t", kernel_base);
|
||||
|
||||
config_builder.open (new VariantType ("a(ssuuuu)"));
|
||||
foreach (var m in layout.modules) {
|
||||
config_builder.add ("(ssuuuu)",
|
||||
m.name,
|
||||
m.version,
|
||||
m.offset,
|
||||
m.size,
|
||||
m.start_func_offset,
|
||||
m.stop_func_offset
|
||||
);
|
||||
}
|
||||
config_builder.close ();
|
||||
|
||||
Bytes symbol_data = hash_builder.build (byte_order);
|
||||
config_builder.add_value (Variant.new_from_data (new VariantType ("ay"), symbol_data.get_data (), true,
|
||||
symbol_data));
|
||||
|
||||
Gum.ElfModule elf;
|
||||
try {
|
||||
elf = new Gum.ElfModule.from_file (agent_config.path);
|
||||
} catch (Gum.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("%s", e.message);
|
||||
}
|
||||
|
||||
var raw_elf = gdb.make_buffer (new Bytes (elf.get_file_data ()));
|
||||
var missing_symbols = new Gee.ArrayList<string> ();
|
||||
elf.enumerate_symbols (s => {
|
||||
unowned Gum.ElfSectionDetails? sect = s.section;
|
||||
if (sect != null && sect.name == ".kernel_addrs") {
|
||||
string name = s.name[1:];
|
||||
SymbolInfo? info = symbols[name];
|
||||
if (info != null) {
|
||||
size_t file_offset = (size_t) (sect.offset + (s.address - sect.address));
|
||||
raw_elf.write_pointer (file_offset, kernel_base + info.offset);
|
||||
} else {
|
||||
missing_symbols.add (name);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!missing_symbols.is_empty) {
|
||||
throw new Error.INVALID_ARGUMENT ("Missing symbols for: %s",
|
||||
string.joinv (", ", missing_symbols.to_array ()));
|
||||
}
|
||||
|
||||
yield machine.enter_exception_level (1, 1000, cancellable);
|
||||
|
||||
var bp = yield gdb.add_breakpoint (SOFT, kernel_base + thread_block.offset, 4, cancellable);
|
||||
GDB.Breakpoint? hit_breakpoint = null;
|
||||
do {
|
||||
var exception = yield gdb.continue_until_exception (cancellable);
|
||||
hit_breakpoint = exception.breakpoint;
|
||||
} while (hit_breakpoint != bp);
|
||||
yield bp.remove (cancellable);
|
||||
|
||||
size_t page_size = yield machine.query_page_size (cancellable);
|
||||
|
||||
elf_allocation = yield inject_elf (elf, raw_elf.bytes, page_size, machine, allocator, cancellable);
|
||||
|
||||
uint64 start_address = 0;
|
||||
uint64 remap_writable_pages_address = 0;
|
||||
uint64 mprotect_address = 0;
|
||||
uint64 base_va = elf_allocation.virtual_address;
|
||||
elf.enumerate_symbols (e => {
|
||||
if (e.name == "_start")
|
||||
start_address = base_va + e.address;
|
||||
else if (e.name == "gum_barebone_try_remap_writable_pages")
|
||||
remap_writable_pages_address = base_va + e.address;
|
||||
else if (e.name == "gum_try_mprotect")
|
||||
mprotect_address = base_va + e.address;
|
||||
else
|
||||
return true;
|
||||
return start_address == 0 || mprotect_address == 0 || remap_writable_pages_address == 0;
|
||||
});
|
||||
if (start_address == 0)
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid agent: no _start symbol found");
|
||||
if (remap_writable_pages_address == 0)
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid agent: no gum_barebone_try_remap_writable_pages symbol found");
|
||||
if (mprotect_address == 0)
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid agent: no gum_try_mprotect symbol found");
|
||||
|
||||
remap_writable_pages_callback = yield new Callback (remap_writable_pages_address,
|
||||
new RemapWritablePagesHandler (machine), machine, cancellable);
|
||||
mprotect_callback = yield new Callback (mprotect_address, new MemoryProtectHandler (machine), machine, cancellable);
|
||||
|
||||
var config_blob = config_builder.end ().get_data_as_bytes ();
|
||||
config_allocation = yield allocator.allocate (config_blob.get_size (), 8, cancellable);
|
||||
|
||||
yield gdb.write_byte_array (config_allocation.virtual_address, config_blob, cancellable);
|
||||
|
||||
yield machine.invoke (start_address, {
|
||||
config_allocation.virtual_address,
|
||||
config_allocation.size
|
||||
},
|
||||
cancellable);
|
||||
|
||||
yield gdb.continue (cancellable);
|
||||
|
||||
process_incoming_messages.begin ();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public async void close (Cancellable? cancellable) throws IOError {
|
||||
io_cancellable.cancel ();
|
||||
}
|
||||
|
||||
public async AgentScriptId create_script (string source, Cancellable? cancellable) throws Error, IOError {
|
||||
var payload = new Variant ("s", source);
|
||||
var response = yield execute_command (Command.CREATE_SCRIPT, payload, cancellable);
|
||||
if (!response.check_format_string ("u", false))
|
||||
throw new Error.PROTOCOL ("Invalid create_script response format");
|
||||
uint32 script_handle;
|
||||
response.get ("u", out script_handle);
|
||||
return AgentScriptId (script_handle);
|
||||
}
|
||||
|
||||
public async void load_script (AgentScriptId script_id, Cancellable? cancellable) throws Error, IOError {
|
||||
var payload = new Variant ("u", script_id.handle);
|
||||
yield execute_command (Command.LOAD_SCRIPT, payload, cancellable);
|
||||
}
|
||||
|
||||
public async void destroy_script (AgentScriptId script_id, Cancellable? cancellable) throws Error, IOError {
|
||||
var payload = new Variant ("u", script_id.handle);
|
||||
yield execute_command (Command.DESTROY_SCRIPT, payload, cancellable);
|
||||
}
|
||||
|
||||
public async void post_script_message (AgentScriptId script_id, string message, Bytes? data, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
var payload = new Variant ("(us)", script_id.handle, message);
|
||||
// TODO: Include data.
|
||||
yield execute_command (Command.POST_SCRIPT_MESSAGE, payload, cancellable);
|
||||
}
|
||||
|
||||
private async Variant execute_command (Command command, Variant payload, Cancellable? cancellable) throws Error, IOError {
|
||||
uint16 request_id = next_request_id++;
|
||||
|
||||
var command_message = new Variant ("(yqv)", (uint8) command, request_id, payload);
|
||||
if (machine.gdb.byte_order != ByteOrder.HOST)
|
||||
command_message = command_message.byteswap ();
|
||||
var command_bytes = command_message.get_data_as_bytes ();
|
||||
|
||||
var builder = machine.gdb.make_buffer_builder ();
|
||||
Bytes frame = builder
|
||||
.append_uint32 ((uint32) command_bytes.get_size ())
|
||||
.append_bytes (command_bytes)
|
||||
.build ();
|
||||
|
||||
var promise = new Promise<Variant> ();
|
||||
pending_requests[request_id] = promise;
|
||||
|
||||
try {
|
||||
yield output.write_all_async (frame.get_data (), Priority.DEFAULT, cancellable, null);
|
||||
} catch (GLib.Error e) {
|
||||
pending_requests.unset (request_id);
|
||||
throw new Error.TRANSPORT ("%s", e.message);
|
||||
}
|
||||
|
||||
var timeout_source = new TimeoutSource (COMMAND_TIMEOUT_MS);
|
||||
timeout_source.set_callback (() => {
|
||||
Promise<Variant>? p;
|
||||
if (pending_requests.unset (request_id, out p))
|
||||
p.reject (new Error.TIMED_OUT ("Command timed out"));
|
||||
return Source.REMOVE;
|
||||
});
|
||||
timeout_source.attach (MainContext.get_thread_default ());
|
||||
|
||||
try {
|
||||
return yield promise.future.wait_async (cancellable);
|
||||
} finally {
|
||||
timeout_source.destroy ();
|
||||
}
|
||||
}
|
||||
|
||||
private async void process_incoming_messages () {
|
||||
var byte_order = machine.gdb.byte_order;
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
size_t header_size = 4;
|
||||
if (input.get_available () < header_size)
|
||||
yield fill_until_n_bytes_available (header_size);
|
||||
|
||||
uint32 body_size = 0;
|
||||
unowned uint8[] size_buf = ((uint8[]) &body_size)[:4];
|
||||
input.peek (size_buf);
|
||||
body_size = uint32.from_little_endian (body_size);
|
||||
|
||||
size_t full_size = header_size + body_size;
|
||||
if (input.get_available () < full_size)
|
||||
yield fill_until_n_bytes_available (full_size);
|
||||
|
||||
var body = new uint8[body_size];
|
||||
input.peek (body, header_size);
|
||||
|
||||
input.skip (full_size, io_cancellable);
|
||||
|
||||
var raw_message = new Bytes.take ((owned) body);
|
||||
|
||||
var message = Variant.new_from_data (new VariantType ("(yqv)"), raw_message.get_data (), false,
|
||||
raw_message);
|
||||
if (byte_order != ByteOrder.HOST)
|
||||
message = message.byteswap ();
|
||||
if (!message.check_format_string ("(yqv)", false))
|
||||
throw new Error.PROTOCOL ("Invalid message format");
|
||||
|
||||
uint8 command_code;
|
||||
uint16 request_id;
|
||||
Variant payload;
|
||||
message.get ("(yqv)", out command_code, out request_id, out payload);
|
||||
|
||||
if (command_code == Command.SCRIPT_MESSAGE) {
|
||||
if (!payload.check_format_string ("(us)", false))
|
||||
throw new Error.PROTOCOL ("Invalid script message payload format");
|
||||
|
||||
uint32 script_handle;
|
||||
unowned string json;
|
||||
payload.get ("(u&s)", out script_handle, out json);
|
||||
|
||||
script_message (AgentScriptId (script_handle), json, null);
|
||||
} else if (command_code == Command.REPLY) {
|
||||
Promise<Variant>? promise;
|
||||
if (pending_requests.unset (request_id, out promise))
|
||||
promise.resolve (payload);
|
||||
}
|
||||
}
|
||||
} catch (GLib.Error e) {
|
||||
}
|
||||
}
|
||||
|
||||
private async void fill_until_n_bytes_available (size_t minimum) throws Error, IOError {
|
||||
size_t available = input.get_available ();
|
||||
while (available < minimum) {
|
||||
if (input.get_buffer_size () < minimum)
|
||||
input.set_buffer_size (minimum);
|
||||
|
||||
ssize_t n;
|
||||
try {
|
||||
n = yield input.fill_async ((ssize_t) (input.get_buffer_size () - available), Priority.DEFAULT,
|
||||
io_cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.TRANSPORT ("Connection closed");
|
||||
}
|
||||
|
||||
if (n == 0)
|
||||
throw new Error.TRANSPORT ("Connection closed");
|
||||
|
||||
available += n;
|
||||
}
|
||||
}
|
||||
|
||||
private class RemapWritablePagesHandler : Object, CallbackHandler {
|
||||
public signal void output (string message);
|
||||
|
||||
public uint arity {
|
||||
get { return 2; }
|
||||
}
|
||||
|
||||
private Machine machine;
|
||||
|
||||
public RemapWritablePagesHandler (Machine machine) {
|
||||
this.machine = machine;
|
||||
}
|
||||
|
||||
public async uint64 handle_invocation (uint64[] args, CallFrame frame, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
var pages = args[0];
|
||||
var num_pages = (uint) args[1];
|
||||
|
||||
var physical_addresses = new Gee.ArrayList<uint64?> ();
|
||||
var gdb = machine.gdb;
|
||||
var reader = new BufferReader (yield gdb.read_buffer (pages, num_pages * gdb.pointer_size, cancellable));
|
||||
for (uint i = 0; i != num_pages; i++)
|
||||
physical_addresses.add (reader.read_pointer ());
|
||||
|
||||
Allocation allocation = yield machine.allocate_pages (physical_addresses, cancellable);
|
||||
// TODO: Handle cleanup.
|
||||
|
||||
return allocation.virtual_address;
|
||||
}
|
||||
}
|
||||
|
||||
private class MemoryProtectHandler : Object, CallbackHandler {
|
||||
public signal void output (string message);
|
||||
|
||||
public uint arity {
|
||||
get { return 3; }
|
||||
}
|
||||
|
||||
private Machine machine;
|
||||
|
||||
public MemoryProtectHandler (Machine machine) {
|
||||
this.machine = machine;
|
||||
}
|
||||
|
||||
public async uint64 handle_invocation (uint64[] args, CallFrame frame, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
var address = args[0];
|
||||
var size = (size_t) args[1];
|
||||
var prot = (Gum.PageProtection) args[2];
|
||||
try {
|
||||
yield machine.protect_pages (address, size, prot, cancellable);
|
||||
return 1;
|
||||
} catch (GLib.Error e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum Command {
|
||||
CREATE_SCRIPT = 1,
|
||||
LOAD_SCRIPT = 2,
|
||||
DESTROY_SCRIPT = 3,
|
||||
POST_SCRIPT_MESSAGE = 4,
|
||||
REPLY = 128,
|
||||
SCRIPT_MESSAGE = 129
|
||||
}
|
||||
|
||||
private enum Status {
|
||||
IDLE,
|
||||
BUSY,
|
||||
DATA_READY,
|
||||
ERROR
|
||||
}
|
||||
}
|
||||
|
||||
private class SymbolHashBuilder : Object {
|
||||
private Gee.Map<string, Gee.List<SymbolInfo>> symbol_table = new Gee.TreeMap<string, Gee.List<SymbolInfo>> ();
|
||||
|
||||
public void add_symbol (SymbolInfo symbol) {
|
||||
var symbol_list = symbol_table[symbol.name];
|
||||
if (symbol_list == null) {
|
||||
symbol_list = new Gee.ArrayList<SymbolInfo> ();
|
||||
symbol_table[symbol.name] = symbol_list;
|
||||
}
|
||||
symbol_list.add (symbol);
|
||||
}
|
||||
|
||||
public Bytes build (ByteOrder byte_order) {
|
||||
var builder = new BufferBuilder (byte_order);
|
||||
|
||||
var all_symbols = new Gee.ArrayList<SymbolInfo> ();
|
||||
foreach (var entry in symbol_table.entries) {
|
||||
foreach (var symbol in entry.value)
|
||||
all_symbols.add (symbol);
|
||||
}
|
||||
|
||||
uint total_symbols = all_symbols.size;
|
||||
builder.append_uint32 (total_symbols);
|
||||
|
||||
var name_index_offset = builder.offset;
|
||||
builder.skip (total_symbols * 4);
|
||||
|
||||
var addr_index_offset = builder.offset;
|
||||
builder.skip (total_symbols * 4);
|
||||
|
||||
var symbol_offsets = new uint32[total_symbols];
|
||||
for (uint i = 0; i != total_symbols; i++) {
|
||||
var symbol = all_symbols[(int) i];
|
||||
|
||||
builder.align (4);
|
||||
symbol_offsets[i] = (uint32) builder.offset;
|
||||
|
||||
builder.append_uint32 (symbol.offset);
|
||||
// TODO: Only include details we need.
|
||||
builder.append_uint8 (symbol.symbol_type);
|
||||
builder.append_uint8 (symbol.section);
|
||||
builder.append_uint16 (symbol.description);
|
||||
builder.append_string (symbol.name, StringTerminator.NUL);
|
||||
}
|
||||
|
||||
for (uint i = 0; i != total_symbols; i++)
|
||||
builder.write_uint32 (name_index_offset + (i * 4), symbol_offsets[i]);
|
||||
|
||||
var addr_sorted_symbols = new Gee.ArrayList<int> ();
|
||||
for (uint i = 0; i != total_symbols; i++)
|
||||
addr_sorted_symbols.add ((int) i);
|
||||
addr_sorted_symbols.sort ((a, b) => {
|
||||
var symbol_a = all_symbols[a];
|
||||
var symbol_b = all_symbols[b];
|
||||
if (symbol_a.offset < symbol_b.offset)
|
||||
return -1;
|
||||
if (symbol_a.offset > symbol_b.offset)
|
||||
return 1;
|
||||
return 0;
|
||||
});
|
||||
|
||||
for (uint i = 0; i != total_symbols; i++) {
|
||||
int original_index = addr_sorted_symbols[(int) i];
|
||||
uint symbol_data_offset = symbol_offsets[original_index];
|
||||
builder.write_uint32 (addr_index_offset + (i * 4), symbol_data_offset);
|
||||
}
|
||||
|
||||
return builder.build ();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
[build]
|
||||
target = "aarch64-unknown-none"
|
||||
Generated
+296
@@ -0,0 +1,296 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bindgen"
|
||||
version = "0.72.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f72209734318d0b619a5e0f5129918b848c416e122a3c4ce054e03cb87b726f"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"itertools",
|
||||
"log",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
"rustc-hash",
|
||||
"shlex",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d487aa071b5f64da6f19a3e848e3578944b726ee5a4854b82172f02aa876bfdc"
|
||||
dependencies = [
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cexpr"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
|
||||
dependencies = [
|
||||
"nom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
|
||||
|
||||
[[package]]
|
||||
name = "clang-sys"
|
||||
version = "1.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
|
||||
dependencies = [
|
||||
"glob",
|
||||
"libc",
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
|
||||
|
||||
[[package]]
|
||||
name = "frida-barebone-agent"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.174"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
|
||||
|
||||
[[package]]
|
||||
name = "libloading"
|
||||
version = "0.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "7.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.2.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "061c1221631e079b26479d25bbf2275bfe5917ae8419cd7e34f13bfc2aa7539a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.95"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.40"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.53.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.53.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.53.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.53.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.53.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.53.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.53.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.53.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.53.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "frida-barebone-agent"
|
||||
version = "1.0.0"
|
||||
edition = "2024"
|
||||
build = "build.rs"
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
opt-level = "z"
|
||||
overflow-checks = false
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
|
||||
[profile.dev]
|
||||
panic = "abort"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.2"
|
||||
bindgen = "0.72.0"
|
||||
@@ -0,0 +1,43 @@
|
||||
## Getting the C toolchain
|
||||
|
||||
npm install -g xpm
|
||||
xpm install
|
||||
export PATH=$PWD/xpacks/.bin:$PATH
|
||||
|
||||
## How to build Gum
|
||||
|
||||
./configure \
|
||||
--host=aarch64-none-elf \
|
||||
--enable-gumjs \
|
||||
--with-devkits=gum,gumjs \
|
||||
--with-devkit-symbol-scope=original
|
||||
make
|
||||
export GUMJS_DEVKIT_DIR=$PWD/build/bindings/gumjs/devkit
|
||||
|
||||
## Building
|
||||
|
||||
export PATH=$PWD/xpacks/.bin:$PATH
|
||||
export CC_aarch64_unknown_none=aarch64-none-elf-gcc
|
||||
export AR_aarch64_unknown_none=aarch64-none-elf-ar
|
||||
export RANLIB_aarch64_unknown_none=aarch64-none-elf-ranlib
|
||||
|
||||
## Development loop
|
||||
|
||||
export FRIDA_BAREBONE_CONFIG=$PWD/etc/xnu.json
|
||||
cargo build --release && make -C ~/src/frida-python && killall -9 qemu-system-aarch64 && sleep 2 && frida -D barebone -p 0
|
||||
|
||||
## Speeding up loop
|
||||
|
||||
./configure \
|
||||
-- \
|
||||
-Dfrida-core:compat=disabled \
|
||||
-Dfrida-core:local_backend=disabled \
|
||||
-Dfrida-core:fruity_backend=disabled \
|
||||
-Dfrida-core:droidy_backend=disabled \
|
||||
-Dfrida-core:socket_backend=disabled \
|
||||
-Dfrida-core:compiler_backend=disabled \
|
||||
-Dfrida-core:gadget=disabled \
|
||||
-Dfrida-core:server=disabled \
|
||||
-Dfrida-core:portal=disabled \
|
||||
-Dfrida-core:inject=disabled \
|
||||
-Dfrida-core:tests=enabled
|
||||
@@ -0,0 +1,51 @@
|
||||
SECTIONS {
|
||||
.text : {
|
||||
*(.text.entrypoint)
|
||||
*(.text*)
|
||||
}
|
||||
.rodata : {
|
||||
*(.rodata*)
|
||||
}
|
||||
.kernel_addrs : ALIGN(8) {
|
||||
. = ALIGN(8);
|
||||
_panic = .; . += 8;
|
||||
_IOLog = .; . += 8;
|
||||
_kalloc = .; . += 8;
|
||||
_kfree = .; . += 8;
|
||||
_kernel_thread_start = .; . += 8;
|
||||
_assert_wait = .; . += 8;
|
||||
_assert_wait_timeout = .; . += 8;
|
||||
_thread_block = .; . += 8;
|
||||
_thread_wakeup = .; . += 8;
|
||||
_mach_absolute_time = .; . += 8;
|
||||
_absolutetime_to_nanoseconds = .; . += 8;
|
||||
_clock_get_calendar_microtime = .; . += 8;
|
||||
_ml_io_map = .; . += 8;
|
||||
_ml_vtophys = .; . += 8;
|
||||
__ZN9IOService11getPlatformEv = .; . += 8;
|
||||
__ZN9IOServiceC2Ev = .; . += 8;
|
||||
__ZN8OSSymbol17withCStringNoCopyEPKc = .; . += 8;
|
||||
__ZN6OSData9withBytesEPKvj = .; . += 8;
|
||||
}
|
||||
.data.rel.ro : {
|
||||
*(.data.rel.ro*)
|
||||
}
|
||||
.got : {
|
||||
*(.got*)
|
||||
}
|
||||
.bss : {
|
||||
*(.bss*)
|
||||
}
|
||||
. = ALIGN(8);
|
||||
_heap_start = .;
|
||||
}
|
||||
|
||||
VERSION {
|
||||
{
|
||||
global:
|
||||
_start;
|
||||
|
||||
local:
|
||||
*;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
use std::{
|
||||
env, fs,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
fn main() {
|
||||
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
|
||||
let devkit_dir = PathBuf::from(env::var("GUMJS_DEVKIT_DIR").unwrap());
|
||||
|
||||
let cc_str = env::var("CC_aarch64_unknown_none")
|
||||
.or_else(|_| env::var("CC"))
|
||||
.unwrap_or_else(|_| "cc".to_string());
|
||||
let cc = Path::new(&cc_str);
|
||||
let cc_include_paths = detect_gcc_include_paths(cc);
|
||||
let cc_library_paths = detect_gcc_library_paths(cc);
|
||||
|
||||
let cc_clang_args: Vec<String> = cc_include_paths
|
||||
.iter()
|
||||
.flat_map(|path| vec!["-isystem".to_string(), path.to_string_lossy().into_owned()])
|
||||
.collect();
|
||||
|
||||
let bindings = bindgen::Builder::default()
|
||||
.use_core()
|
||||
.header(devkit_dir.join("frida-gumjs.h").to_str().unwrap())
|
||||
.clang_arg("-nostdinc")
|
||||
.clang_arg("-target")
|
||||
.clang_arg("aarch64-none-elf")
|
||||
.clang_args(cc_clang_args)
|
||||
.clang_arg(format!("-I{}", devkit_dir.to_str().unwrap()))
|
||||
.merge_extern_blocks(true)
|
||||
.generate()
|
||||
.expect("Unable to generate bindings");
|
||||
|
||||
bindings
|
||||
.write_to_file(out_dir.join("bindings.rs"))
|
||||
.expect("Couldn't write bindings");
|
||||
|
||||
println!(
|
||||
"cargo:rustc-link-search=native={}",
|
||||
devkit_dir.to_str().unwrap()
|
||||
);
|
||||
println!("cargo:rustc-link-lib=static=frida-gumjs");
|
||||
for path in cc_library_paths {
|
||||
println!("cargo:rustc-link-search=native={}", path.to_string_lossy());
|
||||
}
|
||||
println!("cargo:rustc-link-lib=static=c");
|
||||
println!("cargo:rustc-link-lib=static=m");
|
||||
println!("cargo:rustc-link-arg=--export-dynamic");
|
||||
println!("cargo:rustc-link-arg=--emit-relocs");
|
||||
println!("cargo:rustc-link-arg=--script=agent.lds");
|
||||
println!("cargo:rustc-link-arg=--gc-sections");
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
}
|
||||
|
||||
pub fn detect_gcc_include_paths(gcc: &Path) -> Vec<PathBuf> {
|
||||
let out = Command::new(gcc)
|
||||
.args(["-xc", "-E", "-v", "-"])
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.expect("Failed to execute GCC to detect include paths");
|
||||
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
|
||||
let mut grab = false;
|
||||
let mut paths = Vec::<PathBuf>::new();
|
||||
|
||||
for line in stderr.lines() {
|
||||
if line.starts_with("#include <...> search starts here:") {
|
||||
grab = true;
|
||||
continue;
|
||||
}
|
||||
if line.starts_with("End of search list.") {
|
||||
break;
|
||||
}
|
||||
if !grab {
|
||||
continue;
|
||||
}
|
||||
|
||||
let raw = line.trim();
|
||||
if raw.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let p = Path::new(raw);
|
||||
if p.exists() {
|
||||
let canonical = fs::canonicalize(p).expect("Failed to canonicalize include path");
|
||||
if !paths.contains(&canonical) {
|
||||
paths.push(canonical);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
paths
|
||||
}
|
||||
|
||||
pub fn detect_gcc_library_paths(gcc: &Path) -> Vec<PathBuf> {
|
||||
let out = Command::new(gcc).arg("-print-search-dirs").output()
|
||||
.expect("Failed to execute GCC to detect library paths");
|
||||
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let line = stdout.lines().find(|l| l.starts_with("libraries:"))
|
||||
.expect("Failed to find libraries line in GCC output");
|
||||
|
||||
let raw_dirs = line.trim_start_matches("libraries: =");
|
||||
let sep = if cfg!(windows) { ';' } else { ':' };
|
||||
|
||||
let mut paths = Vec::new();
|
||||
for raw in raw_dirs.split(sep) {
|
||||
if raw.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let p = Path::new(raw);
|
||||
if !p.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let canonical = fs::canonicalize(p).expect("Failed to canonicalize library path");
|
||||
if !paths.contains(&canonical) {
|
||||
paths.push(canonical);
|
||||
}
|
||||
}
|
||||
|
||||
paths
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export FRIDA_BAREBONE_CONFIG=$PWD/etc/xnu.json
|
||||
export PYTHONPATH=$HOME/src/frida-python
|
||||
|
||||
export PATH=$PWD/xpacks/.bin:$PATH
|
||||
export CC_aarch64_unknown_none=aarch64-none-elf-gcc
|
||||
export AR_aarch64_unknown_none=aarch64-none-elf-ar
|
||||
export RANLIB_aarch64_unknown_none=aarch64-none-elf-ranlib
|
||||
export GUMJS_DEVKIT_DIR=/home/oleavr/src/frida-gum/build/bindings/gumjs/devkit
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"connection": {
|
||||
"host": "127.0.0.1",
|
||||
"port": 9000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"connection": {
|
||||
"host": "127.0.0.1",
|
||||
"port": 9000
|
||||
},
|
||||
"allocator": {
|
||||
"mode": "physical",
|
||||
"physical_base": "0x8ec9b4000"
|
||||
},
|
||||
"agent": {
|
||||
"path": "/Users/oleavr/src/frida-core/src/barebone/agent/target/aarch64-unknown-none/debug/frida-barebone-agent",
|
||||
"transport": {
|
||||
"type": "ram",
|
||||
"path": "/Volumes/RAM Disk/ios-dram",
|
||||
"base_address": "0x800000000"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"connection": {
|
||||
"host": "127.0.0.1",
|
||||
"port": 9000
|
||||
},
|
||||
"allocator": {
|
||||
"mode": "target-functions",
|
||||
"alloc_function": "0xfffffff007a3c278",
|
||||
"free_function": "0xfffffff007a3c338"
|
||||
},
|
||||
"agent": {
|
||||
"path": "/Users/oleavr/src/frida-core/src/barebone/agent/target/aarch64-unknown-none/release/frida-barebone-agent",
|
||||
"transport": {
|
||||
"type": "hostlink",
|
||||
"qmp": "unix:/Users/oleavr/src/frida-barebone-ios/qmp.sock"
|
||||
}
|
||||
},
|
||||
"image": {
|
||||
"file": "/Users/oleavr/src/frida-barebone-ios/iPhone11_8_iPhone12_1_14.0_18A5351d_Restore/kernelcache.research.iphone12b",
|
||||
"base": "0xfffffff007004000",
|
||||
"symbols": {
|
||||
"IOLog": "0xfedb68",
|
||||
"_ZN6OSData9withBytesEPKvj": "0xf88588",
|
||||
"_ZN8OSSymbol17withCStringNoCopyEPKc": "0xfc05dc",
|
||||
"_ZN9IOService11getPlatformEv": "0x101ad48",
|
||||
"_ZN9IOServiceC2Ev": "0x1018318",
|
||||
"absolutetime_to_nanoseconds": "0xb5d1e4",
|
||||
"assert_wait": "0xa4d294",
|
||||
"assert_wait_timeout": "0xa4d430",
|
||||
"clock_get_calendar_microtime": "0xa1f32c",
|
||||
"kalloc": "0xa38278",
|
||||
"kernel_thread_start": "0xa70674",
|
||||
"kfree": "0xa38338",
|
||||
"mach_absolute_time": "0xb5ccc0",
|
||||
"ml_io_map": "0xb57a04",
|
||||
"ml_vtophys": "0xb584a0",
|
||||
"panic": "0x27d7944",
|
||||
"thread_block": "0xa51728",
|
||||
"thread_wakeup": "0xa54ea0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
const _copyinstr = new NativeFunction(
|
||||
DebugSymbol.getFunctionByName('copyinstr'),
|
||||
'int',
|
||||
['pointer', 'pointer', 'size_t', 'pointer']);
|
||||
const { pointerSize } = Process;
|
||||
|
||||
Interceptor.attach(DebugSymbol.getFunctionByName('__mac_execve'), {
|
||||
onEnter(args) {
|
||||
const fname = copyinstr(args[1].readPointer());
|
||||
console.log(`>>> __mac_execve() fname=${fname}`);
|
||||
},
|
||||
onLeave(retval) {
|
||||
console.log(`<<< __mac_execve() => ${retval.toInt32()}`);
|
||||
}
|
||||
});
|
||||
|
||||
Interceptor.attach(DebugSymbol.getFunctionByName('posix_spawn'), {
|
||||
onEnter(args) {
|
||||
const path = copyinstr(args[1].add(pointerSize).readPointer());
|
||||
console.log(`>>> posix_spawn() path=${path}`);
|
||||
},
|
||||
onLeave(retval) {
|
||||
console.log(`<<< posix_spawn() => ${retval.toInt32()}`);
|
||||
}
|
||||
});
|
||||
|
||||
function copyinstr(userAddr) {
|
||||
const bufSize = 4096;
|
||||
const buf = Memory.alloc(bufSize);
|
||||
const actual = Memory.alloc(pointerSize);
|
||||
if (_copyinstr(userAddr, buf, bufSize, actual) !== 0)
|
||||
throw new Error('copyinstr failed');
|
||||
return buf.readUtf8String();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
console.log("Agent loading");
|
||||
const cm = new CModule(File.readAllBytes("./target/aarch64-unknown-none/release/frida-barebone-agent"));
|
||||
//const cm = new CModule(File.readAllBytes("./target/aarch64-unknown-none/debug/frida-barebone-agent"));
|
||||
|
||||
const start = new NativeFunction(cm._start, "pointer", []);
|
||||
const bufferPhysicalAddress = start();
|
||||
console.log("Ready! Buffer is at physical address:", bufferPhysicalAddress);
|
||||
$gdb.continue();
|
||||
|
||||
Object.assign(globalThis, { cm, start });
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "frida-barebone-agent",
|
||||
"version": "1.0.0",
|
||||
"description": "xPack configuration for frida-barebone-agent",
|
||||
"xpack": {
|
||||
"minimumXpmRequired": "0.20.8",
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@xpack-dev-tools/aarch64-none-elf-gcc": {
|
||||
"specifier": "14.2.1-1.1.1",
|
||||
"local": "link",
|
||||
"platforms": "all"
|
||||
}
|
||||
},
|
||||
"properties": {},
|
||||
"actions": {},
|
||||
"buildConfigurations": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
use core::ptr;
|
||||
|
||||
use crate::bindings::{g_wait_is_set, gint64, gpointer};
|
||||
use crate::xnu;
|
||||
|
||||
const G_WAIT_INFINITE: gint64 = -1;
|
||||
|
||||
pub static mut WAKEUP_TOKEN: u64 = 0;
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_get_monotonic_time() -> gint64 {
|
||||
let abstime = xnu::mach_absolute_time();
|
||||
let time = xnu::absolutetime_to_nanoseconds(abstime);
|
||||
(time / 1000) as gint64
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_wait_sleep(token: gpointer, timeout_us: gint64) {
|
||||
let wait_event = ptr::addr_of_mut!(WAKEUP_TOKEN) as *const u8;
|
||||
|
||||
let wait_result = if timeout_us == G_WAIT_INFINITE {
|
||||
xnu::assert_wait(wait_event, xnu::THREAD_INTERRUPTIBLE)
|
||||
} else {
|
||||
xnu::assert_wait_timeout(
|
||||
wait_event,
|
||||
xnu::THREAD_INTERRUPTIBLE,
|
||||
(timeout_us * 1000) as u32,
|
||||
1, // TODO
|
||||
)
|
||||
};
|
||||
if wait_result != xnu::THREAD_WAITING {
|
||||
panic!("assert_wait_timeout failed: {}", wait_result);
|
||||
}
|
||||
|
||||
if unsafe { g_wait_is_set(token) != 0 } {
|
||||
xnu::thread_wakeup(wait_event);
|
||||
return;
|
||||
}
|
||||
|
||||
xnu::thread_block(None);
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_wait_wake(_token: gpointer) {
|
||||
xnu::thread_wakeup(ptr::addr_of_mut!(WAKEUP_TOKEN) as *const u8);
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
use crate::bindings::GCond;
|
||||
use crate::bindings::GMutex;
|
||||
use crate::bindings::GPrivate;
|
||||
use crate::bindings::GRWLock;
|
||||
use crate::bindings::GRecMutex;
|
||||
use crate::bindings::GSystemThread;
|
||||
use crate::bindings::GThreadFunc;
|
||||
use crate::bindings::{gpointer, gulong};
|
||||
use alloc::boxed::Box;
|
||||
use alloc::collections::BTreeMap;
|
||||
use core::arch::asm;
|
||||
use core::ffi::c_void;
|
||||
use core::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
|
||||
// Our implementation structures that overlay the opaque GLib structures
|
||||
|
||||
#[repr(C, align(8))]
|
||||
struct MutexImpl {
|
||||
lock: AtomicU32,
|
||||
_padding: [u8; core::mem::size_of::<GMutex>() - core::mem::size_of::<AtomicU32>()],
|
||||
}
|
||||
|
||||
#[repr(C, align(8))]
|
||||
struct RecMutexImpl {
|
||||
owner: AtomicU64, // Thread ID of the owner (uses the 'p' field)
|
||||
count: AtomicU32, // Recursion count (uses i[0])
|
||||
_unused: u32, // Unused (uses i[1])
|
||||
}
|
||||
|
||||
#[repr(C, align(8))]
|
||||
struct RWLockImpl {
|
||||
state: AtomicU32, // Lock state (readers count + writer bit)
|
||||
_padding: [u8; core::mem::size_of::<GRWLock>() - core::mem::size_of::<AtomicU32>()],
|
||||
}
|
||||
|
||||
#[repr(C, align(8))]
|
||||
struct CondImpl {
|
||||
signal: AtomicU32, // Signal state
|
||||
_padding: [u8; core::mem::size_of::<GCond>() - core::mem::size_of::<AtomicU32>()],
|
||||
}
|
||||
|
||||
const _: () = assert!(core::mem::size_of::<MutexImpl>() == core::mem::size_of::<GMutex>());
|
||||
const _: () = assert!(core::mem::align_of::<MutexImpl>() == core::mem::align_of::<GMutex>());
|
||||
const _: () = assert!(core::mem::size_of::<RecMutexImpl>() == core::mem::size_of::<GRecMutex>());
|
||||
const _: () = assert!(core::mem::align_of::<RecMutexImpl>() == core::mem::align_of::<GRecMutex>());
|
||||
const _: () = assert!(core::mem::size_of::<RWLockImpl>() == core::mem::size_of::<GRWLock>());
|
||||
const _: () = assert!(core::mem::align_of::<RWLockImpl>() == core::mem::align_of::<GRWLock>());
|
||||
const _: () = assert!(core::mem::size_of::<CondImpl>() == core::mem::size_of::<GCond>());
|
||||
const _: () = assert!(core::mem::align_of::<CondImpl>() == core::mem::align_of::<GCond>());
|
||||
|
||||
// System thread implementation
|
||||
#[repr(C)]
|
||||
struct SystemThreadImpl {
|
||||
mutex: GMutex, // Protects the thread state
|
||||
cond: GCond, // Signals thread completion
|
||||
thread_id: AtomicU64, // XNU thread ID
|
||||
func: GThreadFunc, // Thread function
|
||||
data: gpointer, // User data
|
||||
finished: AtomicU32, // Whether thread has finished (0 = running, 1 = finished)
|
||||
detached: AtomicU32, // Whether thread is detached (1) or joinable (0)
|
||||
}
|
||||
|
||||
// Thread wrapper data passed to XNU kernel thread
|
||||
#[repr(C)]
|
||||
struct ThreadWrapperData {
|
||||
func: GThreadFunc,
|
||||
data: gpointer,
|
||||
system_thread: *mut SystemThreadImpl,
|
||||
}
|
||||
|
||||
unsafe fn mutex_impl<'a>(mutex: *mut GMutex) -> &'a mut MutexImpl {
|
||||
unsafe { &mut *(mutex as *mut MutexImpl) }
|
||||
}
|
||||
|
||||
unsafe fn rec_mutex_impl<'a>(rec_mutex: *mut GRecMutex) -> &'a mut RecMutexImpl {
|
||||
unsafe { &mut *(rec_mutex as *mut RecMutexImpl) }
|
||||
}
|
||||
|
||||
unsafe fn rw_lock_impl<'a>(rw_lock: *mut GRWLock) -> &'a mut RWLockImpl {
|
||||
unsafe { &mut *(rw_lock as *mut RWLockImpl) }
|
||||
}
|
||||
|
||||
unsafe fn cond_impl<'a>(cond: *mut GCond) -> &'a mut CondImpl {
|
||||
unsafe { &mut *(cond as *mut CondImpl) }
|
||||
}
|
||||
|
||||
// TODO: Clean up Thread-Local Storage (TLS) entries when threads exit
|
||||
static mut TLS_STORAGE: Option<Box<BTreeMap<(u64, *mut GPrivate), *mut c_void>>> = None;
|
||||
static TLS_LOCK: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_mutex_init(mutex: *mut GMutex) {
|
||||
unsafe {
|
||||
let impl_ = mutex_impl(mutex);
|
||||
impl_.lock.store(0, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_mutex_clear(_mutex: *mut GMutex) {}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_mutex_lock(mutex: *mut GMutex) {
|
||||
unsafe {
|
||||
let impl_ = mutex_impl(mutex);
|
||||
lock_acquire(&impl_.lock);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_mutex_unlock(mutex: *mut GMutex) {
|
||||
unsafe {
|
||||
let impl_ = mutex_impl(mutex);
|
||||
lock_release(&impl_.lock);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_mutex_trylock(mutex: *mut GMutex) -> u32 {
|
||||
unsafe {
|
||||
let impl_ = mutex_impl(mutex);
|
||||
if lock_try_acquire(&impl_.lock) {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rec_mutex_init(rec_mutex: *mut GRecMutex) {
|
||||
unsafe {
|
||||
let impl_ = rec_mutex_impl(rec_mutex);
|
||||
impl_.owner.store(0, Ordering::Relaxed);
|
||||
impl_.count.store(0, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rec_mutex_clear(_rec_mutex: *mut GRecMutex) {
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rec_mutex_lock(rec_mutex: *mut GRecMutex) {
|
||||
unsafe {
|
||||
let impl_ = rec_mutex_impl(rec_mutex);
|
||||
let current_thread = get_current_thread_id();
|
||||
|
||||
loop {
|
||||
if rec_mutex_try_acquire(impl_, current_thread) {
|
||||
break;
|
||||
}
|
||||
rec_mutex_wait(impl_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rec_mutex_trylock(rec_mutex: *mut GRecMutex) -> u32 {
|
||||
unsafe {
|
||||
let impl_ = rec_mutex_impl(rec_mutex);
|
||||
let current_thread = get_current_thread_id();
|
||||
|
||||
if rec_mutex_try_acquire(impl_, current_thread) {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rec_mutex_unlock(rec_mutex: *mut GRecMutex) {
|
||||
unsafe {
|
||||
let impl_ = rec_mutex_impl(rec_mutex);
|
||||
|
||||
loop {
|
||||
let current_count = impl_.count.load(Ordering::Relaxed);
|
||||
|
||||
if current_count == 1 {
|
||||
if impl_.count
|
||||
.compare_exchange_weak(1, 0, Ordering::Release, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
{
|
||||
impl_.owner.store(0, Ordering::Relaxed);
|
||||
lock_notify_all();
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if impl_.count
|
||||
.compare_exchange_weak(current_count, current_count - 1, Ordering::Release, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn rec_mutex_try_acquire(impl_: &mut RecMutexImpl, current_thread: u64) -> bool {
|
||||
let current_count = impl_.count.load(Ordering::Relaxed);
|
||||
|
||||
if current_count == 0 {
|
||||
if impl_.count
|
||||
.compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
{
|
||||
impl_.owner.store(current_thread, Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
let current_owner = impl_.owner.load(Ordering::Relaxed);
|
||||
if current_owner == current_thread {
|
||||
if impl_.count
|
||||
.compare_exchange_weak(
|
||||
current_count,
|
||||
current_count + 1,
|
||||
Ordering::Acquire,
|
||||
Ordering::Relaxed,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
unsafe fn rec_mutex_wait(impl_: &mut RecMutexImpl) {
|
||||
while impl_.count.load(Ordering::Relaxed) != 0 {
|
||||
unsafe { lock_wait_primitive() };
|
||||
}
|
||||
}
|
||||
|
||||
// Read-Write Lock implementation
|
||||
// We use a simple scheme where the atomic value represents:
|
||||
// - 0: unlocked
|
||||
// - 1-0x7FFFFFFF: number of readers holding the lock
|
||||
// - 0x80000000: writer lock held
|
||||
const RW_WRITER_LOCK_BIT: u32 = 0x80000000;
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rw_lock_init(rw_lock: *mut GRWLock) {
|
||||
unsafe {
|
||||
let impl_ = rw_lock_impl(rw_lock);
|
||||
impl_.state.store(0, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rw_lock_clear(_rw_lock: *mut GRWLock) {}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rw_lock_writer_lock(rw_lock: *mut GRWLock) {
|
||||
unsafe {
|
||||
let impl_ = rw_lock_impl(rw_lock);
|
||||
loop {
|
||||
if rw_lock_writer_try_acquire(impl_) {
|
||||
break;
|
||||
}
|
||||
rw_lock_wait_for_all(impl_);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rw_lock_writer_trylock(rw_lock: *mut GRWLock) -> u32 {
|
||||
unsafe {
|
||||
let impl_ = rw_lock_impl(rw_lock);
|
||||
if rw_lock_writer_try_acquire(impl_) {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rw_lock_writer_unlock(rw_lock: *mut GRWLock) {
|
||||
unsafe {
|
||||
let impl_ = rw_lock_impl(rw_lock);
|
||||
impl_.state.store(0, Ordering::Release);
|
||||
lock_notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rw_lock_reader_lock(rw_lock: *mut GRWLock) {
|
||||
unsafe {
|
||||
let impl_ = rw_lock_impl(rw_lock);
|
||||
loop {
|
||||
let current = impl_.state.load(Ordering::Relaxed);
|
||||
if current & RW_WRITER_LOCK_BIT != 0 {
|
||||
rw_lock_wait_for_writers(impl_);
|
||||
continue;
|
||||
}
|
||||
if impl_.state
|
||||
.compare_exchange_weak(current, current + 1, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rw_lock_reader_trylock(rw_lock: *mut GRWLock) -> u32 {
|
||||
unsafe {
|
||||
let impl_ = rw_lock_impl(rw_lock);
|
||||
if rw_lock_reader_try_acquire(impl_) {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_rw_lock_reader_unlock(rw_lock: *mut GRWLock) {
|
||||
unsafe {
|
||||
let impl_ = rw_lock_impl(rw_lock);
|
||||
loop {
|
||||
let current = impl_.state.load(Ordering::Relaxed);
|
||||
if impl_.state
|
||||
.compare_exchange_weak(current, current - 1, Ordering::Release, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
{
|
||||
if current - 1 == 0 {
|
||||
lock_notify_all();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn rw_lock_writer_try_acquire(impl_: &mut RWLockImpl) -> bool {
|
||||
impl_.state
|
||||
.compare_exchange_weak(0, RW_WRITER_LOCK_BIT, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
unsafe fn rw_lock_reader_try_acquire(impl_: &mut RWLockImpl) -> bool {
|
||||
let current = impl_.state.load(Ordering::Relaxed);
|
||||
if current & RW_WRITER_LOCK_BIT != 0 {
|
||||
return false;
|
||||
}
|
||||
impl_.state
|
||||
.compare_exchange_weak(current, current + 1, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
unsafe fn rw_lock_wait_for_writers(impl_: &mut RWLockImpl) {
|
||||
while impl_.state.load(Ordering::Relaxed) & RW_WRITER_LOCK_BIT != 0 {
|
||||
unsafe { lock_wait_primitive() };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn rw_lock_wait_for_all(impl_: &mut RWLockImpl) {
|
||||
while impl_.state.load(Ordering::Relaxed) != 0 {
|
||||
unsafe { lock_wait_primitive() };
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_cond_init(cond: *mut GCond) {
|
||||
unsafe {
|
||||
let impl_ = cond_impl(cond);
|
||||
impl_.signal.store(0, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_cond_clear(_cond: *mut GCond) {}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_cond_wait(cond: *mut GCond, mutex: *mut GMutex) {
|
||||
unsafe {
|
||||
g_mutex_unlock(mutex);
|
||||
|
||||
let impl_ = cond_impl(cond);
|
||||
while impl_.signal.load(Ordering::Acquire) == 0 {
|
||||
lock_wait_primitive();
|
||||
}
|
||||
|
||||
g_mutex_lock(mutex);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_cond_signal(cond: *mut GCond) {
|
||||
unsafe {
|
||||
let impl_ = cond_impl(cond);
|
||||
impl_.signal.store(1, Ordering::Release);
|
||||
lock_notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_cond_broadcast(cond: *mut GCond) {
|
||||
unsafe {
|
||||
let impl_ = cond_impl(cond);
|
||||
impl_.signal.store(1, Ordering::Release);
|
||||
lock_notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_cond_wait_until(cond: *mut GCond, mutex: *mut GMutex, _end_time: i64) -> u32 {
|
||||
// TODO: Implement proper timeout handling
|
||||
g_cond_wait(cond, mutex);
|
||||
1
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_private_get(key: *mut GPrivate) -> *mut c_void {
|
||||
unsafe {
|
||||
let thread_id = get_current_thread_id();
|
||||
lock_acquire(&TLS_LOCK);
|
||||
|
||||
ensure_tls_storage();
|
||||
let storage_ptr = core::ptr::addr_of_mut!(TLS_STORAGE);
|
||||
let storage = (*storage_ptr).as_ref().unwrap();
|
||||
|
||||
let value = storage
|
||||
.get(&(thread_id, key))
|
||||
.copied()
|
||||
.unwrap_or(core::ptr::null_mut());
|
||||
|
||||
lock_release(&TLS_LOCK);
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn g_private_set(key: *mut GPrivate, value: *mut c_void) {
|
||||
unsafe {
|
||||
let thread_id = get_current_thread_id();
|
||||
lock_acquire(&TLS_LOCK);
|
||||
|
||||
ensure_tls_storage();
|
||||
let storage_ptr = core::ptr::addr_of_mut!(TLS_STORAGE);
|
||||
let storage = (*storage_ptr).as_mut().unwrap();
|
||||
|
||||
storage.insert((thread_id, key), value);
|
||||
|
||||
lock_release(&TLS_LOCK);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn ensure_tls_storage() {
|
||||
let storage_ptr = core::ptr::addr_of_mut!(TLS_STORAGE);
|
||||
unsafe {
|
||||
if (*storage_ptr).is_none() {
|
||||
*storage_ptr = Some(Box::new(BTreeMap::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _g_system_thread_create(
|
||||
_stack_size: gulong,
|
||||
_name: *const core::ffi::c_char,
|
||||
func: GThreadFunc,
|
||||
data: gpointer,
|
||||
) -> *mut GSystemThread {
|
||||
unsafe {
|
||||
let system_thread = crate::xnu::kalloc(core::mem::size_of::<SystemThreadImpl>()) as *mut SystemThreadImpl;
|
||||
|
||||
g_mutex_init(&mut (*system_thread).mutex);
|
||||
g_cond_init(&mut (*system_thread).cond);
|
||||
(*system_thread).thread_id.store(0, Ordering::Relaxed);
|
||||
(*system_thread).func = func;
|
||||
(*system_thread).data = data;
|
||||
(*system_thread).finished.store(0, Ordering::Relaxed);
|
||||
(*system_thread).detached.store(0, Ordering::Relaxed);
|
||||
|
||||
let wrapper_data = crate::xnu::kalloc(core::mem::size_of::<ThreadWrapperData>()) as *mut ThreadWrapperData;
|
||||
(*wrapper_data).func = func;
|
||||
(*wrapper_data).data = data;
|
||||
(*wrapper_data).system_thread = system_thread;
|
||||
|
||||
let _xnu_result = crate::xnu::kernel_thread_start(thread_wrapper, wrapper_data as *mut c_void);
|
||||
|
||||
system_thread as *mut GSystemThread
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn thread_wrapper(parameter: *mut c_void, _wait_result: i32) {
|
||||
unsafe {
|
||||
let wrapper_data = parameter as *mut ThreadWrapperData;
|
||||
let func = (*wrapper_data).func;
|
||||
let data = (*wrapper_data).data;
|
||||
let system_thread = (*wrapper_data).system_thread;
|
||||
|
||||
let current_thread_id = get_current_thread_id();
|
||||
(*system_thread).thread_id.store(current_thread_id, Ordering::Relaxed);
|
||||
|
||||
func.unwrap()(data);
|
||||
|
||||
g_mutex_lock(&mut (*system_thread).mutex);
|
||||
(*system_thread).finished.store(1, Ordering::Relaxed);
|
||||
g_cond_signal(&mut (*system_thread).cond);
|
||||
|
||||
let detached = (*system_thread).detached.load(Ordering::Relaxed);
|
||||
g_mutex_unlock(&mut (*system_thread).mutex);
|
||||
|
||||
if detached != 0 {
|
||||
cleanup_system_thread(system_thread);
|
||||
}
|
||||
|
||||
cleanup_wrapper_data(wrapper_data);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _g_system_thread_detach(thread: *mut GSystemThread) {
|
||||
unsafe {
|
||||
let system_thread = thread as *mut SystemThreadImpl;
|
||||
|
||||
g_mutex_lock(&mut (*system_thread).mutex);
|
||||
(*system_thread).detached.store(1, Ordering::Relaxed);
|
||||
|
||||
let finished = (*system_thread).finished.load(Ordering::Relaxed);
|
||||
g_mutex_unlock(&mut (*system_thread).mutex);
|
||||
if finished != 0 {
|
||||
cleanup_system_thread(system_thread);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _g_system_thread_wait(thread: *mut GSystemThread) {
|
||||
unsafe {
|
||||
let system_thread = thread as *mut SystemThreadImpl;
|
||||
|
||||
loop {
|
||||
let thread_id = (*system_thread).thread_id.load(Ordering::Acquire);
|
||||
if thread_id != 0 {
|
||||
break;
|
||||
}
|
||||
core::hint::spin_loop();
|
||||
}
|
||||
|
||||
g_mutex_lock(&mut (*system_thread).mutex);
|
||||
while (*system_thread).finished.load(Ordering::Relaxed) == 0 {
|
||||
g_cond_wait(&mut (*system_thread).cond, &mut (*system_thread).mutex);
|
||||
}
|
||||
g_mutex_unlock(&mut (*system_thread).mutex);
|
||||
|
||||
cleanup_system_thread(system_thread);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn cleanup_system_thread(system_thread: *mut SystemThreadImpl) {
|
||||
crate::xnu::free(system_thread as *mut u8, core::mem::size_of::<SystemThreadImpl>());
|
||||
}
|
||||
|
||||
unsafe fn cleanup_wrapper_data(wrapper_data: *mut ThreadWrapperData) {
|
||||
crate::xnu::free(wrapper_data as *mut u8, core::mem::size_of::<ThreadWrapperData>());
|
||||
}
|
||||
|
||||
unsafe fn lock_acquire(lock: &AtomicU32) {
|
||||
loop {
|
||||
if unsafe { lock_try_acquire(lock) } {
|
||||
break;
|
||||
}
|
||||
unsafe { lock_wait(lock) };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn lock_try_acquire(lock: &AtomicU32) -> bool {
|
||||
lock.compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
unsafe fn lock_release(lock: &AtomicU32) {
|
||||
lock.store(0, Ordering::Release);
|
||||
unsafe { lock_notify_all() };
|
||||
}
|
||||
|
||||
unsafe fn lock_wait(lock: &AtomicU32) {
|
||||
while lock.load(Ordering::Relaxed) != 0 {
|
||||
unsafe { lock_wait_primitive() };
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn lock_wait_primitive() {
|
||||
unsafe {
|
||||
asm!("wfe", options(nomem, nostack));
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn lock_notify_all() {
|
||||
unsafe {
|
||||
asm!("sev", options(nomem, nostack));
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn get_current_thread_id() -> u64 {
|
||||
let thread_ptr: u64;
|
||||
unsafe {
|
||||
asm!("mrs {}, tpidr_el1", out(reg) thread_ptr, options(nomem, nostack));
|
||||
}
|
||||
thread_ptr
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
use crate::{
|
||||
bindings::{
|
||||
_GInterfaceInfo, _GTypeInfo, _GumPageProtection_GUM_PAGE_EXECUTE,
|
||||
_GumRwxSupport_GUM_RWX_NONE, GArray, GObject, GObjectClass, GPrivate, GType,
|
||||
GumDebugSymbolDetails, GumExportDetails, GumExportType_GUM_EXPORT_FUNCTION,
|
||||
GumFoundExportFunc, GumMemoryRange, GumModule, GumModuleInterface, GumModuleRegistry,
|
||||
GumPageProtection, GumRwxSupport, GumThreadId, GumTlsKey, g_array_append_vals, g_array_new,
|
||||
g_free, g_object_get_type, g_object_new, g_object_unref, g_once_init_enter,
|
||||
g_once_init_leave, g_strdup, g_type_add_interface_static, g_type_class_peek_parent,
|
||||
g_type_register_static, gboolean, gchar, gconstpointer, gpointer, gsize, guint,
|
||||
gum_barebone_register_module,
|
||||
gum_barebone_try_remap_writable_pages as _gum_barebone_try_remap_writable_pages,
|
||||
gum_module_get_type, gum_mprotect, gum_query_page_size,
|
||||
},
|
||||
gthread, libc, xnu,
|
||||
};
|
||||
use alloc::boxed::Box;
|
||||
use alloc::ffi::CString;
|
||||
use alloc::format;
|
||||
use core::ptr;
|
||||
use core::{ffi::CStr, ptr::read_volatile};
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_process_get_current_thread_id() -> GumThreadId {
|
||||
unsafe { gthread::get_current_thread_id() }
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_barebone_query_page_size() -> guint {
|
||||
unsafe {
|
||||
let tcr_el1: u64;
|
||||
core::arch::asm!("mrs {}, tcr_el1", out(reg) tcr_el1, options(nomem, nostack));
|
||||
|
||||
let tg0 = (tcr_el1 >> 14) & 0x3;
|
||||
|
||||
match tg0 {
|
||||
0b00 => 4096,
|
||||
0b01 => 65536,
|
||||
0b10 => 16384,
|
||||
_ => 4096,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_query_rwx_support() -> GumRwxSupport {
|
||||
_GumRwxSupport_GUM_RWX_NONE
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_memory_can_remap_writable() -> gboolean {
|
||||
1
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_memory_try_remap_writable_pages(
|
||||
first_page: gpointer,
|
||||
n_pages: guint,
|
||||
) -> gpointer {
|
||||
unsafe {
|
||||
let page_size = gum_query_page_size() as usize;
|
||||
let mut physical_addrs = alloc::vec::Vec::with_capacity(n_pages as usize);
|
||||
|
||||
let mut current_page = first_page as u64;
|
||||
for _ in 0..n_pages {
|
||||
let phys_addr = xnu::ml_vtophys(current_page);
|
||||
physical_addrs.push(phys_addr as gpointer);
|
||||
current_page += page_size as u64;
|
||||
}
|
||||
|
||||
_gum_barebone_try_remap_writable_pages(
|
||||
physical_addrs.as_ptr() as *mut *const core::ffi::c_void,
|
||||
physical_addrs.len() as guint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
#[inline(never)]
|
||||
pub extern "C" fn gum_barebone_try_remap_writable_pages(
|
||||
addrs: *const gpointer,
|
||||
n_addrs: guint,
|
||||
) -> gpointer {
|
||||
unsafe {
|
||||
read_volatile(&n_addrs);
|
||||
read_volatile(addrs)
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_try_mprotect(
|
||||
_address: gpointer,
|
||||
_size: gsize,
|
||||
_prot: GumPageProtection,
|
||||
) -> gboolean {
|
||||
1
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_memory_allocate(
|
||||
_address: gpointer,
|
||||
size: gsize,
|
||||
_alignment: gsize,
|
||||
prot: GumPageProtection,
|
||||
) -> gpointer {
|
||||
let ptr = crate::xnu::kalloc(size as usize);
|
||||
unsafe {
|
||||
core::ptr::write_bytes(ptr, 0, size as usize);
|
||||
if (prot & _GumPageProtection_GUM_PAGE_EXECUTE) != 0 {
|
||||
gum_mprotect(ptr as gpointer, size, prot);
|
||||
}
|
||||
}
|
||||
ptr as gpointer
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_memory_free(address: gpointer, size: gsize) -> gboolean {
|
||||
crate::xnu::free(address as *mut u8, size as usize);
|
||||
1
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_clear_cache(address: gpointer, size: gsize) {
|
||||
unsafe {
|
||||
let start = address as *const u8;
|
||||
let end = start.add(size as usize);
|
||||
libc::__clear_cache(start, end);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_tls_key_new() -> GumTlsKey {
|
||||
Box::into_raw(Box::new(unsafe { core::mem::zeroed::<GPrivate>() })) as GumTlsKey
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_tls_key_free(key: GumTlsKey) {
|
||||
unsafe {
|
||||
let _ = Box::from_raw(key as *mut GPrivate);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_tls_key_get_value(key: GumTlsKey) -> gpointer {
|
||||
gthread::g_private_get(key as *mut GPrivate)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_tls_key_set_value(key: GumTlsKey, value: gpointer) {
|
||||
gthread::g_private_set(key as *mut GPrivate, value)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_barebone_on_registry_activating(registry: *mut GumModuleRegistry) {
|
||||
let kernel_base = crate::xnu::get_kernel_base();
|
||||
|
||||
unsafe {
|
||||
let module_infos = core::ptr::addr_of!(crate::MODULE_INFO);
|
||||
let module_infos = &*module_infos;
|
||||
|
||||
let mut i = 0;
|
||||
for module_info in module_infos.iter() {
|
||||
let module_base = kernel_base + module_info.offset as u64;
|
||||
|
||||
let module_path = if i == 0 {
|
||||
"/System/Library/Kernels/kernel"
|
||||
} else {
|
||||
&format!(
|
||||
"/System/Library/Extensions/{}.kext/{}",
|
||||
module_info.name, module_info.name
|
||||
)
|
||||
};
|
||||
let module_range = GumMemoryRange {
|
||||
base_address: module_base,
|
||||
size: module_info.size as u64,
|
||||
};
|
||||
|
||||
let module = gum_native_module_new(&module_path, &module_info.version, &module_range);
|
||||
gum_barebone_register_module(registry, module);
|
||||
g_object_unref(module as gpointer);
|
||||
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct GumNativeModule {
|
||||
parent: GObject,
|
||||
name: *mut gchar,
|
||||
version: *mut gchar,
|
||||
path: *mut gchar,
|
||||
range: GumMemoryRange,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[allow(dead_code)]
|
||||
pub struct GumNativeModuleClass {
|
||||
parent_class: GObjectClass,
|
||||
}
|
||||
|
||||
static mut GUM_NATIVE_MODULE_TYPE: gsize = 0;
|
||||
static mut GUM_NATIVE_MODULE_PARENT_CLASS: *mut GObjectClass = core::ptr::null_mut();
|
||||
|
||||
fn gum_native_module_get_type() -> GType {
|
||||
unsafe {
|
||||
if g_once_init_enter(
|
||||
core::ptr::addr_of_mut!(GUM_NATIVE_MODULE_TYPE) as *mut ::core::ffi::c_void
|
||||
) != 0
|
||||
{
|
||||
let type_name = c"GumNativeModule".as_ptr() as *const gchar;
|
||||
|
||||
let type_info = _GTypeInfo {
|
||||
class_size: core::mem::size_of::<GObjectClass>() as u16,
|
||||
base_init: None,
|
||||
base_finalize: None,
|
||||
class_init: Some(gum_native_module_class_init),
|
||||
class_finalize: None,
|
||||
class_data: core::ptr::null(),
|
||||
instance_size: core::mem::size_of::<GumNativeModule>() as u16,
|
||||
n_preallocs: 0,
|
||||
instance_init: None,
|
||||
value_table: core::ptr::null(),
|
||||
};
|
||||
|
||||
let new_type = g_type_register_static(g_object_get_type(), type_name, &type_info, 0);
|
||||
|
||||
let interface_info = _GInterfaceInfo {
|
||||
interface_init: Some(gum_native_module_iface_init),
|
||||
interface_finalize: None,
|
||||
interface_data: core::ptr::null_mut(),
|
||||
};
|
||||
|
||||
g_type_add_interface_static(new_type, gum_module_get_type(), &interface_info);
|
||||
|
||||
g_once_init_leave(
|
||||
core::ptr::addr_of_mut!(GUM_NATIVE_MODULE_TYPE) as *mut ::core::ffi::c_void,
|
||||
new_type as gsize,
|
||||
);
|
||||
}
|
||||
|
||||
GUM_NATIVE_MODULE_TYPE as GType
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn gum_native_module_class_init(klass: gpointer, _class_data: gpointer) {
|
||||
unsafe {
|
||||
let object_class = klass as *mut GObjectClass;
|
||||
|
||||
GUM_NATIVE_MODULE_PARENT_CLASS = g_type_class_peek_parent(klass) as *mut GObjectClass;
|
||||
|
||||
(*object_class).finalize = Some(gum_native_module_finalize);
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn gum_native_module_iface_init(g_iface: gpointer, _iface_data: gpointer) {
|
||||
unsafe {
|
||||
let iface = g_iface as *mut GumModuleInterface;
|
||||
(*iface).get_name = Some(gum_native_module_get_name);
|
||||
(*iface).get_version = Some(gum_native_module_get_version);
|
||||
(*iface).get_path = Some(gum_native_module_get_path);
|
||||
(*iface).get_range = Some(gum_native_module_get_range);
|
||||
(*iface).enumerate_exports = Some(gum_native_module_enumerate_exports);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn gum_native_module_finalize(object: *mut GObject) {
|
||||
unsafe {
|
||||
let module = object as *mut GumNativeModule;
|
||||
|
||||
g_free((*module).path as gpointer);
|
||||
|
||||
(*GUM_NATIVE_MODULE_PARENT_CLASS).finalize.unwrap()(object);
|
||||
}
|
||||
}
|
||||
|
||||
fn gum_native_module_new(path: &str, version: &str, range: &GumMemoryRange) -> *mut GumModule {
|
||||
unsafe {
|
||||
let path_cstr = CString::new(path).unwrap();
|
||||
let version_cstr = CString::new(version).unwrap();
|
||||
|
||||
let module =
|
||||
g_object_new(gum_native_module_get_type(), ptr::null()) as *mut GumNativeModule;
|
||||
(*module).path = g_strdup(path_cstr.as_ptr());
|
||||
(*module).name = (*module).path.add(path.rfind('/').unwrap() + 1);
|
||||
(*module).version = g_strdup(version_cstr.as_ptr());
|
||||
(*module).range = *range;
|
||||
|
||||
module as *mut GumModule
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn gum_native_module_get_name(module: *mut GumModule) -> *const gchar {
|
||||
unsafe {
|
||||
let native_module = module as *mut GumNativeModule;
|
||||
(*native_module).name as *const gchar
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn gum_native_module_get_version(module: *mut GumModule) -> *const gchar {
|
||||
unsafe {
|
||||
let native_module = module as *mut GumNativeModule;
|
||||
(*native_module).version as *const gchar
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn gum_native_module_get_path(module: *mut GumModule) -> *const gchar {
|
||||
unsafe {
|
||||
let native_module = module as *mut GumNativeModule;
|
||||
(*native_module).path as *const gchar
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn gum_native_module_get_range(module: *mut GumModule) -> *const GumMemoryRange {
|
||||
unsafe {
|
||||
let native_module = module as *mut GumNativeModule;
|
||||
&(*native_module).range as *const GumMemoryRange
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn gum_native_module_enumerate_exports(
|
||||
self_: *mut GumModule,
|
||||
func: GumFoundExportFunc,
|
||||
user_data: gpointer,
|
||||
) {
|
||||
unsafe {
|
||||
let module = self_ as *mut GumNativeModule;
|
||||
let module_range = &(*module).range;
|
||||
|
||||
let symbol_table = core::ptr::addr_of!(crate::SYMBOL_TABLE);
|
||||
let symbol_table = &*symbol_table;
|
||||
|
||||
const N_EXT: u8 = 0x01; // External symbol flag
|
||||
const N_TYPE: u8 = 0x0e; // Type mask
|
||||
const N_SECT: u8 = 0x0e; // Defined in section
|
||||
|
||||
let start_address = module_range.base_address;
|
||||
let end_address = module_range.base_address + module_range.size;
|
||||
|
||||
for symbol_ref in symbol_table.iter_symbols_in_range(start_address, end_address) {
|
||||
let is_external = (symbol_ref.symbol_type() & N_EXT) != 0;
|
||||
let is_defined = (symbol_ref.symbol_type() & N_TYPE) == N_SECT;
|
||||
if !is_external || !is_defined {
|
||||
continue;
|
||||
}
|
||||
|
||||
let export_type = GumExportType_GUM_EXPORT_FUNCTION;
|
||||
|
||||
let export_details = GumExportDetails {
|
||||
type_: export_type,
|
||||
name: g_strdup(symbol_ref.name_ptr()),
|
||||
address: symbol_ref.address(),
|
||||
};
|
||||
|
||||
let should_continue =
|
||||
func.unwrap()(&export_details as *const GumExportDetails, user_data);
|
||||
if should_continue == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_symbol_details_from_address(
|
||||
address: gpointer,
|
||||
details: *mut GumDebugSymbolDetails,
|
||||
) -> gboolean {
|
||||
unsafe {
|
||||
let table = core::ptr::addr_of!(crate::SYMBOL_TABLE).read();
|
||||
if let Some(symbol) = table.find_symbol_by_address(address as u64) {
|
||||
let name_bytes = symbol.name().as_bytes();
|
||||
let copy_len = core::cmp::min(name_bytes.len(), 2048);
|
||||
core::ptr::copy_nonoverlapping(
|
||||
name_bytes.as_ptr(),
|
||||
(*details).symbol_name.as_mut_ptr() as *mut u8,
|
||||
copy_len,
|
||||
);
|
||||
(*details).symbol_name[copy_len] = 0;
|
||||
|
||||
(*details).address = symbol.address();
|
||||
|
||||
(*details).module_name[0] = 0;
|
||||
(*details).file_name[0] = 0;
|
||||
(*details).line_number = 0;
|
||||
(*details).column = 0;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_symbol_name_from_address(address: gpointer) -> *mut gchar {
|
||||
unsafe {
|
||||
let table = core::ptr::addr_of!(crate::SYMBOL_TABLE).read();
|
||||
let name_ptr = table.find_symbol_name_ptr_by_address(address as u64);
|
||||
g_strdup(name_ptr as *const gchar)
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_find_function(name: *const gchar) -> gpointer {
|
||||
unsafe {
|
||||
let target_name = CStr::from_ptr(name).to_string_lossy();
|
||||
let table = core::ptr::addr_of!(crate::SYMBOL_TABLE).read();
|
||||
|
||||
if let Some(symbol) = table.find_symbol_by_name(&target_name) {
|
||||
return symbol.address() as gpointer;
|
||||
}
|
||||
|
||||
core::ptr::null_mut()
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_find_functions_named(name: *const gchar) -> *mut GArray {
|
||||
unsafe {
|
||||
let array = g_array_new(0, 0, core::mem::size_of::<gpointer>() as guint);
|
||||
|
||||
let target_name = CStr::from_ptr(name).to_string_lossy();
|
||||
let table = core::ptr::addr_of!(crate::SYMBOL_TABLE).read();
|
||||
|
||||
let symbols = table.find_symbols_by_name(&target_name);
|
||||
for symbol in symbols {
|
||||
let addr = symbol.address() as gpointer;
|
||||
g_array_append_vals(array, &addr as *const gpointer as gconstpointer, 1);
|
||||
}
|
||||
|
||||
array
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_find_functions_matching(pattern: *const gchar) -> *mut GArray {
|
||||
unsafe {
|
||||
let array = g_array_new(0, 0, core::mem::size_of::<gpointer>() as guint);
|
||||
|
||||
let glob_pattern = CStr::from_ptr(pattern).to_string_lossy();
|
||||
let table = core::ptr::addr_of!(crate::SYMBOL_TABLE).read();
|
||||
|
||||
let symbols = table.find_symbols_matching_glob(&glob_pattern);
|
||||
for symbol in symbols {
|
||||
let addr = symbol.address() as gpointer;
|
||||
g_array_append_vals(array, &addr as *const gpointer as gconstpointer, 1);
|
||||
}
|
||||
|
||||
array
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_load_symbols(_path: *const gchar) -> gboolean {
|
||||
0
|
||||
}
|
||||
@@ -0,0 +1,763 @@
|
||||
use core::cell::UnsafeCell;
|
||||
use core::ffi::c_void;
|
||||
use core::mem::size_of;
|
||||
use core::ptr::{read_volatile, write_volatile};
|
||||
use core::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use crate::gum::gum_barebone_query_page_size;
|
||||
use crate::xnu;
|
||||
|
||||
const MMIO_SIZE: u64 = 0x200;
|
||||
|
||||
static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
const QSZ: u16 = 64;
|
||||
|
||||
const MAGIC: usize = 0x000;
|
||||
const VERSION: usize = 0x004;
|
||||
const DEVICE: usize = 0x008;
|
||||
const STATUS: usize = 0x070;
|
||||
|
||||
const DEVFEAT: usize = 0x010;
|
||||
const DEVFEAT_SEL: usize = 0x014;
|
||||
const DRVFEAT: usize = 0x020;
|
||||
const DRVFEAT_SEL: usize = 0x024;
|
||||
|
||||
const QSEL: usize = 0x030;
|
||||
const QNUM_MAX: usize = 0x034;
|
||||
const QNUM: usize = 0x038;
|
||||
const QREADY: usize = 0x044;
|
||||
|
||||
const QDESC_LO: usize = 0x080;
|
||||
const QDESC_HI: usize = 0x084;
|
||||
const QAVAIL_LO: usize = 0x090;
|
||||
const QAVAIL_HI: usize = 0x094;
|
||||
const QUSED_LO: usize = 0x0a0;
|
||||
const QUSED_HI: usize = 0x0a4;
|
||||
|
||||
const QNOTIFY: usize = 0x050;
|
||||
const ISR: usize = 0x060;
|
||||
const ISR_ACK: usize = 0x064;
|
||||
|
||||
const ST_ACK: u32 = 1;
|
||||
const ST_DRV: u32 = 2;
|
||||
const ST_DRV_OK: u32 = 4;
|
||||
const ST_FEAT_OK: u32 = 8;
|
||||
const ST_FAILED: u32 = 0x80;
|
||||
|
||||
const DEV_ID_CONSOLE: u32 = 3;
|
||||
const F_VERSION_1: u64 = 1u64 << 32;
|
||||
const F_MULTIPORT: u64 = 1u64 << 1;
|
||||
|
||||
const INT_VRING: u32 = 1;
|
||||
|
||||
const Q_RX0: u16 = 0;
|
||||
const Q_TX0: u16 = 1;
|
||||
const Q_CTRL_RX: u16 = 2;
|
||||
const Q_CTRL_TX: u16 = 3;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct VConsCtrl {
|
||||
id: u32,
|
||||
event: u16,
|
||||
value: u16,
|
||||
}
|
||||
const EV_DEVICE_READY: u16 = 0;
|
||||
const EV_DEVICE_ADD: u16 = 1;
|
||||
const EV_PORT_READY: u16 = 3;
|
||||
const EV_PORT_OPEN: u16 = 6;
|
||||
const EV_CONSOLE_PORT: u16 = 4;
|
||||
|
||||
#[repr(C)]
|
||||
struct Desc {
|
||||
addr: u64,
|
||||
len: u32,
|
||||
flags: u16,
|
||||
next: u16,
|
||||
}
|
||||
const D_NEXT: u16 = 1;
|
||||
const D_WRITE: u16 = 2;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct Avail {
|
||||
flags: u16,
|
||||
idx: u16,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct UsedElem {
|
||||
id: u32,
|
||||
len: u32,
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct Used {
|
||||
flags: u16,
|
||||
idx: u16,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct DmaPage {
|
||||
va: *mut u8,
|
||||
pa: u64,
|
||||
}
|
||||
|
||||
fn dma_page_alloc() -> DmaPage {
|
||||
let len = PAGE_SIZE.load(Ordering::Relaxed);
|
||||
let va = xnu::kalloc(len);
|
||||
let pa = xnu::ml_vtophys(va as u64);
|
||||
DmaPage { va, pa }
|
||||
}
|
||||
|
||||
fn dma_page_free(p: DmaPage) {
|
||||
let len = PAGE_SIZE.load(Ordering::Relaxed);
|
||||
xnu::free(p.va, len);
|
||||
}
|
||||
|
||||
struct Vq {
|
||||
sel: u16,
|
||||
size: u16,
|
||||
desc_va: *mut u8,
|
||||
avail_va: *mut u8,
|
||||
used_va: *mut u8,
|
||||
avail_idx: u16,
|
||||
used_idx: u16,
|
||||
free_head: u16,
|
||||
free_cnt: u16,
|
||||
}
|
||||
impl Vq {
|
||||
fn new(mmio: *mut u8, sel: u16, size: u16) -> Self {
|
||||
w32(mmio, QSEL, sel as u32);
|
||||
let max = r32(mmio, QNUM_MAX) as u16;
|
||||
debug_assert!(max >= size && max != 0);
|
||||
w32(mmio, QNUM, size as u32);
|
||||
|
||||
let d = dma_page_alloc();
|
||||
let a = dma_page_alloc();
|
||||
let u = dma_page_alloc();
|
||||
|
||||
let ps = PAGE_SIZE.load(core::sync::atomic::Ordering::Relaxed);
|
||||
unsafe {
|
||||
core::ptr::write_bytes(d.va, 0, ps);
|
||||
core::ptr::write_bytes(a.va, 0, ps);
|
||||
core::ptr::write_bytes(u.va, 0, ps);
|
||||
}
|
||||
|
||||
w64(mmio, QDESC_LO, QDESC_HI, d.pa);
|
||||
w64(mmio, QAVAIL_LO, QAVAIL_HI, a.pa);
|
||||
w64(mmio, QUSED_LO, QUSED_HI, u.pa);
|
||||
|
||||
let dp = d.va as *mut Desc;
|
||||
for i in 0..size {
|
||||
unsafe {
|
||||
(*dp.add(i as usize)).flags = 0;
|
||||
(*dp.add(i as usize)).next = if i + 1 < size { i + 1 } else { 0xFFFF };
|
||||
}
|
||||
}
|
||||
|
||||
w32(mmio, QREADY, 1);
|
||||
|
||||
Self {
|
||||
sel,
|
||||
size,
|
||||
desc_va: d.va,
|
||||
avail_va: a.va,
|
||||
used_va: u.va,
|
||||
avail_idx: 0,
|
||||
used_idx: 0,
|
||||
free_head: 0,
|
||||
free_cnt: size,
|
||||
}
|
||||
}
|
||||
|
||||
fn alloc(&mut self) -> u16 {
|
||||
debug_assert!(self.free_cnt > 0);
|
||||
let h = self.free_head;
|
||||
let dp = self.desc_va as *mut Desc;
|
||||
unsafe {
|
||||
self.free_head = (*dp.add(h as usize)).next;
|
||||
}
|
||||
self.free_cnt -= 1;
|
||||
h
|
||||
}
|
||||
|
||||
fn free_chain(&mut self, mut idx: u16) {
|
||||
let dp = self.desc_va as *mut Desc;
|
||||
loop {
|
||||
self.free_cnt += 1;
|
||||
let (flags, next) = unsafe {
|
||||
let p = dp.add(idx as usize);
|
||||
((*p).flags, (*p).next)
|
||||
};
|
||||
if (flags & D_NEXT) == 0 {
|
||||
break;
|
||||
}
|
||||
idx = next;
|
||||
}
|
||||
unsafe {
|
||||
(*dp.add(idx as usize)).next = self.free_head;
|
||||
}
|
||||
self.free_head = idx;
|
||||
}
|
||||
|
||||
fn push_avail(&mut self, head: u16) {
|
||||
let ap = self.avail_va as *mut Avail;
|
||||
let ring = unsafe { (ap as *mut u8).add(size_of::<Avail>()) as *mut u16 };
|
||||
let slot = (self.avail_idx % self.size) as usize;
|
||||
unsafe {
|
||||
*ring.add(slot) = head;
|
||||
}
|
||||
wmb();
|
||||
self.avail_idx = self.avail_idx.wrapping_add(1);
|
||||
unsafe {
|
||||
(*ap).idx = self.avail_idx;
|
||||
}
|
||||
}
|
||||
|
||||
fn pop_used(&mut self) -> Option<UsedElem> {
|
||||
let up = self.used_va as *mut Used;
|
||||
if unsafe { (*up).idx } == self.used_idx {
|
||||
return None;
|
||||
}
|
||||
let ring = unsafe { (up as *mut u8).add(size_of::<Used>()) as *mut UsedElem };
|
||||
let elem = unsafe { *ring.add((self.used_idx % self.size) as usize) };
|
||||
self.used_idx = self.used_idx.wrapping_add(1);
|
||||
Some(elem)
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
mmio: *mut u8,
|
||||
|
||||
ctrl_rx: Vq,
|
||||
ctrl_tx: Vq,
|
||||
|
||||
port_id: Option<u32>,
|
||||
rx: Option<Vq>,
|
||||
tx: Option<Vq>,
|
||||
|
||||
rx_need: usize,
|
||||
rx_have: usize,
|
||||
rx_lenbuf: [u8; 4],
|
||||
rx_lenhave: usize,
|
||||
rx_buf: Option<&'static mut [u8]>,
|
||||
|
||||
tx_head: *mut TxNode,
|
||||
tx_tail: *mut TxNode,
|
||||
|
||||
ctrl_rx_pages: [Option<DmaPage>; QSZ as usize],
|
||||
data_rx_pages: [Option<DmaPage>; QSZ as usize],
|
||||
tx_pages: [Option<DmaPage>; QSZ as usize],
|
||||
|
||||
wake_token: *const u8,
|
||||
|
||||
on_rx: Option<fn(&[u8])>,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct TxNode {
|
||||
next: *mut TxNode,
|
||||
frame: &'static [u8],
|
||||
}
|
||||
|
||||
pub struct Hostlink {
|
||||
state: UnsafeCell<Inner>,
|
||||
}
|
||||
|
||||
unsafe impl Send for Hostlink {}
|
||||
|
||||
impl Hostlink {
|
||||
pub fn init(mmio_base: u64, irq_line: u32, on_rx: Option<fn(&[u8])>, wake_token: *const u8) -> Result<Self, ()> {
|
||||
let page_size = gum_barebone_query_page_size();
|
||||
PAGE_SIZE.store(page_size as usize, Ordering::Relaxed);
|
||||
|
||||
let mmio = xnu::ml_io_map(mmio_base, MMIO_SIZE) as *mut u8;
|
||||
if mmio.is_null() {
|
||||
return Err(());
|
||||
}
|
||||
|
||||
w32(mmio, STATUS, 0);
|
||||
w32(mmio, STATUS, ST_ACK | ST_DRV);
|
||||
|
||||
let magic_ok = r32(mmio, MAGIC) == 0x7472_6976;
|
||||
let version_ok = r32(mmio, VERSION) == 2;
|
||||
let device_ok = r32(mmio, DEVICE) == DEV_ID_CONSOLE;
|
||||
if !(magic_ok && version_ok && device_ok) {
|
||||
w32(mmio, STATUS, ST_FAILED);
|
||||
return Err(());
|
||||
}
|
||||
|
||||
let dev_lo = feat_get(mmio, 0) as u64;
|
||||
let dev_hi = (feat_get(mmio, 1) as u64) << 32;
|
||||
let mut drv: u64 = 0;
|
||||
if (dev_hi & F_VERSION_1) != 0 {
|
||||
drv |= F_VERSION_1;
|
||||
}
|
||||
if (dev_lo & F_MULTIPORT) != 0 {
|
||||
drv |= F_MULTIPORT;
|
||||
}
|
||||
feat_set(mmio, 0, (drv & 0xffff_ffff) as u32);
|
||||
feat_set(mmio, 1, (drv >> 32) as u32);
|
||||
w32(mmio, STATUS, r32(mmio, STATUS) | ST_FEAT_OK);
|
||||
let feats_ok = (r32(mmio, STATUS) & ST_FEAT_OK) != 0;
|
||||
if !feats_ok {
|
||||
w32(mmio, STATUS, ST_FAILED);
|
||||
return Err(());
|
||||
}
|
||||
|
||||
let ctrl_rx = Vq::new(mmio, Q_CTRL_RX, QSZ);
|
||||
let ctrl_tx = Vq::new(mmio, Q_CTRL_TX, QSZ);
|
||||
|
||||
w32(mmio, STATUS, r32(mmio, STATUS) | ST_DRV_OK);
|
||||
|
||||
xnu::install_interrupt_handler(
|
||||
irq_line,
|
||||
wake_token as *mut c_void,
|
||||
isr_wake,
|
||||
core::ptr::null_mut(),
|
||||
);
|
||||
|
||||
let inner = Inner {
|
||||
mmio,
|
||||
ctrl_rx,
|
||||
ctrl_tx,
|
||||
port_id: None,
|
||||
rx: None,
|
||||
tx: None,
|
||||
rx_need: 0,
|
||||
rx_have: 0,
|
||||
rx_lenbuf: [0; 4],
|
||||
rx_lenhave: 0,
|
||||
rx_buf: None,
|
||||
tx_head: core::ptr::null_mut(),
|
||||
tx_tail: core::ptr::null_mut(),
|
||||
ctrl_rx_pages: [None; QSZ as usize],
|
||||
data_rx_pages: [None; QSZ as usize],
|
||||
tx_pages: [None; QSZ as usize],
|
||||
wake_token,
|
||||
on_rx,
|
||||
};
|
||||
|
||||
let hl = Hostlink {
|
||||
state: UnsafeCell::new(inner),
|
||||
};
|
||||
|
||||
hl.ctrl_prime_rx(8);
|
||||
hl.ctrl_send(VConsCtrl {
|
||||
id: 0,
|
||||
event: EV_DEVICE_READY,
|
||||
value: 1,
|
||||
});
|
||||
|
||||
Ok(hl)
|
||||
}
|
||||
|
||||
pub fn send(&self, payload: &[u8]) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
|
||||
let total = 4 + payload.len();
|
||||
let buf = xnu::kalloc(total);
|
||||
unsafe {
|
||||
let len = payload.len() as u32;
|
||||
*buf.add(0) = (len & 0xFF) as u8;
|
||||
*buf.add(1) = ((len >> 8) & 0xFF) as u8;
|
||||
*buf.add(2) = ((len >> 16) & 0xFF) as u8;
|
||||
*buf.add(3) = ((len >> 24) & 0xFF) as u8;
|
||||
core::ptr::copy_nonoverlapping(payload.as_ptr(), buf.add(4), payload.len());
|
||||
}
|
||||
let frame: &'static [u8] = unsafe { core::slice::from_raw_parts(buf, total) };
|
||||
|
||||
let node = xnu::kalloc(size_of::<TxNode>()) as *mut TxNode;
|
||||
unsafe {
|
||||
(*node).next = core::ptr::null_mut();
|
||||
(*node).frame = frame;
|
||||
}
|
||||
|
||||
if s.tx_tail.is_null() {
|
||||
s.tx_head = node;
|
||||
s.tx_tail = node;
|
||||
} else {
|
||||
unsafe {
|
||||
(*s.tx_tail).next = node;
|
||||
}
|
||||
s.tx_tail = node;
|
||||
}
|
||||
|
||||
xnu::thread_wakeup(s.wake_token);
|
||||
}
|
||||
|
||||
pub fn process(&self) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
|
||||
if (r32(s.mmio, ISR) & INT_VRING) != 0 {
|
||||
w32(s.mmio, ISR_ACK, INT_VRING);
|
||||
}
|
||||
|
||||
self.ctrl_complete();
|
||||
self.ctrl_prime_rx(QSZ as usize);
|
||||
|
||||
self.data_rx_complete();
|
||||
self.data_tx_complete();
|
||||
self.data_tx_push();
|
||||
self.data_rx_refill();
|
||||
}
|
||||
|
||||
fn ctrl_prime_rx(&self, count: usize) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
let mut posted = 0usize;
|
||||
while posted < count {
|
||||
if s.ctrl_rx.free_cnt == 0 {
|
||||
break;
|
||||
}
|
||||
let pg = dma_page_alloc();
|
||||
let h = s.ctrl_rx.alloc();
|
||||
let d = s.ctrl_rx.desc_va as *mut Desc;
|
||||
unsafe {
|
||||
(*d.add(h as usize)).addr = pg.pa;
|
||||
(*d.add(h as usize)).len = PAGE_SIZE.load(Ordering::Relaxed) as u32;
|
||||
(*d.add(h as usize)).flags = D_WRITE;
|
||||
(*d.add(h as usize)).next = 0;
|
||||
}
|
||||
s.ctrl_rx_pages[h as usize] = Some(pg);
|
||||
s.ctrl_rx.push_avail(h);
|
||||
posted += 1;
|
||||
}
|
||||
let sel = s.ctrl_rx.sel;
|
||||
self.kick(sel);
|
||||
}
|
||||
|
||||
fn ctrl_send(&self, msg: VConsCtrl) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
let pg = dma_page_alloc();
|
||||
unsafe {
|
||||
core::ptr::write(pg.va as *mut VConsCtrl, msg);
|
||||
}
|
||||
let h = s.ctrl_tx.alloc();
|
||||
let d = s.ctrl_tx.desc_va as *mut Desc;
|
||||
unsafe {
|
||||
(*d.add(h as usize)).addr = pg.pa;
|
||||
(*d.add(h as usize)).len = size_of::<VConsCtrl>() as u32;
|
||||
(*d.add(h as usize)).flags = 0;
|
||||
(*d.add(h as usize)).next = 0;
|
||||
}
|
||||
s.tx_pages[h as usize] = Some(pg);
|
||||
s.ctrl_tx.push_avail(h);
|
||||
let sel = s.ctrl_tx.sel;
|
||||
self.kick(sel);
|
||||
}
|
||||
|
||||
fn ctrl_complete(&self) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
while let Some(u) = s.ctrl_rx.pop_used() {
|
||||
let h = u.id as u16;
|
||||
if let Some(pg) = s.ctrl_rx_pages[h as usize].take() {
|
||||
let ev = unsafe { *(pg.va as *const VConsCtrl) };
|
||||
dma_page_free(pg);
|
||||
|
||||
match ev.event {
|
||||
EV_DEVICE_ADD | EV_CONSOLE_PORT => {
|
||||
if s.port_id.is_none() {
|
||||
self.setup_data_port(ev.id);
|
||||
self.ctrl_send(VConsCtrl {
|
||||
id: ev.id,
|
||||
event: EV_PORT_READY,
|
||||
value: 1,
|
||||
});
|
||||
self.ctrl_send(VConsCtrl {
|
||||
id: ev.id,
|
||||
event: EV_PORT_OPEN,
|
||||
value: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let pg2 = dma_page_alloc();
|
||||
let d = s.ctrl_rx.desc_va as *mut Desc;
|
||||
unsafe {
|
||||
(*d.add(h as usize)).addr = pg2.pa;
|
||||
(*d.add(h as usize)).len = PAGE_SIZE.load(Ordering::Relaxed) as u32;
|
||||
(*d.add(h as usize)).flags = D_WRITE;
|
||||
(*d.add(h as usize)).next = 0;
|
||||
}
|
||||
s.ctrl_rx_pages[h as usize] = Some(pg2);
|
||||
s.ctrl_rx.push_avail(h);
|
||||
}
|
||||
}
|
||||
let sel = s.ctrl_rx.sel;
|
||||
self.kick(sel);
|
||||
|
||||
while let Some(u) = s.ctrl_tx.pop_used() {
|
||||
let head = u.id as u16;
|
||||
if let Some(pg) = s.tx_pages[head as usize].take() {
|
||||
dma_page_free(pg);
|
||||
}
|
||||
s.ctrl_tx.free_chain(head);
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_data_port(&self, id: u32) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
if s.port_id.is_some() {
|
||||
return;
|
||||
}
|
||||
let (rx_i, tx_i) = if id == 0 {
|
||||
(Q_RX0, Q_TX0)
|
||||
} else {
|
||||
let base = 4 + ((id as u16 - 1) * 2);
|
||||
(base, base + 1)
|
||||
};
|
||||
let rx = Vq::new(s.mmio, rx_i, QSZ);
|
||||
let tx = Vq::new(s.mmio, tx_i, QSZ);
|
||||
s.rx = Some(rx);
|
||||
s.tx = Some(tx);
|
||||
s.port_id = Some(id);
|
||||
self.data_rx_refill();
|
||||
}
|
||||
|
||||
fn data_rx_refill(&self) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
let Some(rxq) = s.rx.as_mut() else {
|
||||
return;
|
||||
};
|
||||
while rxq.free_cnt > 0 {
|
||||
let h = rxq.alloc();
|
||||
let pg = dma_page_alloc();
|
||||
let d = rxq.desc_va as *mut Desc;
|
||||
unsafe {
|
||||
(*d.add(h as usize)).addr = pg.pa;
|
||||
(*d.add(h as usize)).len = PAGE_SIZE.load(Ordering::Relaxed) as u32;
|
||||
(*d.add(h as usize)).flags = D_WRITE;
|
||||
(*d.add(h as usize)).next = 0;
|
||||
}
|
||||
s.data_rx_pages[h as usize] = Some(pg);
|
||||
rxq.push_avail(h);
|
||||
}
|
||||
let sel = rxq.sel;
|
||||
self.kick(sel);
|
||||
}
|
||||
|
||||
fn data_rx_complete(&self) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
let Some(rxq) = s.rx.as_mut() else {
|
||||
return;
|
||||
};
|
||||
while let Some(u) = rxq.pop_used() {
|
||||
let h = u.id as u16;
|
||||
let n = u.len as usize;
|
||||
|
||||
if let Some(pg) = s.data_rx_pages[h as usize].take() {
|
||||
{
|
||||
let bytes = unsafe { core::slice::from_raw_parts(pg.va, n) };
|
||||
self.feed_rx_stream(bytes);
|
||||
}
|
||||
dma_page_free(pg);
|
||||
|
||||
let pg2 = dma_page_alloc();
|
||||
let d = rxq.desc_va as *mut Desc;
|
||||
unsafe {
|
||||
(*d.add(h as usize)).addr = pg2.pa;
|
||||
(*d.add(h as usize)).len = PAGE_SIZE.load(Ordering::Relaxed) as u32;
|
||||
(*d.add(h as usize)).flags = D_WRITE;
|
||||
(*d.add(h as usize)).next = 0;
|
||||
}
|
||||
s.data_rx_pages[h as usize] = Some(pg2);
|
||||
rxq.push_avail(h);
|
||||
}
|
||||
}
|
||||
let sel = rxq.sel;
|
||||
self.kick(sel);
|
||||
}
|
||||
|
||||
fn feed_rx_stream(&self, mut chunk: &[u8]) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
while !chunk.is_empty() {
|
||||
if s.rx_lenhave < 4 {
|
||||
let need = 4 - s.rx_lenhave;
|
||||
let take = core::cmp::min(need, chunk.len());
|
||||
s.rx_lenbuf[s.rx_lenhave..s.rx_lenhave + take].copy_from_slice(&chunk[..take]);
|
||||
s.rx_lenhave += take;
|
||||
chunk = &chunk[take..];
|
||||
if s.rx_lenhave < 4 {
|
||||
return;
|
||||
}
|
||||
|
||||
let len = (s.rx_lenbuf[0] as usize)
|
||||
| ((s.rx_lenbuf[1] as usize) << 8)
|
||||
| ((s.rx_lenbuf[2] as usize) << 16)
|
||||
| ((s.rx_lenbuf[3] as usize) << 24);
|
||||
|
||||
if s.rx_buf.is_none() && len > 0 {
|
||||
let buf = xnu::kalloc(len);
|
||||
let slice: &'static mut [u8] =
|
||||
unsafe { core::slice::from_raw_parts_mut(buf, len) };
|
||||
s.rx_buf = Some(slice);
|
||||
s.rx_need = len;
|
||||
s.rx_have = 0;
|
||||
}
|
||||
}
|
||||
|
||||
let need = s.rx_need.saturating_sub(s.rx_have);
|
||||
let take = core::cmp::min(need, chunk.len());
|
||||
if let Some(ref mut buf) = s.rx_buf {
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(
|
||||
chunk.as_ptr(),
|
||||
buf.as_mut_ptr().wrapping_add(s.rx_have),
|
||||
take,
|
||||
);
|
||||
}
|
||||
}
|
||||
s.rx_have += take;
|
||||
chunk = &chunk[take..];
|
||||
|
||||
if s.rx_have == s.rx_need {
|
||||
if let (Some(cb), Some(buf)) = (s.on_rx, &s.rx_buf) {
|
||||
cb(&buf[..]);
|
||||
}
|
||||
s.rx_buf = None;
|
||||
s.rx_need = 0;
|
||||
s.rx_have = 0;
|
||||
s.rx_lenhave = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn data_tx_complete(&self) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
let Some(txq) = s.tx.as_mut() else {
|
||||
return;
|
||||
};
|
||||
while let Some(u) = txq.pop_used() {
|
||||
let mut i = u.id as u16;
|
||||
loop {
|
||||
if let Some(pg) = s.tx_pages[i as usize].take() {
|
||||
dma_page_free(pg);
|
||||
}
|
||||
let d = txq.desc_va as *mut Desc;
|
||||
let (f, n) = unsafe {
|
||||
let p = d.add(i as usize);
|
||||
((*p).flags, (*p).next)
|
||||
};
|
||||
if (f & D_NEXT) == 0 {
|
||||
break;
|
||||
}
|
||||
i = n;
|
||||
}
|
||||
txq.free_chain(u.id as u16);
|
||||
}
|
||||
}
|
||||
|
||||
fn data_tx_push(&self) {
|
||||
let s = unsafe { &mut *self.state.get() };
|
||||
let Some(txq) = s.tx.as_mut() else {
|
||||
return;
|
||||
};
|
||||
loop {
|
||||
let node = if s.tx_head.is_null() {
|
||||
core::ptr::null_mut()
|
||||
} else {
|
||||
let n = s.tx_head;
|
||||
s.tx_head = unsafe { (*n).next };
|
||||
if s.tx_head.is_null() {
|
||||
s.tx_tail = core::ptr::null_mut();
|
||||
}
|
||||
n
|
||||
};
|
||||
if node.is_null() {
|
||||
break;
|
||||
}
|
||||
let frame = unsafe { (*node).frame };
|
||||
|
||||
let mut off = 0usize;
|
||||
let mut head: Option<u16> = None;
|
||||
let mut prev = 0u16;
|
||||
|
||||
while off < frame.len() {
|
||||
if txq.free_cnt == 0 {
|
||||
break;
|
||||
}
|
||||
let page = PAGE_SIZE.load(Ordering::Relaxed);
|
||||
let chunk = core::cmp::min(page, frame.len() - off);
|
||||
let pg = dma_page_alloc();
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(frame.as_ptr().add(off), pg.va, chunk);
|
||||
}
|
||||
|
||||
let i = txq.alloc();
|
||||
let d = txq.desc_va as *mut Desc;
|
||||
unsafe {
|
||||
(*d.add(i as usize)).addr = pg.pa;
|
||||
(*d.add(i as usize)).len = chunk as u32;
|
||||
(*d.add(i as usize)).flags = 0;
|
||||
(*d.add(i as usize)).next = 0;
|
||||
}
|
||||
s.tx_pages[i as usize] = Some(pg);
|
||||
|
||||
if let Some(_h) = head {
|
||||
unsafe {
|
||||
(*d.add(prev as usize)).flags |= D_NEXT;
|
||||
(*d.add(prev as usize)).next = i;
|
||||
}
|
||||
prev = i;
|
||||
} else {
|
||||
head = Some(i);
|
||||
prev = i;
|
||||
}
|
||||
|
||||
off += chunk;
|
||||
}
|
||||
|
||||
if let Some(h) = head {
|
||||
let sel = txq.sel;
|
||||
txq.push_avail(h);
|
||||
self.kick(sel);
|
||||
}
|
||||
|
||||
xnu::free(frame.as_ptr() as *mut u8, frame.len());
|
||||
xnu::free(node as *mut u8, core::mem::size_of::<TxNode>());
|
||||
}
|
||||
}
|
||||
|
||||
fn kick(&self, sel: u16) {
|
||||
let s = unsafe { &*self.state.get() };
|
||||
wmb();
|
||||
w32(s.mmio, QSEL, sel as u32);
|
||||
w32(s.mmio, QNOTIFY, sel as u32);
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn isr_wake(token: *mut c_void, _refcon: *mut c_void, _nub: *mut c_void, _src: i32) {
|
||||
xnu::thread_wakeup(token as *const u8);
|
||||
}
|
||||
|
||||
fn r32(mmio: *mut u8, off: usize) -> u32 {
|
||||
unsafe { read_volatile(mmio.add(off) as *const u32) }
|
||||
}
|
||||
|
||||
fn w32(mmio: *mut u8, off: usize, val: u32) {
|
||||
unsafe { write_volatile(mmio.add(off) as *mut u32, val) }
|
||||
}
|
||||
|
||||
fn w64(mmio: *mut u8, lo: usize, hi: usize, v: u64) {
|
||||
w32(mmio, lo, (v & 0xffff_ffff) as u32);
|
||||
w32(mmio, hi, (v >> 32) as u32);
|
||||
}
|
||||
|
||||
fn feat_get(mmio: *mut u8, sel: u32) -> u32 {
|
||||
w32(mmio, DEVFEAT_SEL, sel);
|
||||
r32(mmio, DEVFEAT)
|
||||
}
|
||||
|
||||
fn feat_set(mmio: *mut u8, sel: u32, v: u32) {
|
||||
w32(mmio, DRVFEAT_SEL, sel);
|
||||
w32(mmio, DRVFEAT, v)
|
||||
}
|
||||
|
||||
fn wmb() {
|
||||
unsafe { core::arch::asm!("dmb ishst", options(nostack, preserves_flags)) }
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
use core::ptr;
|
||||
use crate::bindings::{GMutex, GRecMutex};
|
||||
use crate::gthread;
|
||||
|
||||
static mut MALLOC_LOCK: GRecMutex = unsafe { core::mem::zeroed() };
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn __malloc_lock(_reent: *mut core::ffi::c_void) {
|
||||
gthread::g_rec_mutex_lock(ptr::addr_of_mut!(MALLOC_LOCK));
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn __malloc_unlock(_reent: *mut core::ffi::c_void) {
|
||||
gthread::g_rec_mutex_unlock(ptr::addr_of_mut!(MALLOC_LOCK));
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _fini() {
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _exit(_status: i32) -> ! {
|
||||
loop {}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _kill(_pid: i32, _sig: i32) -> i32 {
|
||||
-1
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _sbrk(incr: isize) -> *mut u8 {
|
||||
const HEAP_SIZE: usize = 32 * 1024 * 1024; // 32 MB
|
||||
|
||||
static mut HEAP_START: *mut u8 = ptr::null_mut();
|
||||
static mut HEAP_CURRENT: *mut u8 = ptr::null_mut();
|
||||
static mut HEAP_MUTEX: GMutex = unsafe { core::mem::zeroed() };
|
||||
|
||||
unsafe {
|
||||
gthread::g_mutex_lock(ptr::addr_of_mut!(HEAP_MUTEX));
|
||||
|
||||
if HEAP_START.is_null() {
|
||||
HEAP_START = crate::xnu::kalloc(HEAP_SIZE);
|
||||
if HEAP_START.is_null() {
|
||||
gthread::g_mutex_unlock(ptr::addr_of_mut!(HEAP_MUTEX));
|
||||
panic!("Failed to allocate 32 MB heap");
|
||||
}
|
||||
HEAP_CURRENT = HEAP_START;
|
||||
}
|
||||
|
||||
let prev_heap_current = HEAP_CURRENT;
|
||||
let new_heap_current = HEAP_CURRENT.add(incr as usize);
|
||||
|
||||
if new_heap_current > HEAP_START.add(HEAP_SIZE) {
|
||||
gthread::g_mutex_unlock(ptr::addr_of_mut!(HEAP_MUTEX));
|
||||
panic!("Heap exhausted: requested {} bytes, {} bytes remaining",
|
||||
incr,
|
||||
HEAP_START.add(HEAP_SIZE).offset_from(HEAP_CURRENT));
|
||||
}
|
||||
|
||||
HEAP_CURRENT = new_heap_current;
|
||||
|
||||
gthread::g_mutex_unlock(ptr::addr_of_mut!(HEAP_MUTEX));
|
||||
prev_heap_current
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _getpid() -> i32 {
|
||||
0
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Timeval {
|
||||
tv_sec: i64,
|
||||
tv_usec: i64,
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _gettimeofday(tp: *mut core::ffi::c_void, _tzp: *mut core::ffi::c_void) -> i32 {
|
||||
let (secs, microsecs) = crate::xnu::clock_get_calendar_microtime();
|
||||
let timeval = Timeval {
|
||||
tv_sec: secs as i64,
|
||||
tv_usec: microsecs as i64,
|
||||
};
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(
|
||||
&timeval as *const Timeval as *const u8,
|
||||
tp as *mut u8,
|
||||
core::mem::size_of::<Timeval>(),
|
||||
);
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _isatty(_fd: i32) -> i32 {
|
||||
1
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _open(_path: *const u8, _flags: i32, _mode: i32) -> i32 {
|
||||
-1
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _close(_fd: i32) -> i32 {
|
||||
0
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _read(_fd: i32, _buf: *mut u8, _count: usize) -> isize {
|
||||
0
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _write(_fd: i32, _buf: *const u8, count: usize) -> isize {
|
||||
count as isize
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _lseek(_fd: i32, _offset: isize, _whence: i32) -> isize {
|
||||
0
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _fstat(_fd: i32, _st: *mut core::ffi::c_void) -> i32 {
|
||||
0
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _link(_old: *const u8, _new: *const u8) -> i32 {
|
||||
-1
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn _unlink(_path: *const u8) -> i32 {
|
||||
-1
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn __clear_cache(_start: *const u8, _end: *const u8) {
|
||||
// On AArch64, we need to flush the instruction cache
|
||||
// This is a simplified implementation for the kernel environment
|
||||
unsafe {
|
||||
core::arch::asm!(
|
||||
"ic iallu", // Invalidate all instruction caches
|
||||
"dsb sy", // Data synchronization barrier
|
||||
"isb", // Instruction synchronization barrier
|
||||
options(nomem, nostack),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
#![no_main]
|
||||
#![no_std]
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use alloc::collections::BTreeMap;
|
||||
use alloc::format;
|
||||
use alloc::string::String;
|
||||
use alloc::vec::Vec;
|
||||
use core::alloc::{GlobalAlloc, Layout};
|
||||
use core::ffi::{CStr, c_void};
|
||||
use core::ptr;
|
||||
use core::ptr::null_mut;
|
||||
use core::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use bindings::{
|
||||
GBytes, GCancellable, GError, GVariant, GVariantIter, GumScript, g_error_free, g_free,
|
||||
g_main_context_default, g_main_context_iteration, g_memdup2, g_object_unref,
|
||||
g_variant_check_format_string, g_variant_get, g_variant_get_child_value, g_variant_get_data,
|
||||
g_variant_get_size, g_variant_get_string, g_variant_get_uint32, g_variant_get_uint64,
|
||||
g_variant_iter_init, g_variant_iter_next, g_variant_new, g_variant_new_from_data,
|
||||
g_variant_new_string, g_variant_new_tuple, g_variant_new_uint32, g_variant_type_free,
|
||||
g_variant_type_new, g_variant_unref, gchar, gpointer, gsize, gum_script_backend_create_sync,
|
||||
gum_script_backend_obtain_qjs, gum_script_load_sync, gum_script_post,
|
||||
gum_script_set_message_handler, gum_script_unload_sync,
|
||||
};
|
||||
use hostlink_virtio::Hostlink;
|
||||
use symbols::SymbolTable;
|
||||
|
||||
mod glib;
|
||||
mod gthread;
|
||||
mod gum;
|
||||
mod hostlink_virtio;
|
||||
|
||||
mod libc;
|
||||
mod pac;
|
||||
mod symbols;
|
||||
mod xnu;
|
||||
|
||||
mod bindings {
|
||||
#![allow(
|
||||
dead_code,
|
||||
improper_ctypes,
|
||||
non_camel_case_types,
|
||||
non_snake_case,
|
||||
non_upper_case_globals,
|
||||
unused_imports
|
||||
)]
|
||||
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
|
||||
pub enum FridaCommand {
|
||||
CreateScript = 1,
|
||||
LoadScript = 2,
|
||||
DestroyScript = 3,
|
||||
PostScriptMessage = 4,
|
||||
|
||||
Reply = 128,
|
||||
ScriptMessage = 129,
|
||||
}
|
||||
|
||||
impl core::fmt::Display for FridaCommand {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
FridaCommand::CreateScript => write!(f, "CreateScript"),
|
||||
FridaCommand::LoadScript => write!(f, "LoadScript"),
|
||||
FridaCommand::DestroyScript => write!(f, "DestroyScript"),
|
||||
FridaCommand::PostScriptMessage => write!(f, "PostScriptMessage"),
|
||||
FridaCommand::Reply => write!(f, "Reply"),
|
||||
FridaCommand::ScriptMessage => write!(f, "ScriptMessage"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct HandlerResponse {
|
||||
variant: *mut GVariant,
|
||||
}
|
||||
|
||||
impl HandlerResponse {
|
||||
fn success(variant: *mut GVariant) -> Self {
|
||||
Self { variant }
|
||||
}
|
||||
|
||||
fn success_empty() -> Self {
|
||||
let variant = unsafe { g_variant_new_tuple(ptr::null(), 0) };
|
||||
Self { variant }
|
||||
}
|
||||
|
||||
fn error(message: &str) -> Self {
|
||||
let mut c_message = String::from(message);
|
||||
c_message.push('\0');
|
||||
let error_variant = unsafe { g_variant_new_string(c_message.as_ptr()) };
|
||||
|
||||
Self {
|
||||
variant: error_variant,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static mut CONFIG_DATA: &'static [u8] = &[];
|
||||
pub static mut MODULE_INFO: Vec<ModuleInfo> = Vec::new();
|
||||
pub static mut SYMBOL_TABLE: SymbolTable = SymbolTable::empty();
|
||||
|
||||
static mut TRANSPORT_DRIVER: *mut Hostlink = core::ptr::null_mut();
|
||||
|
||||
#[inline(always)]
|
||||
fn transport_set(driver: Hostlink) {
|
||||
unsafe {
|
||||
let boxed = Box::into_raw(Box::new(driver));
|
||||
TRANSPORT_DRIVER = boxed;
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn transport_get_unchecked() -> &'static Hostlink {
|
||||
unsafe {
|
||||
debug_assert!(!TRANSPORT_DRIVER.is_null());
|
||||
&*TRANSPORT_DRIVER
|
||||
}
|
||||
}
|
||||
|
||||
static mut SCRIPTS: BTreeMap<u32, *mut GumScript> = BTreeMap::new();
|
||||
static NEXT_SCRIPT_ID: AtomicU32 = AtomicU32::new(1);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ModuleInfo {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub offset: u32,
|
||||
pub size: u32,
|
||||
pub start_func_offset: u32,
|
||||
pub stop_func_offset: u32,
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn _start(config_data: *const u8, config_size: usize) {
|
||||
unsafe {
|
||||
CONFIG_DATA = core::slice::from_raw_parts(config_data, config_size);
|
||||
|
||||
xnu::kernel_thread_start(frida_agent_worker, 12345usize as *mut core::ffi::c_void);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn frida_agent_worker(_parameter: *mut core::ffi::c_void, _wait_result: i32) {
|
||||
unsafe {
|
||||
bindings::g_set_panic_handler(Some(frida_panic_handler), ptr::null_mut());
|
||||
bindings::gum_init_embedded();
|
||||
bindings::g_log_set_default_handler(Some(frida_log_handler), ptr::null_mut());
|
||||
|
||||
let (mmio, irq, kernel_base, module_info, symbol_table) =
|
||||
parse_config(core::ptr::addr_of!(CONFIG_DATA).read());
|
||||
xnu::set_kernel_base(kernel_base);
|
||||
MODULE_INFO = module_info;
|
||||
SYMBOL_TABLE = symbol_table;
|
||||
|
||||
transport_set(
|
||||
Hostlink::init(
|
||||
mmio,
|
||||
irq,
|
||||
Some(on_frame_from_host),
|
||||
ptr::addr_of_mut!(glib::WAKEUP_TOKEN) as *const u8,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let main_context = g_main_context_default();
|
||||
|
||||
loop {
|
||||
transport_get_unchecked().process();
|
||||
g_main_context_iteration(main_context, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_frame_from_host(frame: &[u8]) {
|
||||
if let Some(variant) = deserialize_message(&frame) {
|
||||
process_incoming_message(variant);
|
||||
unsafe {
|
||||
g_variant_unref(variant);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn parse_config(config: &[u8]) -> (u64, u32, u64, Vec<ModuleInfo>, SymbolTable) {
|
||||
unsafe {
|
||||
let type_string = c"(tuta(ssuuuu)ay)".as_ptr() as *const gchar;
|
||||
let variant_type = g_variant_type_new(type_string);
|
||||
|
||||
let root_variant = g_variant_new_from_data(
|
||||
variant_type,
|
||||
config.as_ptr() as *const core::ffi::c_void,
|
||||
config.len() as gsize,
|
||||
1,
|
||||
None,
|
||||
ptr::null_mut(),
|
||||
);
|
||||
|
||||
let hostlink_mmio_variant = g_variant_get_child_value(root_variant, 0);
|
||||
let hostlink_mmio = g_variant_get_uint64(hostlink_mmio_variant);
|
||||
|
||||
let hostlink_irq_variant = g_variant_get_child_value(root_variant, 1);
|
||||
let hostlink_irq = g_variant_get_uint32(hostlink_irq_variant);
|
||||
|
||||
let kernel_base_variant = g_variant_get_child_value(root_variant, 2);
|
||||
let kernel_base = g_variant_get_uint64(kernel_base_variant);
|
||||
xnu::set_kernel_base(kernel_base);
|
||||
|
||||
let module_info_variant = g_variant_get_child_value(root_variant, 3);
|
||||
let mut iter: GVariantIter = core::mem::zeroed();
|
||||
g_variant_iter_init(&mut iter as *mut GVariantIter, module_info_variant);
|
||||
|
||||
let mut module_info: Vec<ModuleInfo> = Vec::new();
|
||||
let mut raw_name: *mut gchar = null_mut();
|
||||
let mut raw_version: *mut gchar = null_mut();
|
||||
let mut offset: u32 = 0;
|
||||
let mut size: u32 = 0;
|
||||
let mut start_func_offset: u32 = 0;
|
||||
let mut stop_func_offset: u32 = 0;
|
||||
while g_variant_iter_next(
|
||||
&mut iter as *mut GVariantIter,
|
||||
c"(&s&suuuu)".as_ptr(),
|
||||
&mut raw_name,
|
||||
&mut raw_version,
|
||||
&mut offset,
|
||||
&mut size,
|
||||
&mut start_func_offset,
|
||||
&mut stop_func_offset,
|
||||
) != 0
|
||||
{
|
||||
module_info.push(ModuleInfo {
|
||||
name: String::from(CStr::from_ptr(raw_name).to_str().unwrap()),
|
||||
version: String::from(CStr::from_ptr(raw_version).to_str().unwrap()),
|
||||
offset,
|
||||
size,
|
||||
start_func_offset,
|
||||
stop_func_offset,
|
||||
});
|
||||
}
|
||||
|
||||
let symbol_array_variant = g_variant_get_child_value(root_variant, 4);
|
||||
let symbol_data_ptr = g_variant_get_data(symbol_array_variant) as *const u8;
|
||||
let symbol_data_size = g_variant_get_size(symbol_array_variant) as usize;
|
||||
let symbol_table = SymbolTable::new(core::slice::from_raw_parts(
|
||||
symbol_data_ptr,
|
||||
symbol_data_size,
|
||||
));
|
||||
|
||||
g_variant_unref(symbol_array_variant);
|
||||
g_variant_unref(module_info_variant);
|
||||
g_variant_unref(kernel_base_variant);
|
||||
g_variant_unref(hostlink_irq_variant);
|
||||
g_variant_unref(hostlink_mmio_variant);
|
||||
g_variant_unref(root_variant);
|
||||
g_variant_type_free(variant_type);
|
||||
|
||||
(
|
||||
hostlink_mmio,
|
||||
hostlink_irq,
|
||||
kernel_base,
|
||||
module_info,
|
||||
symbol_table,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn serialize_message(variant: *mut GVariant) -> Option<Vec<u8>> {
|
||||
unsafe {
|
||||
let size = g_variant_get_size(variant) as usize;
|
||||
if size == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let data_ptr = g_variant_get_data(variant) as *const u8;
|
||||
let mut result = Vec::with_capacity(size);
|
||||
result.resize(size, 0);
|
||||
core::ptr::copy_nonoverlapping(data_ptr, result.as_mut_ptr(), size);
|
||||
|
||||
Some(result)
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_message(data: &[u8]) -> Option<*mut GVariant> {
|
||||
unsafe {
|
||||
if data.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let variant_type = g_variant_type_new(c"(yqv)".as_ptr());
|
||||
let data_copy = g_memdup2(data.as_ptr() as *const c_void, data.len() as u64);
|
||||
let variant = g_variant_new_from_data(
|
||||
variant_type,
|
||||
data_copy,
|
||||
data.len() as u64,
|
||||
0,
|
||||
Some(g_free),
|
||||
data_copy,
|
||||
);
|
||||
g_variant_type_free(variant_type);
|
||||
|
||||
if variant.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(variant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_incoming_message(variant: *mut GVariant) {
|
||||
{
|
||||
let mut cmd_value: u8 = 0;
|
||||
let mut request_id: u16 = 0;
|
||||
let mut payload_variant: *mut GVariant = ptr::null_mut();
|
||||
|
||||
let cmd = unsafe {
|
||||
g_variant_get(
|
||||
variant,
|
||||
c"(yqv)".as_ptr(),
|
||||
&mut cmd_value,
|
||||
&mut request_id,
|
||||
&mut payload_variant,
|
||||
);
|
||||
|
||||
core::mem::transmute::<u8, FridaCommand>(cmd_value)
|
||||
};
|
||||
|
||||
let response = match cmd {
|
||||
FridaCommand::CreateScript => handle_create_script(payload_variant),
|
||||
FridaCommand::LoadScript => handle_load_script(payload_variant),
|
||||
FridaCommand::DestroyScript => handle_destroy_script(payload_variant),
|
||||
FridaCommand::PostScriptMessage => handle_post_script_message(payload_variant),
|
||||
_ => HandlerResponse::error("Unknown command"),
|
||||
};
|
||||
|
||||
send_command_reply(request_id, response);
|
||||
|
||||
unsafe { g_variant_unref(payload_variant) };
|
||||
}
|
||||
}
|
||||
|
||||
fn send_command_reply(request_id: u16, response: HandlerResponse) {
|
||||
unsafe {
|
||||
let message = g_variant_new(
|
||||
c"(yqv)".as_ptr(),
|
||||
FridaCommand::Reply as u8 as u32,
|
||||
request_id as u32,
|
||||
response.variant,
|
||||
);
|
||||
|
||||
if let Some(serialized) = serialize_message(message) {
|
||||
transport_get_unchecked().send(&serialized);
|
||||
}
|
||||
|
||||
g_variant_unref(message);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_create_script(payload_variant: *mut GVariant) -> HandlerResponse {
|
||||
unsafe {
|
||||
if g_variant_check_format_string(payload_variant, c"s".as_ptr(), 0) == 0 {
|
||||
return HandlerResponse::error("Invalid payload format: expected string");
|
||||
}
|
||||
let source = g_variant_get_string(payload_variant, core::ptr::null_mut());
|
||||
|
||||
let backend = gum_script_backend_obtain_qjs();
|
||||
let cancellable: *mut GCancellable = ptr::null_mut();
|
||||
let mut error: *mut GError = ptr::null_mut();
|
||||
|
||||
let script = gum_script_backend_create_sync(
|
||||
backend,
|
||||
c"agent.js".as_ptr(),
|
||||
source,
|
||||
ptr::null_mut(),
|
||||
cancellable,
|
||||
&mut error,
|
||||
);
|
||||
|
||||
if !error.is_null() {
|
||||
let error_msg = CStr::from_ptr((*error).message).to_str().unwrap();
|
||||
let error_string = String::from(error_msg);
|
||||
g_error_free(error);
|
||||
return HandlerResponse::error(&error_string);
|
||||
}
|
||||
|
||||
let script_id = NEXT_SCRIPT_ID.fetch_add(1, Ordering::Relaxed);
|
||||
|
||||
let script_id_ptr = Box::into_raw(Box::new(script_id));
|
||||
gum_script_set_message_handler(
|
||||
script,
|
||||
Some(frida_message_handler),
|
||||
script_id_ptr as *mut c_void,
|
||||
None,
|
||||
);
|
||||
|
||||
core::ptr::addr_of_mut!(SCRIPTS)
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.insert(script_id, script);
|
||||
|
||||
HandlerResponse::success(g_variant_new_uint32(script_id))
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn frida_message_handler(
|
||||
message: *const gchar,
|
||||
_data: *mut GBytes,
|
||||
user_data: gpointer,
|
||||
) {
|
||||
unsafe {
|
||||
let script_id = *(user_data as *const u32);
|
||||
|
||||
let message_variant = g_variant_new(
|
||||
c"(yqv)".as_ptr(),
|
||||
FridaCommand::ScriptMessage as u8 as u32,
|
||||
0u32,
|
||||
g_variant_new(c"(us)".as_ptr(), script_id, message),
|
||||
);
|
||||
|
||||
if let Some(serialized) = serialize_message(message_variant) {
|
||||
transport_get_unchecked().send(&serialized);
|
||||
}
|
||||
|
||||
g_variant_unref(message_variant);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_load_script(payload_variant: *mut GVariant) -> HandlerResponse {
|
||||
unsafe {
|
||||
if g_variant_check_format_string(payload_variant, c"u".as_ptr(), 0) == 0 {
|
||||
return HandlerResponse::error("Invalid payload format: expected uint32");
|
||||
}
|
||||
let script_id = g_variant_get_uint32(payload_variant);
|
||||
|
||||
let Some(script) = get_script_by_id(script_id) else {
|
||||
return HandlerResponse::error(&format!("Script with ID {} not found", script_id));
|
||||
};
|
||||
|
||||
gum_script_load_sync(script, ptr::null_mut());
|
||||
|
||||
HandlerResponse::success_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_destroy_script(payload_variant: *mut GVariant) -> HandlerResponse {
|
||||
unsafe {
|
||||
if g_variant_check_format_string(payload_variant, c"u".as_ptr(), 0) == 0 {
|
||||
return HandlerResponse::error("Invalid payload format: expected uint32");
|
||||
}
|
||||
let script_id = g_variant_get_uint32(payload_variant);
|
||||
|
||||
let scripts = core::ptr::addr_of_mut!(SCRIPTS).as_mut().unwrap();
|
||||
let Some(script) = scripts.remove(&script_id) else {
|
||||
return HandlerResponse::error(&format!("Script with ID {} not found", script_id));
|
||||
};
|
||||
|
||||
gum_script_unload_sync(script, ptr::null_mut());
|
||||
g_object_unref(script as *mut c_void);
|
||||
|
||||
HandlerResponse::success_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_post_script_message(payload_variant: *mut GVariant) -> HandlerResponse {
|
||||
unsafe {
|
||||
if g_variant_check_format_string(payload_variant, c"(us)".as_ptr(), 0) == 0 {
|
||||
return HandlerResponse::error("Invalid payload format: expected (uint32, string)");
|
||||
}
|
||||
let mut script_id: u32 = 0;
|
||||
let mut message: *const gchar = ptr::null();
|
||||
g_variant_get(
|
||||
payload_variant,
|
||||
c"(u&s)".as_ptr(),
|
||||
&mut script_id,
|
||||
&mut message,
|
||||
);
|
||||
|
||||
let Some(script) = get_script_by_id(script_id) else {
|
||||
return HandlerResponse::error(&format!("Script with ID {} not found", script_id));
|
||||
};
|
||||
|
||||
gum_script_post(script, message, ptr::null_mut());
|
||||
|
||||
HandlerResponse::success_empty()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn get_script_by_id(script_id: u32) -> Option<*mut GumScript> {
|
||||
unsafe {
|
||||
let scripts = core::ptr::addr_of_mut!(SCRIPTS).as_mut().unwrap();
|
||||
scripts.get(&script_id).copied()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn frida_panic_handler(message: *const u8, _user_data: *mut core::ffi::c_void) {
|
||||
let msg = unsafe { core::ffi::CStr::from_ptr(message).to_str().unwrap() };
|
||||
panic!("[Frida] {}", msg);
|
||||
}
|
||||
|
||||
unsafe extern "C" fn frida_log_handler(
|
||||
_log_domain: *const core::ffi::c_char,
|
||||
_log_level: i32,
|
||||
message: *const core::ffi::c_char,
|
||||
_user_data: *mut core::ffi::c_void,
|
||||
) {
|
||||
let msg = unsafe { core::ffi::CStr::from_ptr(message).to_str().unwrap() };
|
||||
kprintln!("[Frida] {}", msg);
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
|
||||
let mut s = format!("{}", info);
|
||||
s.push('\0');
|
||||
xnu::panic(s.as_str());
|
||||
loop {}
|
||||
}
|
||||
|
||||
pub struct XnuAllocator;
|
||||
|
||||
unsafe impl GlobalAlloc for XnuAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
xnu::kalloc(layout.size())
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
xnu::free(ptr, layout.size());
|
||||
}
|
||||
}
|
||||
|
||||
#[global_allocator]
|
||||
static GLOBAL: XnuAllocator = XnuAllocator;
|
||||
extern crate alloc;
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! kprintln {
|
||||
($($arg:tt)*) => {{
|
||||
use core::fmt::Write;
|
||||
let mut buf = alloc::string::String::new();
|
||||
write!(&mut buf, $($arg)*).unwrap();
|
||||
buf.push('\n');
|
||||
buf.push('\0');
|
||||
crate::xnu::io_log(&buf)
|
||||
}};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use core::arch::asm;
|
||||
|
||||
pub unsafe fn ptrauth_sign(ptr: *const u8, discriminator: usize) -> *const u8 {
|
||||
let signed: usize;
|
||||
unsafe {
|
||||
asm!(
|
||||
".inst 0xdac10020", // pacia x0, x1
|
||||
in("x0") ptr as usize,
|
||||
in("x1") discriminator,
|
||||
lateout("x0") signed,
|
||||
options(nomem, nostack),
|
||||
);
|
||||
}
|
||||
signed as *const u8
|
||||
}
|
||||
|
||||
pub unsafe fn ptrauth_strip_data(ptr: *const u8) -> *const u8 {
|
||||
let stripped: usize;
|
||||
unsafe {
|
||||
asm!(
|
||||
".inst 0xdac143e0", // xpaci x0
|
||||
in("x0") ptr as usize,
|
||||
lateout("x0") stripped,
|
||||
options(nomem, nostack),
|
||||
);
|
||||
}
|
||||
stripped as *const u8
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
use crate::bindings::{
|
||||
GPatternSpec, g_pattern_spec_free, g_pattern_spec_match_string, g_pattern_spec_new,
|
||||
};
|
||||
use crate::xnu::get_kernel_base;
|
||||
use alloc::ffi::CString;
|
||||
use core::cmp::Ordering;
|
||||
use core::ffi::{CStr, c_char};
|
||||
use core::mem::size_of;
|
||||
use core::ptr;
|
||||
|
||||
pub struct SymbolTable {
|
||||
data: &'static [u8],
|
||||
symbol_count: usize,
|
||||
}
|
||||
|
||||
impl SymbolTable {
|
||||
pub const fn empty() -> Self {
|
||||
Self {
|
||||
data: &[],
|
||||
symbol_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new(data: &'static [u8]) -> Self {
|
||||
if data.len() < 4 {
|
||||
return Self::empty();
|
||||
}
|
||||
let symbol_count = unsafe { *(data.as_ptr() as *const u32) as usize };
|
||||
Self { data, symbol_count }
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.symbol_count == 0
|
||||
}
|
||||
|
||||
pub fn symbol_count(&self) -> usize {
|
||||
self.symbol_count
|
||||
}
|
||||
|
||||
pub fn find_symbol_by_name(&self, name: &str) -> Option<SymbolRef> {
|
||||
let (_, entry) = self.binary_search_by_name(name)?;
|
||||
Some(SymbolRef {
|
||||
symbol_table: self,
|
||||
entry,
|
||||
kernel_base: get_kernel_base(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn find_symbols_by_name(&self, name: &str) -> SymbolsByNameIterator {
|
||||
let (found_index, _) = match self.binary_search_by_name(name) {
|
||||
Some(result) => result,
|
||||
None => return SymbolsByNameIterator::empty(self),
|
||||
};
|
||||
|
||||
let mut start = found_index;
|
||||
let mut end = found_index;
|
||||
|
||||
while start > 0 {
|
||||
let entry = self.get_symbol_entry_by_name_index(start - 1);
|
||||
let symbol_name = entry.name(self);
|
||||
if symbol_name == name {
|
||||
start -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
while end + 1 < self.symbol_count {
|
||||
let entry = self.get_symbol_entry_by_name_index(end + 1);
|
||||
let symbol_name = entry.name(self);
|
||||
if symbol_name == name {
|
||||
end += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
SymbolsByNameIterator {
|
||||
symbol_table: self,
|
||||
current_index: start,
|
||||
end_index: end + 1,
|
||||
kernel_base: get_kernel_base(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_symbols_matching_glob(&self, pattern: &str) -> SymbolsMatchingIterator {
|
||||
if self.is_empty() {
|
||||
return SymbolsMatchingIterator::empty(self);
|
||||
}
|
||||
|
||||
let pattern_cstr = CString::new(pattern).unwrap();
|
||||
let pspec = unsafe { g_pattern_spec_new(pattern_cstr.as_ptr()) };
|
||||
|
||||
SymbolsMatchingIterator {
|
||||
symbol_table: self,
|
||||
current_index: 0,
|
||||
end_index: self.symbol_count,
|
||||
pspec,
|
||||
kernel_base: get_kernel_base(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_symbol_by_address(&self, address: u64) -> Option<SymbolRef> {
|
||||
let target_offset = (address - get_kernel_base()) as u32;
|
||||
let (_, entry) = self.binary_search_by_address(target_offset)?;
|
||||
Some(SymbolRef {
|
||||
symbol_table: self,
|
||||
entry,
|
||||
kernel_base: get_kernel_base(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn find_symbol_name_ptr_by_address(&self, address: u64) -> *const c_char {
|
||||
let target_offset = (address - get_kernel_base()) as u32;
|
||||
if let Some((_, entry)) = self.binary_search_by_address(target_offset) {
|
||||
entry.name_ptr(self)
|
||||
} else {
|
||||
ptr::null()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_closest_symbol_by_address(&self, address: u64) -> Option<SymbolRef> {
|
||||
let kernel_base = get_kernel_base();
|
||||
let target_offset = (address - kernel_base) as u32;
|
||||
let (_, entry) = self.binary_search_closest_by_address(target_offset)?;
|
||||
Some(SymbolRef {
|
||||
symbol_table: self,
|
||||
entry,
|
||||
kernel_base,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn iter_symbols_in_range(&self, start_address: u64, end_address: u64) -> SymbolsInRangeIterator {
|
||||
if self.is_empty() {
|
||||
return SymbolsInRangeIterator {
|
||||
symbol_table: self,
|
||||
current_index: 0,
|
||||
end_index: 0,
|
||||
end_offset: 0,
|
||||
kernel_base: get_kernel_base(),
|
||||
};
|
||||
}
|
||||
|
||||
let kernel_base = get_kernel_base();
|
||||
let start_offset = (start_address - kernel_base) as u32;
|
||||
let end_offset = (end_address - kernel_base) as u32;
|
||||
|
||||
let mut left = 0;
|
||||
let mut right = self.symbol_count;
|
||||
|
||||
while left < right {
|
||||
let mid = left + (right - left) / 2;
|
||||
let entry = self.get_symbol_entry_by_address_index(mid);
|
||||
|
||||
if entry.address_offset < start_offset {
|
||||
left = mid + 1;
|
||||
} else {
|
||||
right = mid;
|
||||
}
|
||||
}
|
||||
|
||||
while left > 0 {
|
||||
let prev_entry = self.get_symbol_entry_by_address_index(left - 1);
|
||||
if prev_entry.address_offset >= start_offset {
|
||||
left -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
SymbolsInRangeIterator {
|
||||
symbol_table: self,
|
||||
current_index: left,
|
||||
end_index: self.symbol_count,
|
||||
end_offset,
|
||||
kernel_base,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_symbol_entry_by_name_index(&self, index: usize) -> &SymbolEntry {
|
||||
let offset = self.name_index_start() + index * 4;
|
||||
let symbol_offset = unsafe { *(self.data.as_ptr().add(offset) as *const u32) as usize };
|
||||
self.symbol_entry_at(symbol_offset)
|
||||
}
|
||||
|
||||
fn get_symbol_entry_by_address_index(&self, index: usize) -> &SymbolEntry {
|
||||
let offset = self.address_index_start() + index * 4;
|
||||
let symbol_offset = unsafe { *(self.data.as_ptr().add(offset) as *const u32) as usize };
|
||||
self.symbol_entry_at(symbol_offset)
|
||||
}
|
||||
|
||||
fn symbol_entry_at(&self, offset: usize) -> &SymbolEntry {
|
||||
unsafe { &*(self.data.as_ptr().add(offset) as *const SymbolEntry) }
|
||||
}
|
||||
|
||||
fn name_index_start(&self) -> usize {
|
||||
4
|
||||
}
|
||||
|
||||
fn address_index_start(&self) -> usize {
|
||||
4 + self.symbol_count * 4
|
||||
}
|
||||
|
||||
fn binary_search_by_name(&self, name: &str) -> Option<(usize, &SymbolEntry)> {
|
||||
self.binary_search(
|
||||
|table, mid| table.get_symbol_entry_by_name_index(mid),
|
||||
|entry| entry.name(self).cmp(name),
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
fn binary_search_by_address(&self, target_offset: u32) -> Option<(usize, &SymbolEntry)> {
|
||||
self.binary_search(
|
||||
|table, mid| table.get_symbol_entry_by_address_index(mid),
|
||||
|entry| entry.address_offset.cmp(&target_offset),
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
fn binary_search_closest_by_address(
|
||||
&self,
|
||||
target_offset: u32,
|
||||
) -> Option<(usize, &SymbolEntry)> {
|
||||
self.binary_search(
|
||||
|table, mid| table.get_symbol_entry_by_address_index(mid),
|
||||
|entry| entry.address_offset.cmp(&target_offset),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
fn binary_search<F, C>(
|
||||
&self,
|
||||
get_entry_fn: F,
|
||||
compare_fn: C,
|
||||
find_closest: bool,
|
||||
) -> Option<(usize, &SymbolEntry)>
|
||||
where
|
||||
F: Fn(&Self, usize) -> &SymbolEntry,
|
||||
C: Fn(&SymbolEntry) -> Ordering,
|
||||
{
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut left = 0;
|
||||
let mut right = self.symbol_count;
|
||||
let mut best_match: Option<(usize, &SymbolEntry)> = None;
|
||||
|
||||
while left < right {
|
||||
let mid = left + (right - left) / 2;
|
||||
let entry = get_entry_fn(self, mid);
|
||||
|
||||
match compare_fn(entry) {
|
||||
Ordering::Equal => return Some((mid, entry)),
|
||||
Ordering::Less => {
|
||||
if find_closest {
|
||||
best_match = Some((mid, entry));
|
||||
}
|
||||
left = mid + 1;
|
||||
}
|
||||
Ordering::Greater => right = mid,
|
||||
}
|
||||
}
|
||||
|
||||
best_match
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct SymbolEntry {
|
||||
address_offset: u32,
|
||||
symbol_type: u8,
|
||||
section: u8,
|
||||
description: u16,
|
||||
}
|
||||
|
||||
impl SymbolEntry {
|
||||
fn name<'a>(&self, symbol_table: &'a SymbolTable) -> &'a str {
|
||||
unsafe {
|
||||
CStr::from_ptr(self.name_ptr(symbol_table))
|
||||
.to_str()
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn name_ptr(&self, symbol_table: &SymbolTable) -> *const c_char {
|
||||
let entry_ptr = self as *const SymbolEntry as *const u8;
|
||||
let data_start = symbol_table.data.as_ptr();
|
||||
let entry_offset = unsafe { entry_ptr.offset_from(data_start) as usize };
|
||||
let name_start = entry_offset + size_of::<SymbolEntry>();
|
||||
|
||||
unsafe { symbol_table.data.as_ptr().add(name_start) as *const c_char }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SymbolRef<'a> {
|
||||
symbol_table: &'a SymbolTable,
|
||||
entry: &'a SymbolEntry,
|
||||
kernel_base: u64,
|
||||
}
|
||||
|
||||
impl<'a> SymbolRef<'a> {
|
||||
pub fn name(&self) -> &'a str {
|
||||
self.entry.name(self.symbol_table)
|
||||
}
|
||||
|
||||
pub fn name_ptr(&self) -> *const c_char {
|
||||
self.entry.name_ptr(self.symbol_table)
|
||||
}
|
||||
|
||||
pub fn address(&self) -> u64 {
|
||||
self.kernel_base + self.entry.address_offset as u64
|
||||
}
|
||||
|
||||
pub fn symbol_type(&self) -> u8 {
|
||||
self.entry.symbol_type
|
||||
}
|
||||
|
||||
pub fn section(&self) -> u8 {
|
||||
self.entry.section
|
||||
}
|
||||
|
||||
pub fn description(&self) -> u16 {
|
||||
self.entry.description
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SymbolsByNameIterator<'a> {
|
||||
symbol_table: &'a SymbolTable,
|
||||
current_index: usize,
|
||||
end_index: usize,
|
||||
kernel_base: u64,
|
||||
}
|
||||
|
||||
impl<'a> SymbolsByNameIterator<'a> {
|
||||
fn empty(symbol_table: &'a SymbolTable) -> Self {
|
||||
Self {
|
||||
symbol_table,
|
||||
current_index: 0,
|
||||
end_index: 0,
|
||||
kernel_base: get_kernel_base(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for SymbolsByNameIterator<'a> {
|
||||
type Item = SymbolRef<'a>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.current_index == self.end_index {
|
||||
return None;
|
||||
}
|
||||
|
||||
let entry = self.symbol_table.get_symbol_entry_by_name_index(self.current_index);
|
||||
self.current_index += 1;
|
||||
|
||||
Some(SymbolRef {
|
||||
symbol_table: self.symbol_table,
|
||||
entry,
|
||||
kernel_base: self.kernel_base,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SymbolsMatchingIterator<'a> {
|
||||
symbol_table: &'a SymbolTable,
|
||||
current_index: usize,
|
||||
end_index: usize,
|
||||
pspec: *mut GPatternSpec,
|
||||
kernel_base: u64,
|
||||
}
|
||||
|
||||
impl<'a> SymbolsMatchingIterator<'a> {
|
||||
fn empty(symbol_table: &'a SymbolTable) -> Self {
|
||||
Self {
|
||||
symbol_table,
|
||||
current_index: 0,
|
||||
end_index: 0,
|
||||
pspec: ptr::null_mut(),
|
||||
kernel_base: get_kernel_base(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for SymbolsMatchingIterator<'a> {
|
||||
type Item = SymbolRef<'a>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
while self.current_index != self.end_index {
|
||||
let entry = self.symbol_table.get_symbol_entry_by_name_index(self.current_index);
|
||||
self.current_index += 1;
|
||||
|
||||
if unsafe { g_pattern_spec_match_string(self.pspec, entry.name_ptr(self.symbol_table)) } != 0 {
|
||||
return Some(SymbolRef {
|
||||
symbol_table: self.symbol_table,
|
||||
entry,
|
||||
kernel_base: self.kernel_base,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for SymbolsMatchingIterator<'a> {
|
||||
fn drop(&mut self) {
|
||||
if !self.pspec.is_null() {
|
||||
unsafe { g_pattern_spec_free(self.pspec) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SymbolsInRangeIterator<'a> {
|
||||
symbol_table: &'a SymbolTable,
|
||||
current_index: usize,
|
||||
end_index: usize,
|
||||
end_offset: u32,
|
||||
kernel_base: u64,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for SymbolsInRangeIterator<'a> {
|
||||
type Item = SymbolRef<'a>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
while self.current_index != self.end_index {
|
||||
let entry = self.symbol_table.get_symbol_entry_by_address_index(self.current_index);
|
||||
self.current_index += 1;
|
||||
|
||||
if entry.address_offset >= self.end_offset {
|
||||
break;
|
||||
}
|
||||
|
||||
return Some(SymbolRef {
|
||||
symbol_table: self.symbol_table,
|
||||
entry,
|
||||
kernel_base: self.kernel_base,
|
||||
});
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
use core::ffi::c_void;
|
||||
use core::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static KERNEL_BASE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub fn get_kernel_base() -> u64 {
|
||||
KERNEL_BASE.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn set_kernel_base(base: u64) {
|
||||
KERNEL_BASE.store(base, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
type ContinuationFn = unsafe extern "C" fn(_parameter: *mut c_void, _wait_result: i32);
|
||||
|
||||
unsafe extern "C" {
|
||||
static _panic: unsafe extern "C" fn(*const u8);
|
||||
static _IOLog: unsafe extern "C" fn(*const u8, ...);
|
||||
static _kalloc: unsafe extern "C" fn(usize) -> *mut u8;
|
||||
static _kfree: unsafe extern "C" fn(*mut u8, usize) -> *mut u8;
|
||||
static _kernel_thread_start:
|
||||
unsafe extern "C" fn(*const (), *mut c_void, *mut *mut c_void) -> isize;
|
||||
static _assert_wait: unsafe extern "C" fn(*const u8, u32) -> i32;
|
||||
static _assert_wait_timeout: unsafe extern "C" fn(*const u8, u32, u32, u32) -> i32;
|
||||
static _thread_block: unsafe extern "C" fn(Option<ContinuationFn>) -> i32;
|
||||
static _thread_wakeup: unsafe extern "C" fn(*const u8) -> i32;
|
||||
static _mach_absolute_time: unsafe extern "C" fn() -> u64;
|
||||
static _absolutetime_to_nanoseconds: unsafe extern "C" fn(u64, *mut u64);
|
||||
static _clock_get_calendar_microtime: unsafe extern "C" fn(*mut u32, *mut u32);
|
||||
static _ml_io_map: unsafe extern "C" fn(u64, u64) -> *mut c_void;
|
||||
static _ml_vtophys: unsafe extern "C" fn(u64) -> u64;
|
||||
static __ZN9IOService11getPlatformEv: unsafe extern "C" fn() -> *mut c_void;
|
||||
static __ZN9IOServiceC2Ev: unsafe extern "C" fn(*mut core::ffi::c_void);
|
||||
static __ZN8OSSymbol17withCStringNoCopyEPKc:
|
||||
unsafe extern "C" fn(*const core::ffi::c_char) -> *const OSSymbol;
|
||||
static __ZN6OSData9withBytesEPKvj:
|
||||
unsafe extern "C" fn(*const core::ffi::c_void, u32) -> *mut OSData;
|
||||
}
|
||||
|
||||
const IO_SERVICE_VTABLE_LENGTH: isize = 168;
|
||||
|
||||
const VT_LOOKUP_IC: isize = IO_SERVICE_VTABLE_LENGTH + 25; // IOPlatformExpert
|
||||
const VT_REGISTER_INT: isize = IO_SERVICE_VTABLE_LENGTH + 0; // IOInterruptController
|
||||
const VT_ENABLE_INT: isize = IO_SERVICE_VTABLE_LENGTH + 3; // IOInterruptController
|
||||
|
||||
pub fn panic(msg: &str) {
|
||||
unsafe { _panic(msg.as_ptr()) };
|
||||
}
|
||||
|
||||
pub fn io_log(msg: &str) {
|
||||
unsafe {
|
||||
_IOLog(msg.as_ptr());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kalloc(size: usize) -> *mut u8 {
|
||||
unsafe { _kalloc(size) }
|
||||
}
|
||||
|
||||
pub fn free(ptr: *mut u8, size: usize) {
|
||||
unsafe {
|
||||
_kfree(ptr, size);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kernel_thread_start(continuation: ContinuationFn, thread_parameter: *mut c_void) -> isize {
|
||||
let mut new_thread: *mut c_void = core::ptr::null_mut();
|
||||
return unsafe {
|
||||
let ptr = crate::pac::ptrauth_sign(continuation as *const u8, 0xd507);
|
||||
_kernel_thread_start(
|
||||
core::mem::transmute(ptr),
|
||||
thread_parameter,
|
||||
&mut new_thread as *mut *mut c_void,
|
||||
)
|
||||
// TODO: Call thread_deallocate()
|
||||
};
|
||||
}
|
||||
|
||||
pub const THREAD_INTERRUPTIBLE: u32 = 1;
|
||||
pub const THREAD_WAITING: i32 = -1;
|
||||
|
||||
pub fn assert_wait(event: *const u8, interruptible: u32) -> i32 {
|
||||
unsafe { _assert_wait(event, interruptible) }
|
||||
}
|
||||
|
||||
pub fn assert_wait_timeout(
|
||||
event: *const u8,
|
||||
interruptible: u32,
|
||||
interval: u32,
|
||||
scale_factor: u32,
|
||||
) -> i32 {
|
||||
unsafe { _assert_wait_timeout(event, interruptible, interval, scale_factor) }
|
||||
}
|
||||
|
||||
pub fn thread_block(continuation: Option<ContinuationFn>) -> i32 {
|
||||
unsafe { _thread_block(continuation) }
|
||||
}
|
||||
|
||||
pub fn thread_wakeup(event: *const u8) -> i32 {
|
||||
unsafe { _thread_wakeup(event) }
|
||||
}
|
||||
|
||||
pub fn mach_absolute_time() -> u64 {
|
||||
unsafe { _mach_absolute_time() }
|
||||
}
|
||||
|
||||
pub fn absolutetime_to_nanoseconds(abstime: u64) -> u64 {
|
||||
let mut nanoseconds: u64 = 0;
|
||||
unsafe {
|
||||
_absolutetime_to_nanoseconds(abstime, &mut nanoseconds);
|
||||
}
|
||||
nanoseconds
|
||||
}
|
||||
|
||||
pub fn clock_get_calendar_microtime() -> (u32, u32) {
|
||||
let mut secs: u32 = 0;
|
||||
let mut microsecs: u32 = 0;
|
||||
unsafe {
|
||||
_clock_get_calendar_microtime(&mut secs, &mut microsecs);
|
||||
}
|
||||
(secs, microsecs)
|
||||
}
|
||||
|
||||
pub fn ml_io_map(phys_addr: u64, size: u64) -> *mut c_void {
|
||||
unsafe { _ml_io_map(phys_addr, size) }
|
||||
}
|
||||
|
||||
pub fn ml_vtophys(vaddr: u64) -> u64 {
|
||||
unsafe { _ml_vtophys(vaddr) }
|
||||
}
|
||||
|
||||
pub type IOInterruptHandler =
|
||||
extern "C" fn(target: *mut c_void, refcon: *mut c_void, nub: *mut c_void, source: i32);
|
||||
|
||||
pub fn install_interrupt_handler(
|
||||
irq: u32,
|
||||
target: *mut c_void,
|
||||
handler: IOInterruptHandler,
|
||||
refcon: *mut c_void,
|
||||
) -> i32 {
|
||||
let pe = unsafe { __ZN9IOService11getPlatformEv() };
|
||||
|
||||
let name =
|
||||
unsafe { __ZN8OSSymbol17withCStringNoCopyEPKc(c"IOInterruptController0000001A".as_ptr()) };
|
||||
|
||||
let lookup: extern "C" fn(*mut IOPlatformExpert, *mut OSSymbol) -> *mut IOInterruptController =
|
||||
vf(pe as _, VT_LOOKUP_IC);
|
||||
let ic = lookup(pe as *mut IOPlatformExpert, name as *mut OSSymbol);
|
||||
if ic.is_null() {
|
||||
panic!("Failed to lookup IOInterruptController");
|
||||
}
|
||||
|
||||
let nub = kalloc(0x88);
|
||||
unsafe {
|
||||
core::ptr::write_bytes(nub, 0, 0x88);
|
||||
__ZN9IOServiceC2Ev(nub as *mut core::ffi::c_void);
|
||||
}
|
||||
|
||||
type IOServiceInitFn = unsafe extern "C" fn(*mut c_void, *mut c_void) -> bool;
|
||||
let init_fn: IOServiceInitFn = vf(nub as *mut c_void, 21);
|
||||
unsafe { init_fn(nub as *mut c_void, core::ptr::null_mut()) };
|
||||
|
||||
let interrupt_sources =
|
||||
kalloc(core::mem::size_of::<IOInterruptSource>()) as *mut IOInterruptSource;
|
||||
|
||||
let source_bytes = irq.to_ne_bytes();
|
||||
let vector_data =
|
||||
unsafe { __ZN6OSData9withBytesEPKvj(source_bytes.as_ptr() as *const core::ffi::c_void, 4) };
|
||||
|
||||
unsafe {
|
||||
(*interrupt_sources).interrupt_controller = ic;
|
||||
(*interrupt_sources).vector_data = vector_data;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let interrupt_sources_ptr = (nub as *mut u8).offset(0x80) as *mut *mut IOInterruptSource;
|
||||
*interrupt_sources_ptr = interrupt_sources;
|
||||
}
|
||||
|
||||
let reg: extern "C" fn(
|
||||
*mut _,
|
||||
*mut c_void,
|
||||
i32,
|
||||
*mut c_void,
|
||||
IOInterruptHandler,
|
||||
*mut c_void,
|
||||
) -> i32 = vf(ic as _, VT_REGISTER_INT);
|
||||
|
||||
let signed_handler = unsafe {
|
||||
let handler_ptr = crate::pac::ptrauth_sign(handler as *const u8, 0xd36);
|
||||
core::mem::transmute::<*const u8, IOInterruptHandler>(handler_ptr)
|
||||
};
|
||||
|
||||
let kr = reg(ic, nub as *mut c_void, 0, target, signed_handler, refcon);
|
||||
if kr != 0 {
|
||||
return kr;
|
||||
}
|
||||
|
||||
let en: extern "C" fn(*mut _, *mut c_void, i32) -> i32 = vf(ic as _, VT_ENABLE_INT);
|
||||
en(ic, nub as *mut c_void, 0)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct IOPlatformExpert {
|
||||
_p: [u8; 0],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct IOInterruptController {
|
||||
_p: [u8; 0],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct OSSymbol {
|
||||
_p: [u8; 0],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct OSData {
|
||||
_p: [u8; 0],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct IOInterruptSource {
|
||||
interrupt_controller: *mut IOInterruptController,
|
||||
vector_data: *mut OSData,
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn vf<T>(obj: *mut c_void, slot: isize) -> T
|
||||
where
|
||||
T: Copy,
|
||||
{
|
||||
let vtable_ptr = unsafe { *(obj as *const *const usize) };
|
||||
let vtable = unsafe { crate::pac::ptrauth_strip_data(vtable_ptr as *const u8) as *const usize };
|
||||
let entry = unsafe { *vtable.offset(slot) };
|
||||
let entry_ptr = unsafe { crate::pac::ptrauth_strip_data(entry as *const u8) };
|
||||
unsafe { core::mem::transmute_copy::<*const u8, T>(&entry_ptr) }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
|
||||
QEMUAppleSilicon/build/qemu-system-aarch64 \
|
||||
-M t8030,memory-backend=ram,trustcache=iPhone11_8_iPhone12_1_14.0_18A5351d_Restore/Firmware/038-44135-124.dmg.trustcache,ticket=root_ticket.der,sep-fw=sep-firmware.n104.RELEASE.new.img4,sep-rom=AppleSEPROM-Cebu-B1,kaslr-off=true,usb-conn-type=unix,usb-conn-addr=/Users/oleavr/src/frida-barebone-ios/usb.socket \
|
||||
-object memory-backend-file,id=ram,size=4G,mem-path="/Volumes/RAM Disk/ios-dram",share=on \
|
||||
-kernel iPhone11_8_iPhone12_1_14.0_18A5351d_Restore/kernelcache.research.iphone12b \
|
||||
-dtb iPhone11_8_iPhone12_1_14.0_18A5351d_Restore/Firmware/all_flash/DeviceTree.n104ap.im4p \
|
||||
-append "tlto_us=-1 mtxspin=-1 agm-genuine=1 agm-authentic=1 agm-trusted=1 serial=3 launchd_unsecure_cache=1 wdt=-1" \
|
||||
-smp 7 \
|
||||
-drive file=sep_nvram,if=pflash,format=qcow2 \
|
||||
-drive file=sep_ssc,if=pflash,format=qcow2 \
|
||||
-drive file=nvme.1,format=qcow2,if=none,id=drive.1 -device nvme-ns,drive=drive.1,bus=nvme-bus.0,nsid=1,nstype=1,logical_block_size=4096,physical_block_size=4096 \
|
||||
-drive file=nvme.2,format=qcow2,if=none,id=drive.2 -device nvme-ns,drive=drive.2,bus=nvme-bus.0,nsid=2,nstype=2,logical_block_size=4096,physical_block_size=4096 \
|
||||
-drive file=nvme.3,format=qcow2,if=none,id=drive.3 -device nvme-ns,drive=drive.3,bus=nvme-bus.0,nsid=3,nstype=3,logical_block_size=4096,physical_block_size=4096 \
|
||||
-drive file=nvme.4,format=qcow2,if=none,id=drive.4 -device nvme-ns,drive=drive.4,bus=nvme-bus.0,nsid=4,nstype=4,logical_block_size=4096,physical_block_size=4096 \
|
||||
-drive file=nvram,if=none,format=qcow2,id=nvram -device apple-nvram,drive=nvram,bus=nvme-bus.0,nsid=5,nstype=5,id=nvram,logical_block_size=4096,physical_block_size=4096 \
|
||||
-drive file=nvme.6,format=qcow2,if=none,id=drive.6 -device nvme-ns,drive=drive.6,bus=nvme-bus.0,nsid=6,nstype=6,logical_block_size=4096,physical_block_size=4096 \
|
||||
-drive file=nvme.7,format=qcow2,if=none,id=drive.7 -device nvme-ns,drive=drive.7,bus=nvme-bus.0,nsid=7,nstype=8,logical_block_size=4096,physical_block_size=4096 \
|
||||
-initrd iPhone11_8_iPhone12_1_14.0_18A5351d_Restore/038-44135-124.dmg \
|
||||
-serial mon:stdio \
|
||||
-monitor tcp:127.0.0.1:9001,server,nowait \
|
||||
-gdb tcp::9000
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
||||
<dict ID="0">
|
||||
<key>IOPlatformInterruptController</key>
|
||||
<string ID="1">IOCPUInterruptController is not serializable</string>
|
||||
|
||||
<key>IOInterruptController0000001A</key>
|
||||
<string ID="2">AppleInterruptController is not serializable</string>
|
||||
|
||||
<key>IOInterruptController00000048</key>
|
||||
<string ID="3">AppleS5L8960XGPIOIC is not serializable</string>
|
||||
|
||||
<key>IOInterruptController00000047</key>
|
||||
<string ID="4">AppleS5L8960XGPIOIC is not serializable</string>
|
||||
|
||||
<key>IOInterruptController00000023</key>
|
||||
<string ID="5">AppleS5L8960XGPIOIC is not serializable</string>
|
||||
|
||||
<key>IOInterruptController00000049</key>
|
||||
<string ID="6">AppleS5L8960XGPIOIC is not serializable</string>
|
||||
|
||||
<key>IOInterruptController0000008B</key>
|
||||
<string ID="7">AppleT8015SPMIController is not serializable</string>
|
||||
|
||||
<key>IOInterruptController00000084</key>
|
||||
<string ID="8">AppleT8015SPMIController is not serializable</string>
|
||||
|
||||
<key>ApplePCIEMSIController-apcie</key>
|
||||
<string ID="9">ApplePCIEMSIController is not serializable</string>
|
||||
|
||||
<key>AppleEmbeddedPCIEPort2</key>
|
||||
<string ID="10">AppleT8030PCIePort is not serializable</string>
|
||||
|
||||
<key>AppleEmbeddedPCIEPort3</key>
|
||||
<string ID="11">AppleT8030PCIePort is not serializable</string>
|
||||
|
||||
<key>IOInterruptController00000087</key>
|
||||
<string ID="12">AppleT8015SPMIController is not serializable</string>
|
||||
|
||||
<key>IOInterruptController0000005F</key>
|
||||
<string ID="13">AppleSMCPMU is not serializable</string>
|
||||
</dict>
|
||||
@@ -0,0 +1,33 @@
|
||||
const osSerialize_withCapacity = new NativeFunction(ptr('0xfffffff007fbf074'), 'pointer', ['uint']);
|
||||
|
||||
const UNPAC_MASK = ptr('0xfffffff000000000');
|
||||
|
||||
const serializer = osSerialize_withCapacity(4096);
|
||||
|
||||
const gIOInterruptControllers = ptr('0xfffffff009a3f090').readPointer();
|
||||
|
||||
const serialize = new NativeFunction(implFor(6, vtableOf(gIOInterruptControllers)), 'uint' /* 'bool' */, ['pointer', 'pointer']);
|
||||
console.log('serialize() is at:', serialize.handle);
|
||||
const result = serialize(gIOInterruptControllers, serializer);
|
||||
console.log('result returned:', result);
|
||||
|
||||
const getText = new NativeFunction(implFor(15, vtableOf(serializer)), 'pointer', ['pointer']);
|
||||
const text = getText(serializer);
|
||||
console.log('Got text:', text.readUtf8String(text));
|
||||
|
||||
const release = new NativeFunction(implFor(5, vtableOf(serializer)), 'void', ['pointer']);
|
||||
release(serializer);
|
||||
|
||||
Object.assign(globalThis, { osSerialize_withCapacity });
|
||||
|
||||
function implFor(n, vtable) {
|
||||
return unpac(vtable.add(n * Process.pointerSize).readPointer());
|
||||
}
|
||||
|
||||
function vtableOf(instance) {
|
||||
return unpac(instance.readPointer());
|
||||
}
|
||||
|
||||
function unpac(p) {
|
||||
return p.or(UNPAC_MASK);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import os
|
||||
import r2pipe
|
||||
|
||||
def scan_files_for_pattern(directory, hex_pattern, file_extension=None):
|
||||
search_command = "/xj " + hex_pattern.strip()
|
||||
|
||||
for root, _, files in os.walk(directory):
|
||||
for filename in files:
|
||||
if file_extension and not filename.endswith(file_extension):
|
||||
continue
|
||||
|
||||
file_path = os.path.join(root, filename)
|
||||
try:
|
||||
r2 = r2pipe.open(file_path, flags=["-n"])
|
||||
r2.cmd("e io.cache=true")
|
||||
|
||||
result = r2.cmdj(search_command)
|
||||
|
||||
if result:
|
||||
print(f"Found in {file_path}:")
|
||||
for match in result:
|
||||
print(f" - Offset: 0x{match['offset']:x}")
|
||||
|
||||
r2.quit()
|
||||
except Exception as e:
|
||||
print(f" Error processing {file_path}: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="Scan dump files for a hex pattern using r2pipe.")
|
||||
parser.add_argument("directory", help="Directory containing dump files")
|
||||
parser.add_argument("pattern", help="Hex pattern to search (e.g. 'ff ff ff ff')")
|
||||
parser.add_argument("--ext", help="Only scan files with this extension", default=None)
|
||||
|
||||
args = parser.parse_args()
|
||||
scan_files_for_pattern(args.directory, args.pattern, args.ext)
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Symbolicate panic backtrace from kernel log")
|
||||
parser.add_argument("--log-file", type=argparse.FileType("r"), required=True,
|
||||
help="Path to the kernel log file")
|
||||
parser.add_argument("--elf-file", type=str, required=True,
|
||||
help="Path to the ELF file for symbolication")
|
||||
parser.add_argument("--base-address", type=lambda x: int(x, 16), required=True,
|
||||
help="Base address where the ELF was loaded (e.g., 0xffffffe8195f0000)")
|
||||
parser.add_argument("--verbose", "-v", action="store_true",
|
||||
help="Show all backtrace frames, not just symbolicated ones")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
log_content = args.log_file.read()
|
||||
args.log_file.close()
|
||||
|
||||
frames = find_last_panic(log_content)
|
||||
if not frames:
|
||||
print("No panic found in the log file", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"Found last panic with {len(frames)} backtrace frames")
|
||||
print(f"ELF base address: 0x{args.base_address:x}")
|
||||
print(f"ELF file: {args.elf_file}")
|
||||
print()
|
||||
|
||||
symbolicated_count = 0
|
||||
|
||||
for i, (lr_str, fp_str) in enumerate(frames):
|
||||
lr_addr = int(lr_str, 16)
|
||||
#fp_addr = int(fp_str, 16)
|
||||
|
||||
if lr_addr >= args.base_address:
|
||||
function, location = symbolicate_address(args.elf_file, lr_addr, args.base_address)
|
||||
offset = lr_addr - args.base_address
|
||||
|
||||
print(f"Frame {i:2d}: lr: {lr_str} (offset: 0x{offset:x}) fp: {fp_str}")
|
||||
|
||||
# Color the function name based on resolution status
|
||||
if function == "<unknown>":
|
||||
colored_function = Colors.bold_yellow(function)
|
||||
elif function == "<error>":
|
||||
colored_function = Colors.bold_red(function)
|
||||
else:
|
||||
colored_function = Colors.bold_green(function)
|
||||
|
||||
print(f" -> {colored_function}")
|
||||
print(f" {location}")
|
||||
print()
|
||||
symbolicated_count += 1
|
||||
elif args.verbose:
|
||||
print(f"Frame {i:2d}: lr: {lr_str} fp: {fp_str} (outside ELF range)")
|
||||
|
||||
if symbolicated_count == 0:
|
||||
print("No addresses found within the ELF address range")
|
||||
if not args.verbose:
|
||||
print("Use --verbose to see all frames")
|
||||
else:
|
||||
print(f"Symbolicated {symbolicated_count} frame(s)")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def find_last_panic(log_content: str):
|
||||
panic_pattern = re.compile(
|
||||
r"panic\(.*?\n.*?Panicked thread:.*?\n((?:\s*lr:\s*0x[0-9a-fA-F]+\s*fp:\s*0x[0-9a-fA-F]+\n)*)",
|
||||
re.DOTALL
|
||||
)
|
||||
|
||||
panics = list(panic_pattern.finditer(log_content))
|
||||
|
||||
if not panics:
|
||||
return None
|
||||
|
||||
last_panic = panics[-1]
|
||||
backtrace_section = last_panic.group(1)
|
||||
|
||||
lr_fp_pattern = re.compile(r"lr:\s*(0x[0-9a-fA-F]+)\s*fp:\s*(0x[0-9a-fA-F]+)")
|
||||
frames = lr_fp_pattern.findall(backtrace_section)
|
||||
|
||||
return frames
|
||||
|
||||
|
||||
def symbolicate_address(elf_path: str, address: int, base_address: int):
|
||||
try:
|
||||
offset = address - base_address
|
||||
|
||||
result = subprocess.run([
|
||||
"aarch64-none-elf-addr2line", "-e", elf_path, "-f", "-C", f"0x{offset:x}"
|
||||
], capture_output=True, text=True, check=True)
|
||||
|
||||
lines = result.stdout.strip().split("\n")
|
||||
if len(lines) >= 2:
|
||||
function = lines[0]
|
||||
location = lines[1]
|
||||
|
||||
if function == "??":
|
||||
function = "<unknown>"
|
||||
if location == "??:0" or location == "??:?":
|
||||
location = "<unknown>"
|
||||
|
||||
return function, location
|
||||
else:
|
||||
return "<unknown>", "<unknown>"
|
||||
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
return "<error>", "<error>"
|
||||
|
||||
|
||||
class Colors:
|
||||
BOLD = "\033[1m"
|
||||
GREEN = "\033[32m"
|
||||
YELLOW = "\033[33m"
|
||||
RED = "\033[31m"
|
||||
RESET = "\033[0m"
|
||||
|
||||
@staticmethod
|
||||
def bold_green(text: str):
|
||||
return f"{Colors.BOLD}{Colors.GREEN}{text}{Colors.RESET}"
|
||||
|
||||
@staticmethod
|
||||
def bold_yellow(text: str):
|
||||
return f"{Colors.BOLD}{Colors.YELLOW}{text}{Colors.RESET}"
|
||||
|
||||
@staticmethod
|
||||
def bold_red(text: str):
|
||||
return f"{Colors.BOLD}{Colors.RED}{text}{Colors.RESET}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+104
-24
@@ -14,59 +14,83 @@ namespace Frida.Barebone {
|
||||
get;
|
||||
}
|
||||
|
||||
public abstract size_t size {
|
||||
get;
|
||||
}
|
||||
|
||||
public abstract async void deallocate (Cancellable? cancellable) throws Error, IOError;
|
||||
}
|
||||
|
||||
public class SimpleAllocator : Object, Allocator {
|
||||
public sealed class NullAllocator : Object, Allocator {
|
||||
public size_t page_size {
|
||||
get { return _page_size; }
|
||||
get {
|
||||
return _page_size;
|
||||
}
|
||||
}
|
||||
|
||||
private size_t _page_size;
|
||||
|
||||
public NullAllocator (size_t page_size) {
|
||||
this._page_size = page_size;
|
||||
}
|
||||
|
||||
public async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable) throws Error, IOError {
|
||||
throw new Error.NOT_SUPPORTED ("To enable this feature, specify an allocator in your FRIDA_BAREBONE_CONFIG");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PhysicalAllocator : Object, Allocator {
|
||||
public size_t page_size {
|
||||
get {
|
||||
return _page_size;
|
||||
}
|
||||
}
|
||||
|
||||
private Machine machine;
|
||||
private size_t _page_size;
|
||||
private uint64 base_pa;
|
||||
|
||||
private uint64 cursor;
|
||||
|
||||
public SimpleAllocator (Machine machine, size_t page_size, uint64 base_pa) {
|
||||
public PhysicalAllocator (Machine machine, size_t page_size, PhysicalAllocatorConfig config) {
|
||||
this.machine = machine;
|
||||
this._page_size = page_size;
|
||||
this.base_pa = base_pa;
|
||||
this.cursor = base_pa;
|
||||
this.cursor = config.physical_base.address;
|
||||
}
|
||||
|
||||
public async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable) throws Error, IOError {
|
||||
if (base_pa == 0) {
|
||||
uint64 example_base;
|
||||
if ("corellium" in machine.gdb.features)
|
||||
example_base = 0x0800000000 + ((2048 - 3) * 1024 * 1024);
|
||||
else
|
||||
example_base = 0x0040000000 + (128 * 1024 * 1024);
|
||||
throw new Error.NOT_SUPPORTED ("To enable this feature, set FRIDA_BAREBONE_HEAP_BASE to the physical " +
|
||||
"base address to use, e.g. 0x%" + uint64.FORMAT_MODIFIER + "x", example_base);
|
||||
}
|
||||
|
||||
uint64 address_pa = cursor;
|
||||
|
||||
size_t vm_size = round_size_up (size, page_size);
|
||||
size_t vm_size = round_size_up (size, _page_size);
|
||||
cursor += vm_size;
|
||||
|
||||
uint num_pages = (uint) (vm_size / page_size);
|
||||
uint num_pages = (uint) (vm_size / _page_size);
|
||||
|
||||
Allocation page_allocation = yield machine.allocate_pages (address_pa, num_pages, cancellable);
|
||||
var physical_addresses = new Gee.ArrayList<uint64?> ();
|
||||
for (uint i = 0; i != num_pages; i++)
|
||||
physical_addresses.add (address_pa + (i * _page_size));
|
||||
|
||||
return new SimpleAllocation (page_allocation);
|
||||
Allocation page_allocation = yield machine.allocate_pages (physical_addresses, cancellable);
|
||||
|
||||
return new PhysicalAllocation (page_allocation);
|
||||
}
|
||||
|
||||
private class SimpleAllocation : Object, Allocation {
|
||||
private class PhysicalAllocation : Object, Allocation {
|
||||
public uint64 virtual_address {
|
||||
get { return page_allocation.virtual_address; }
|
||||
get {
|
||||
return page_allocation.virtual_address;
|
||||
}
|
||||
}
|
||||
|
||||
public size_t size {
|
||||
get {
|
||||
return page_allocation.size;
|
||||
}
|
||||
}
|
||||
|
||||
private Allocation page_allocation;
|
||||
|
||||
public SimpleAllocation (Allocation page_allocation) {
|
||||
this.page_allocation = page_allocation;
|
||||
public PhysicalAllocation (Allocation allocation) {
|
||||
page_allocation = allocation;
|
||||
}
|
||||
|
||||
public async void deallocate (Cancellable? cancellable) throws Error, IOError {
|
||||
@@ -75,4 +99,60 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TargetFunctionsAllocator : Object, Allocator {
|
||||
public size_t page_size {
|
||||
get {
|
||||
return _page_size;
|
||||
}
|
||||
}
|
||||
|
||||
private Machine machine;
|
||||
private size_t _page_size;
|
||||
private TargetFunctionsAllocatorConfig config;
|
||||
|
||||
public TargetFunctionsAllocator (Machine machine, size_t page_size, TargetFunctionsAllocatorConfig config) {
|
||||
this.machine = machine;
|
||||
this._page_size = page_size;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable) throws Error, IOError {
|
||||
uint64 address = yield machine.invoke (config.alloc_function.address, { size }, cancellable);
|
||||
|
||||
// TODO: Handle alignment.
|
||||
|
||||
return new TargetAllocation (address, size, machine, config);
|
||||
}
|
||||
|
||||
private class TargetAllocation : Object, Allocation {
|
||||
public uint64 virtual_address {
|
||||
get {
|
||||
return _virtual_address;
|
||||
}
|
||||
}
|
||||
|
||||
public size_t size {
|
||||
get {
|
||||
return _size;
|
||||
}
|
||||
}
|
||||
|
||||
private uint64 _virtual_address;
|
||||
public size_t _size;
|
||||
private Machine machine;
|
||||
private TargetFunctionsAllocatorConfig config;
|
||||
|
||||
public TargetAllocation (uint64 address, size_t size, Machine m, TargetFunctionsAllocatorConfig c) {
|
||||
_virtual_address = address;
|
||||
_size = size;
|
||||
machine = m;
|
||||
config = c;
|
||||
}
|
||||
|
||||
public async void deallocate (Cancellable? cancellable) throws Error, IOError {
|
||||
yield machine.invoke (config.free_function.address, { _virtual_address, size }, cancellable);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public class ArmMachine : Object, Machine {
|
||||
public sealed class ArmMachine : Object, Machine {
|
||||
public override GDB.Client gdb {
|
||||
get;
|
||||
set;
|
||||
@@ -26,16 +26,25 @@ namespace Frida.Barebone {
|
||||
return 4096;
|
||||
}
|
||||
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async void enumerate_ranges (Gum.PageProtection prot, FoundRangeFunc func, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async Allocation allocate_pages (uint64 physical_address, uint num_pages, Cancellable? cancellable)
|
||||
public async Allocation allocate_pages (Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async void protect_pages (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async Gee.List<uint64?> scan_ranges (Gee.List<Gum.MemoryRange?> ranges, MatchPattern pattern, uint max_matches,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
@@ -45,8 +54,7 @@ namespace Frida.Barebone {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, uint64 landing_zone, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public class Arm64Machine : Object, Machine {
|
||||
public sealed class Arm64Machine : Object, Machine {
|
||||
public override GDB.Client gdb {
|
||||
get;
|
||||
set;
|
||||
@@ -25,6 +25,13 @@ namespace Frida.Barebone {
|
||||
private const uint64 INT6_MASK = 0x3fULL;
|
||||
private const uint64 INT48_MASK = 0xffffffffffffULL;
|
||||
|
||||
private const uint64 TABLE_PXN_BIT = 1ULL << 59;
|
||||
|
||||
private const uint64 UXN_BIT = 1ULL << 54;
|
||||
private const uint64 PXN_BIT = 1ULL << 53;
|
||||
private const uint64 AP1_BIT = 1ULL << 7;
|
||||
private const uint64 AP0_BIT = 1ULL << 6;
|
||||
|
||||
public Arm64Machine (GDB.Client gdb) {
|
||||
Object (gdb: gdb);
|
||||
}
|
||||
@@ -35,6 +42,17 @@ namespace Frida.Barebone {
|
||||
return p.granule;
|
||||
}
|
||||
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Error, IOError {
|
||||
GDB.Exception? exception = gdb.exception;
|
||||
if (exception == null)
|
||||
throw new Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
GDB.Thread thread = exception.thread;
|
||||
|
||||
var cpsr = yield thread.read_register ("cpsr", cancellable);
|
||||
|
||||
return (uint) ((cpsr >> 2) & 3);
|
||||
}
|
||||
|
||||
public async void enumerate_ranges (Gum.PageProtection prot, FoundRangeFunc func, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
Gee.List<RangeDetails> ranges = ("corellium" in gdb.features)
|
||||
@@ -55,7 +73,7 @@ namespace Frida.Barebone {
|
||||
|
||||
yield set_addressing_mode (gdb, PHYSICAL, cancellable);
|
||||
try {
|
||||
yield collect_ranges_in_table (p.tt1, p.first_level, p.upper_bits, p.granule, result, cancellable);
|
||||
yield collect_ranges_in_table (p.tt1, p.first_level, p.upper_bits, p, result, cancellable);
|
||||
} finally {
|
||||
set_addressing_mode.begin (gdb, VIRTUAL, null);
|
||||
}
|
||||
@@ -63,30 +81,30 @@ namespace Frida.Barebone {
|
||||
return result;
|
||||
}
|
||||
|
||||
private async void collect_ranges_in_table (uint64 table_address, uint level, uint64 upper_bits, Granule granule,
|
||||
private async void collect_ranges_in_table (uint64 table_address, uint level, uint64 upper_bits, MMUParameters p,
|
||||
Gee.List<RangeDetails> ranges, Cancellable? cancellable) throws Error, IOError {
|
||||
uint max_entries = compute_max_entries (level, granule);
|
||||
uint max_entries = compute_max_entries (level, p);
|
||||
Buffer entries = yield gdb.read_buffer (table_address, max_entries * Descriptor.SIZE, cancellable);
|
||||
uint shift = address_shift_at_level (level, granule);
|
||||
uint shift = address_shift_at_level (level, p.granule);
|
||||
for (uint i = 0; i != max_entries; i++) {
|
||||
uint64 raw_descriptor = entries.read_uint64 (i * Descriptor.SIZE);
|
||||
|
||||
Descriptor desc = Descriptor.parse (raw_descriptor, level, granule);
|
||||
Descriptor desc = Descriptor.parse (raw_descriptor, level, p.granule);
|
||||
if (desc.kind == INVALID)
|
||||
continue;
|
||||
|
||||
uint64 address = upper_bits | ((uint64) i << shift);
|
||||
|
||||
if (desc.kind == BLOCK) {
|
||||
size_t size = 1 << num_block_bits_at_level (level, granule);
|
||||
Gum.PageProtection prot = protection_from_flags (desc.flags);
|
||||
size_t size = 1 << num_block_bits_at_level (level, p.granule);
|
||||
Gum.PageProtection prot = protection_from_flags (desc.flags, p);
|
||||
|
||||
ranges.add (new RangeDetails (address, desc.target_address, size, prot, MappingType.UNKNOWN));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
yield collect_ranges_in_table (desc.target_address, level + 1, address, granule, ranges, cancellable);
|
||||
yield collect_ranges_in_table (desc.target_address, level + 1, address, p, ranges, cancellable);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,33 +163,35 @@ namespace Frida.Barebone {
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Allocation allocate_pages (uint64 physical_address, uint num_pages, Cancellable? cancellable)
|
||||
public async Allocation allocate_pages (Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
MMUParameters p = yield MMUParameters.load (gdb, cancellable);
|
||||
|
||||
yield set_addressing_mode (gdb, PHYSICAL, cancellable);
|
||||
try {
|
||||
Allocation? allocation = yield maybe_insert_descriptor_in_table (physical_address, num_pages, p.tt1,
|
||||
p.first_level, p.upper_bits, p.granule, cancellable);
|
||||
Allocation? allocation = yield maybe_insert_descriptor_in_table (physical_addresses, p.tt1, p.first_level,
|
||||
p.upper_bits, p, cancellable);
|
||||
if (allocation == null)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to insert page table mapping; please file a bug");
|
||||
|
||||
return allocation;
|
||||
} finally {
|
||||
set_addressing_mode.begin (gdb, VIRTUAL, null);
|
||||
}
|
||||
}
|
||||
|
||||
private async Allocation? maybe_insert_descriptor_in_table (uint64 physical_address, uint num_pages,
|
||||
uint64 table_address, uint level, uint64 upper_bits, Granule granule, Cancellable? cancellable)
|
||||
private async Allocation? maybe_insert_descriptor_in_table (Gee.List<uint64?> physical_addresses,
|
||||
uint64 table_address, uint level, uint64 upper_bits, MMUParameters p, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
uint max_entries = compute_max_entries (level, granule);
|
||||
uint shift = address_shift_at_level (level, granule);
|
||||
uint max_entries = compute_max_entries (level, p);
|
||||
uint shift = address_shift_at_level (level, p.granule);
|
||||
|
||||
uint64 first_available_va = 0;
|
||||
uint64 first_available_slot = 0;
|
||||
uint num_available_slots = 0;
|
||||
uint chunk_max_size = (level < 3) ? 4 : 64;
|
||||
uint chunk_offset = 0;
|
||||
uint num_pages = physical_addresses.size;
|
||||
while (chunk_offset != max_entries && num_available_slots != num_pages) {
|
||||
uint64 chunk_base_address = table_address + (chunk_offset * Descriptor.SIZE);
|
||||
uint chunk_size = uint.min (chunk_max_size, max_entries - chunk_offset);
|
||||
@@ -184,13 +204,15 @@ namespace Frida.Barebone {
|
||||
uint table_index = chunk_offset + i;
|
||||
uint64 address = upper_bits | ((uint64) table_index << shift);
|
||||
|
||||
Descriptor desc = Descriptor.parse (raw_descriptor, level, granule);
|
||||
Descriptor desc = Descriptor.parse (raw_descriptor, level, p.granule);
|
||||
|
||||
if (level < 3) {
|
||||
if (desc.kind != TABLE)
|
||||
continue;
|
||||
Allocation? allocation = yield maybe_insert_descriptor_in_table (physical_address,
|
||||
num_pages, desc.target_address, level + 1, address, granule, cancellable);
|
||||
if ((desc.flags & DescriptorFlags.PXNTABLE) != 0)
|
||||
continue;
|
||||
Allocation? allocation = yield maybe_insert_descriptor_in_table (physical_addresses,
|
||||
desc.target_address, level + 1, address, p, cancellable);
|
||||
if (allocation != null)
|
||||
return allocation;
|
||||
continue;
|
||||
@@ -215,26 +237,205 @@ namespace Frida.Barebone {
|
||||
if (num_available_slots != num_pages)
|
||||
return null;
|
||||
|
||||
Gum.PageProtection page_prot = Gum.PageProtection.READ | Gum.PageProtection.WRITE;
|
||||
if (!p.sprr_enabled)
|
||||
page_prot |= Gum.PageProtection.EXECUTE;
|
||||
|
||||
var builder = gdb.make_buffer_builder ();
|
||||
for (uint i = 0; i != num_available_slots; i++) {
|
||||
uint64 cur_physical_address = physical_address + (i * granule);
|
||||
uint64 new_descriptor = cur_physical_address | 0x40000000000403ULL;
|
||||
uint64 base_descriptor = physical_addresses[(int) i] | 0x403ULL;
|
||||
uint64 new_descriptor = apply_protection_bits (base_descriptor, page_prot, p);
|
||||
builder.append_uint64 (new_descriptor);
|
||||
}
|
||||
Bytes new_descriptors = builder.build ();
|
||||
Bytes old_descriptors = yield gdb.read_byte_array (first_available_slot, new_descriptors.get_size (), cancellable);
|
||||
yield gdb.write_byte_array (first_available_slot, new_descriptors, cancellable);
|
||||
|
||||
return new DescriptorAllocation (first_available_va, first_available_slot, old_descriptors, gdb);
|
||||
size_t size = num_pages * p.granule;
|
||||
return new DescriptorAllocation (first_available_va, size, first_available_slot, old_descriptors, gdb);
|
||||
}
|
||||
|
||||
public async void protect_pages (uint64 virtual_address, size_t size, Gum.PageProtection prot, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
MMUParameters p = yield MMUParameters.load (gdb, cancellable);
|
||||
|
||||
yield set_addressing_mode (gdb, PHYSICAL, cancellable);
|
||||
try {
|
||||
uint64 page_mask = p.granule - 1;
|
||||
uint64 aligned_va = virtual_address & ~page_mask;
|
||||
uint64 aligned_end = (virtual_address + size + page_mask) & ~page_mask;
|
||||
uint num_pages = (uint) ((aligned_end - aligned_va) / p.granule);
|
||||
|
||||
yield perform_protect_pages (aligned_va, num_pages, prot, p, cancellable);
|
||||
} finally {
|
||||
set_addressing_mode.begin (gdb, VIRTUAL, null);
|
||||
}
|
||||
}
|
||||
|
||||
private async void perform_protect_pages (uint64 start_va, uint num_pages, Gum.PageProtection prot, MMUParameters p,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
var table_cache = new TableWalkCache ();
|
||||
uint pages_processed = 0;
|
||||
|
||||
var processed_tables = new Gee.HashSet<uint64?> (Numeric.uint64_hash, Numeric.uint64_equal);
|
||||
bool need_exec = (prot & Gum.PageProtection.EXECUTE) != 0;
|
||||
|
||||
while (pages_processed != num_pages) {
|
||||
uint64 current_va = start_va + (uint64) pages_processed * p.granule;
|
||||
|
||||
uint64 table_pa = yield find_level3_table (current_va, p, table_cache, cancellable);
|
||||
|
||||
if (need_exec && !processed_tables.contains (table_pa)) {
|
||||
yield clear_pxn_table_bits_for_va (current_va, p, table_cache, cancellable);
|
||||
processed_tables.add (table_pa);
|
||||
}
|
||||
|
||||
uint level3_shift = address_shift_at_level (3, p.granule);
|
||||
uint64 level3_mask = (1ULL << level3_shift) - 1;
|
||||
uint64 table_base_va = current_va & ~level3_mask;
|
||||
uint64 table_end_va = table_base_va + (1ULL << level3_shift);
|
||||
uint64 remaining_va = start_va + num_pages * p.granule;
|
||||
uint64 batch_end_va = uint64.min (remaining_va, table_end_va);
|
||||
uint batch_size = (uint) ((batch_end_va - current_va) / p.granule);
|
||||
|
||||
yield protect_pages_in_table (current_va, batch_size, prot, table_pa, p, cancellable);
|
||||
|
||||
pages_processed += batch_size;
|
||||
}
|
||||
}
|
||||
|
||||
private async void protect_pages_in_table (uint64 current_va, uint batch_size, Gum.PageProtection prot,
|
||||
uint64 table_pa, MMUParameters p, Cancellable? cancellable) throws Error, IOError {
|
||||
uint index_bits = num_address_bits_at_level (3, p);
|
||||
uint index_shift = inpage_bits_for_granule (p.granule);
|
||||
uint index_mask = (1U << index_bits) - 1;
|
||||
|
||||
uint64 first_index = (current_va >> index_shift) & index_mask;
|
||||
uint64 first_slot_pa = table_pa + (first_index * Descriptor.SIZE);
|
||||
|
||||
Buffer descriptors = yield gdb.read_buffer (first_slot_pa, batch_size * Descriptor.SIZE, cancellable);
|
||||
|
||||
bool any_changed = false;
|
||||
for (uint i = 0; i != batch_size; i++) {
|
||||
uint64 raw_desc = descriptors.read_uint64 (i * Descriptor.SIZE);
|
||||
uint64 new_desc = apply_protection_bits (raw_desc, prot, p);
|
||||
|
||||
if (new_desc != raw_desc) {
|
||||
descriptors.write_uint64 (i * Descriptor.SIZE, new_desc);
|
||||
any_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (any_changed)
|
||||
yield gdb.write_byte_array (first_slot_pa, descriptors.bytes, cancellable);
|
||||
}
|
||||
|
||||
private async uint64 find_level3_table (uint64 va, MMUParameters p, TableWalkCache cache, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
TableWalkResult? cached = cache.lookup (va, p);
|
||||
if (cached != null)
|
||||
return yield walk_to_level3 (va, cached.table_pa, cached.level, p, cache, cancellable);
|
||||
|
||||
return yield walk_to_level3 (va, p.tt1, p.first_level, p, cache, cancellable);
|
||||
}
|
||||
|
||||
private async uint64 walk_to_level3 (uint64 va, uint64 start_table_pa, uint start_level, MMUParameters p,
|
||||
TableWalkCache cache, Cancellable? cancellable) throws Error, IOError {
|
||||
uint64 table_pa = start_table_pa;
|
||||
uint level = start_level;
|
||||
|
||||
while (level != 3) {
|
||||
cache.store (va, level, table_pa, p);
|
||||
|
||||
uint shift = address_shift_at_level (level, p.granule);
|
||||
uint entries = compute_max_entries (level, p);
|
||||
uint index = (uint) ((va >> shift) & (entries - 1));
|
||||
uint64 slot_pa = table_pa + ((uint64) index * Descriptor.SIZE);
|
||||
|
||||
Buffer d_buf = yield gdb.read_buffer (slot_pa, Descriptor.SIZE, cancellable);
|
||||
uint64 raw = d_buf.read_uint64 (0);
|
||||
Descriptor desc = Descriptor.parse (raw, level, p.granule);
|
||||
|
||||
if (desc.kind != TABLE)
|
||||
throw new Error.NOT_SUPPORTED ("Walk failed at level %u", level);
|
||||
|
||||
table_pa = desc.target_address;
|
||||
level++;
|
||||
}
|
||||
|
||||
return table_pa;
|
||||
}
|
||||
|
||||
private async void clear_pxn_table_bits_for_va (uint64 va, MMUParameters p, TableWalkCache cache, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
uint64 table_pa = p.tt1;
|
||||
for (uint level = p.first_level; level != 3; level++) {
|
||||
uint entries = compute_max_entries (level, p);
|
||||
uint shift = address_shift_at_level (level, p.granule);
|
||||
uint index = (uint) ((va >> shift) & (entries - 1));
|
||||
uint64 slot_pa = table_pa + (index * Descriptor.SIZE);
|
||||
|
||||
Buffer d_buf = yield gdb.read_buffer (slot_pa, Descriptor.SIZE, cancellable);
|
||||
uint64 raw_desc = d_buf.read_uint64 (0);
|
||||
Descriptor desc = Descriptor.parse (raw_desc, level, p.granule);
|
||||
if (desc.kind != TABLE)
|
||||
break;
|
||||
|
||||
if ((raw_desc & TABLE_PXN_BIT) != 0) {
|
||||
uint64 new_desc = raw_desc & ~TABLE_PXN_BIT;
|
||||
d_buf.write_uint64 (0, new_desc);
|
||||
yield gdb.write_byte_array (slot_pa, d_buf.bytes, cancellable);
|
||||
}
|
||||
|
||||
table_pa = desc.target_address;
|
||||
}
|
||||
}
|
||||
|
||||
private class TableWalkCache {
|
||||
private Gee.Map<uint64?, TableWalkResult> cache =
|
||||
new Gee.HashMap<uint64?, TableWalkResult> (Numeric.uint64_hash, Numeric.uint64_equal);
|
||||
|
||||
public TableWalkResult? lookup (uint64 va, MMUParameters p) {
|
||||
for (int level = 2; level >= (int) p.first_level; level--) {
|
||||
uint64 cache_key = compute_cache_key (va, (uint) level, p);
|
||||
TableWalkResult? result = cache[cache_key];
|
||||
if (result != null)
|
||||
return result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void store (uint64 va, uint level, uint64 table_pa, MMUParameters p) {
|
||||
if (level >= 3)
|
||||
return;
|
||||
|
||||
uint64 cache_key = compute_cache_key (va, level, p);
|
||||
cache[cache_key] = new TableWalkResult () {
|
||||
table_pa = table_pa,
|
||||
level = level
|
||||
};
|
||||
}
|
||||
|
||||
private uint64 compute_cache_key (uint64 va, uint level, MMUParameters p) {
|
||||
uint shift = address_shift_at_level (level + 1, p.granule);
|
||||
return (va >> shift) << shift;
|
||||
}
|
||||
}
|
||||
|
||||
private class TableWalkResult {
|
||||
public uint64 table_pa;
|
||||
public uint level;
|
||||
}
|
||||
|
||||
public async Gee.List<uint64?> scan_ranges (Gee.List<Gum.MemoryRange?> ranges, MatchPattern pattern, uint max_matches,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
unowned uint8[] scanner_blob = Data.Barebone.get_memory_scanner_arm64_elf_blob ().data;
|
||||
|
||||
var raw_scanner = new Bytes.static (scanner_blob);
|
||||
|
||||
Gum.ElfModule scanner;
|
||||
try {
|
||||
scanner = new Gum.ElfModule.from_blob (new Bytes.static (scanner_blob));
|
||||
scanner = new Gum.ElfModule.from_blob (raw_scanner);
|
||||
} catch (Gum.Error e) {
|
||||
throw new Error.NOT_SUPPORTED ("%s", e.message);
|
||||
}
|
||||
@@ -293,13 +494,17 @@ namespace Frida.Barebone {
|
||||
|
||||
uint64 module_page_pa = page_start (module_pa, page_size);
|
||||
|
||||
Allocation module_allocation = yield allocate_pages (module_page_pa, num_pages, cancellable);
|
||||
var module_pas = new Gee.ArrayList<uint64?> ();
|
||||
for (uint i = 0; i != num_pages; i++)
|
||||
module_pas.add (module_page_pa + (i * page_size)); // FIXME: This assumes a contiguous range.
|
||||
|
||||
Allocation module_allocation = yield allocate_pages (module_pas, cancellable);
|
||||
|
||||
size_t page_offset = (size_t) (module_pa - module_page_pa);
|
||||
uint64 module_va = module_allocation.virtual_address + page_offset;
|
||||
uint64 data_va = module_va + data_offset;
|
||||
|
||||
Bytes scanner_module = relocate (scanner, module_va);
|
||||
Bytes scanner_module = relocate (scanner, raw_scanner, module_va);
|
||||
Bytes original_memory = yield gdb.read_byte_array (module_va, vm_size, cancellable);
|
||||
yield gdb.write_byte_array (module_va, scanner_module, cancellable);
|
||||
|
||||
@@ -354,14 +559,17 @@ namespace Frida.Barebone {
|
||||
case ABS64:
|
||||
relocated.write_uint64 ((size_t) r.address, base_va + r.symbol.address + r.addend);
|
||||
break;
|
||||
case PREL32:
|
||||
var diff = (int64) (base_va + r.symbol.address + r.addend) - (int64) (base_va + r.address);
|
||||
relocated.write_int32 ((size_t) r.address, (int32) diff);
|
||||
break;
|
||||
default:
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported relocation type: %s",
|
||||
Marshal.enum_to_nick<Gum.ElfArm64Relocation> (type));
|
||||
}
|
||||
}
|
||||
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, uint64 landing_zone, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
if (args.length > 8)
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported number of arguments; please open a PR");
|
||||
|
||||
@@ -377,6 +585,7 @@ namespace Frida.Barebone {
|
||||
|
||||
regs["pc"] = impl;
|
||||
|
||||
uint64 landing_zone = saved_regs["pc"].get_uint64 ();
|
||||
regs["x30"] = landing_zone;
|
||||
|
||||
uint64 sp = saved_regs["sp"].get_uint64 ();
|
||||
@@ -406,6 +615,35 @@ namespace Frida.Barebone {
|
||||
return retval;
|
||||
}
|
||||
|
||||
public async void execute (uint64 start, uint64 end, Cancellable? cancellable) throws Error, IOError {
|
||||
bool was_running = gdb.state != STOPPED;
|
||||
if (was_running)
|
||||
yield gdb.stop (cancellable);
|
||||
|
||||
GDB.Thread thread = gdb.exception.thread;
|
||||
Gee.Map<string, Variant> saved_regs = yield thread.read_registers (cancellable);
|
||||
|
||||
var regs = new Gee.HashMap<string, Variant> ();
|
||||
regs.set_all (saved_regs);
|
||||
|
||||
regs["pc"] = start;
|
||||
|
||||
yield thread.write_registers (regs, cancellable);
|
||||
|
||||
GDB.Breakpoint bp = yield gdb.add_breakpoint (SOFT, end, 4, cancellable);
|
||||
GDB.Exception ex = null;
|
||||
do {
|
||||
ex = yield gdb.continue_until_exception (cancellable);
|
||||
} while (ex.breakpoint != bp || ex.thread.id != thread.id);
|
||||
// TODO: Improve GDB.Client to guarantee a single GDB.Thread instance per ID.
|
||||
yield bp.remove (cancellable);
|
||||
|
||||
yield thread.write_registers (saved_regs, cancellable);
|
||||
|
||||
if (was_running)
|
||||
yield gdb.continue (cancellable);
|
||||
}
|
||||
|
||||
public async CallFrame load_call_frame (GDB.Thread thread, uint arity, Cancellable? cancellable) throws Error, IOError {
|
||||
var regs = yield thread.read_registers (cancellable);
|
||||
|
||||
@@ -689,6 +927,10 @@ namespace Frida.Barebone {
|
||||
public uint first_level;
|
||||
public uint64 upper_bits;
|
||||
public uint64 tt1;
|
||||
public uint t1sz;
|
||||
|
||||
public bool sprr_enabled;
|
||||
public uint64 sprr_perm;
|
||||
|
||||
public static async MMUParameters load (GDB.Client gdb, Cancellable? cancellable) throws Error, IOError {
|
||||
GDB.Exception? exception = gdb.exception;
|
||||
@@ -716,6 +958,10 @@ namespace Frida.Barebone {
|
||||
parameters.upper_bits |= 1ULL << (63 - i);
|
||||
|
||||
parameters.tt1 = regs.ttbr1 & INT48_MASK;
|
||||
parameters.t1sz = t1sz;
|
||||
|
||||
parameters.sprr_enabled = (regs.sprr_config & 1) != 0;
|
||||
parameters.sprr_perm = regs.sprr_perm;
|
||||
|
||||
return parameters;
|
||||
}
|
||||
@@ -724,6 +970,8 @@ namespace Frida.Barebone {
|
||||
private class MMURegisters {
|
||||
public uint64 tcr;
|
||||
public uint64 ttbr1;
|
||||
public uint64 sprr_config;
|
||||
public uint64 sprr_perm;
|
||||
|
||||
public static async MMURegisters read (GDB.Thread thread, Cancellable? cancellable) throws Error, IOError {
|
||||
var regs = new MMURegisters ();
|
||||
@@ -741,10 +989,19 @@ namespace Frida.Barebone {
|
||||
regs.tcr = val;
|
||||
else if (name == "ttbr1_el1")
|
||||
regs.ttbr1 = val;
|
||||
else if (name == "sprr_config_el1")
|
||||
regs.sprr_config = val;
|
||||
else if (name == "sprr_el1br1_el1")
|
||||
regs.sprr_perm = val;
|
||||
}
|
||||
} else {
|
||||
regs.tcr = yield thread.read_register ("tcr_el1", cancellable);
|
||||
regs.ttbr1 = yield thread.read_register ("ttbr1_el1", cancellable);
|
||||
try {
|
||||
regs.sprr_config = yield thread.read_register ("sprr_config_el1", cancellable);
|
||||
regs.sprr_perm = yield thread.read_register ("sprr_el1br1_el1", cancellable);
|
||||
} catch (Error e) {
|
||||
}
|
||||
}
|
||||
|
||||
return regs;
|
||||
@@ -850,16 +1107,27 @@ namespace Frida.Barebone {
|
||||
|
||||
private class DescriptorAllocation : Object, Allocation {
|
||||
public uint64 virtual_address {
|
||||
get { return base_va; }
|
||||
get {
|
||||
return base_va;
|
||||
}
|
||||
}
|
||||
|
||||
public size_t size {
|
||||
get {
|
||||
return _size;
|
||||
}
|
||||
}
|
||||
|
||||
private uint64 base_va;
|
||||
private size_t _size;
|
||||
private uint64 first_slot;
|
||||
private Bytes? old_descriptors;
|
||||
private GDB.Client gdb;
|
||||
|
||||
public DescriptorAllocation (uint64 base_va, uint64 first_slot, Bytes old_descriptors, GDB.Client gdb) {
|
||||
public DescriptorAllocation (uint64 base_va, size_t size, uint64 first_slot, Bytes old_descriptors,
|
||||
GDB.Client gdb) {
|
||||
this.base_va = base_va;
|
||||
this._size = size;
|
||||
this.first_slot = first_slot;
|
||||
this.old_descriptors = old_descriptors;
|
||||
this.gdb = gdb;
|
||||
@@ -908,11 +1176,23 @@ namespace Frida.Barebone {
|
||||
assert_not_reached ();
|
||||
}
|
||||
|
||||
private static uint compute_max_entries (uint level, Granule granule) {
|
||||
return 1 << num_address_bits_at_level (level, granule);
|
||||
private static uint compute_max_entries (uint level, MMUParameters p) {
|
||||
return 1 << num_address_bits_at_level (level, p);
|
||||
}
|
||||
|
||||
private static uint num_address_bits_at_level (uint level, Granule granule) {
|
||||
private static uint num_address_bits_at_level (uint level, MMUParameters p) {
|
||||
if (level == p.first_level) {
|
||||
uint available_address_bits = 64 - p.t1sz - inpage_bits_for_granule (p.granule);
|
||||
uint consumed_by_lower_levels = 0;
|
||||
for (uint l = level + 1; l <= 3; l++)
|
||||
consumed_by_lower_levels += unclipped_address_bits_at_level (l, p.granule);
|
||||
return available_address_bits - consumed_by_lower_levels;
|
||||
} else {
|
||||
return unclipped_address_bits_at_level (level, p.granule);
|
||||
}
|
||||
}
|
||||
|
||||
private static uint unclipped_address_bits_at_level (uint level, Granule granule) {
|
||||
switch (granule) {
|
||||
case 4K:
|
||||
return 9;
|
||||
@@ -932,7 +1212,7 @@ namespace Frida.Barebone {
|
||||
private static uint address_shift_at_level (uint level, Granule granule) {
|
||||
uint shift = inpage_bits_for_granule (granule);
|
||||
for (int l = 2; l != (int) level - 1; l--)
|
||||
shift += num_address_bits_at_level (l, granule);
|
||||
shift += unclipped_address_bits_at_level (l, granule);
|
||||
return shift;
|
||||
}
|
||||
|
||||
@@ -949,7 +1229,45 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
|
||||
private static Gum.PageProtection protection_from_flags (DescriptorFlags flags) {
|
||||
private static Gum.PageProtection protection_from_flags (DescriptorFlags flags, MMUParameters p) {
|
||||
if (p.sprr_enabled) {
|
||||
uint idx = 0;
|
||||
if ((flags & DescriptorFlags.AP_READ_ONLY) != 0)
|
||||
idx |= 1 << 3;
|
||||
if ((flags & DescriptorFlags.AP_ALLOW_APPLICATION) != 0)
|
||||
idx |= 1 << 2;
|
||||
if ((flags & DescriptorFlags.UXN) != 0)
|
||||
idx |= 1 << 1;
|
||||
if ((flags & DescriptorFlags.PXN) != 0)
|
||||
idx |= 1 << 0;
|
||||
|
||||
uint perm = (uint) ((p.sprr_perm >> (idx * 4)) & 0xf);
|
||||
|
||||
Gum.PageProtection prot;
|
||||
switch (perm & 3) {
|
||||
case 0:
|
||||
prot = 0;
|
||||
break;
|
||||
case 1:
|
||||
prot = READ | EXECUTE;
|
||||
if ((perm >> 2) == 2)
|
||||
prot = EXECUTE;
|
||||
break;
|
||||
case 2:
|
||||
prot = READ;
|
||||
break;
|
||||
case 3:
|
||||
prot = READ | WRITE;
|
||||
if ((perm >> 2) == 1)
|
||||
prot = 0;
|
||||
break;
|
||||
default:
|
||||
assert_not_reached ();
|
||||
}
|
||||
|
||||
return prot;
|
||||
}
|
||||
|
||||
Gum.PageProtection prot = READ;
|
||||
if ((flags & DescriptorFlags.PXN) == 0)
|
||||
prot |= EXECUTE;
|
||||
@@ -958,6 +1276,93 @@ namespace Frida.Barebone {
|
||||
return prot;
|
||||
}
|
||||
|
||||
private static uint64 apply_protection_bits (uint64 descriptor, Gum.PageProtection prot, MMUParameters p) throws Error {
|
||||
uint64 result = descriptor;
|
||||
|
||||
if (p.sprr_enabled) {
|
||||
uint target_sprr_index = find_sprr_index_for_permissions (prot, p);
|
||||
result = apply_sprr_index_to_descriptor (result, target_sprr_index);
|
||||
} else {
|
||||
result = apply_non_sprr_protection_bits (result, prot);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static uint64 apply_non_sprr_protection_bits (uint64 descriptor, Gum.PageProtection prot) {
|
||||
uint64 result = descriptor;
|
||||
|
||||
bool want_exec = (prot & Gum.PageProtection.EXECUTE) != 0;
|
||||
bool want_write = (prot & Gum.PageProtection.WRITE) != 0;
|
||||
|
||||
if (want_exec)
|
||||
result &= ~(UXN_BIT | PXN_BIT);
|
||||
else
|
||||
result |= (UXN_BIT | PXN_BIT);
|
||||
|
||||
if (want_write) {
|
||||
result &= ~(AP1_BIT | AP0_BIT);
|
||||
} else {
|
||||
result |= AP1_BIT;
|
||||
result &= ~AP0_BIT;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static uint find_sprr_index_for_permissions (Gum.PageProtection prot, MMUParameters p) throws Error {
|
||||
bool want_read = (prot & Gum.PageProtection.READ) != 0;
|
||||
bool want_write = (prot & Gum.PageProtection.WRITE) != 0;
|
||||
bool want_exec = (prot & Gum.PageProtection.EXECUTE) != 0;
|
||||
|
||||
for (uint i = 0; i != 16; i++) {
|
||||
uint perm = (uint) ((p.sprr_perm >> (i * 4)) & 0xf);
|
||||
|
||||
bool slot_allows_read = false;
|
||||
bool slot_allows_write = false;
|
||||
bool slot_allows_exec = false;
|
||||
|
||||
switch (perm & 3) {
|
||||
case 0:
|
||||
break;
|
||||
case 1:
|
||||
slot_allows_exec = true;
|
||||
if ((perm >> 2) != 2)
|
||||
slot_allows_read = true;
|
||||
break;
|
||||
case 2:
|
||||
slot_allows_read = true;
|
||||
break;
|
||||
case 3:
|
||||
slot_allows_read = true;
|
||||
slot_allows_write = ((perm >> 2) != 1);
|
||||
break;
|
||||
}
|
||||
|
||||
if (slot_allows_read == want_read && slot_allows_write == want_write && slot_allows_exec == want_exec)
|
||||
return i;
|
||||
}
|
||||
|
||||
throw new Error.INVALID_ARGUMENT ("No suitable SPRR slot found for protection 0x%x", prot);
|
||||
}
|
||||
|
||||
private static uint64 apply_sprr_index_to_descriptor (uint64 descriptor, uint sprr_index) {
|
||||
uint64 result = descriptor;
|
||||
|
||||
result &= ~(AP1_BIT | AP0_BIT | UXN_BIT | PXN_BIT);
|
||||
|
||||
if ((sprr_index & 0x8) != 0)
|
||||
result |= AP1_BIT;
|
||||
if ((sprr_index & 0x4) != 0)
|
||||
result |= AP0_BIT;
|
||||
if ((sprr_index & 0x2) != 0)
|
||||
result |= UXN_BIT;
|
||||
if ((sprr_index & 0x1) != 0)
|
||||
result |= PXN_BIT;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Gum.PageProtection protection_from_corellium_pt_details (string details) {
|
||||
Gum.PageProtection prot = READ;
|
||||
if (!("pXN" in details))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public class UnknownMachine : Object, Machine {
|
||||
public sealed class UnknownMachine : Object, Machine {
|
||||
public GDB.Client gdb {
|
||||
get;
|
||||
set;
|
||||
@@ -22,15 +22,24 @@ namespace Frida.Barebone {
|
||||
return 4096;
|
||||
}
|
||||
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async void enumerate_ranges (Gum.PageProtection prot, FoundRangeFunc func, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
}
|
||||
|
||||
public async Allocation allocate_pages (uint64 physical_address, uint num_pages, Cancellable? cancellable)
|
||||
public async Allocation allocate_pages (Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async void protect_pages (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async Gee.List<uint64?> scan_ranges (Gee.List<Gum.MemoryRange?> ranges, MatchPattern pattern,
|
||||
uint max_matches, Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
@@ -40,8 +49,7 @@ namespace Frida.Barebone {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, uint64 landing_zone, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public class IA32Machine : Object, Machine {
|
||||
public sealed class IA32Machine : Object, Machine {
|
||||
public override GDB.Client gdb {
|
||||
get;
|
||||
set;
|
||||
@@ -22,16 +22,25 @@ namespace Frida.Barebone {
|
||||
return 4096;
|
||||
}
|
||||
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async void enumerate_ranges (Gum.PageProtection prot, FoundRangeFunc func, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async Allocation allocate_pages (uint64 physical_address, uint num_pages, Cancellable? cancellable)
|
||||
public async Allocation allocate_pages (Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async void protect_pages (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async Gee.List<uint64?> scan_ranges (Gee.List<Gum.MemoryRange?> ranges, MatchPattern pattern, uint max_matches,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
@@ -41,8 +50,7 @@ namespace Frida.Barebone {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, uint64 landing_zone, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 362 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user