mirror of
https://github.com/frida/frida-core.git
synced 2026-11-08 08:05:58 -10:00
Compare commits
No files matched your search
@@ -21,7 +21,7 @@ jobs:
|
||||
matrix:
|
||||
include:
|
||||
- { id: windows-arm64, runner: '"windows-11-arm"', sys: CLANGARM64, pkg: 'mingw-w64-clang-aarch64-clang', opts: "'-Dfrida-gum:v8=disabled'" }
|
||||
- { id: windows-x86_64, runner: '"windows-latest"', sys: MINGW64, pkg: 'mingw-w64-x86_64-gcc' }
|
||||
- { id: windows-x86_64, runner: '"windows-latest"', sys: UCRT64, pkg: 'mingw-w64-ucrt-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"' }
|
||||
@@ -451,7 +451,10 @@ jobs:
|
||||
cd build
|
||||
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
|
||||
/opt/sabrelite/run.sh /tmp/runner.tar \
|
||||
"cp /opt/frida/frida-tests /opt/frida/frida-agent.so /tmp/ && \
|
||||
ln -sP /opt/frida/labrats /tmp/labrats && \
|
||||
/tmp/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
|
||||
@@ -668,9 +671,17 @@ jobs:
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- uses: ilammy/msvc-dev-cmd@v1
|
||||
with:
|
||||
arch: ${{ matrix.msvc-arch }}
|
||||
- name: Set up MSVC environment
|
||||
run: |
|
||||
$vs = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -products * -latest -property installationPath
|
||||
$before = @{}
|
||||
Get-ChildItem env: | ForEach-Object { $before[$_.Name] = $_.Value }
|
||||
cmd /c "`"$vs\VC\Auxiliary\Build\vcvarsall.bat`" ${{ matrix.msvc-arch }} >nul && set" | ForEach-Object {
|
||||
$name, $value = $_ -split '=', 2
|
||||
if ($before[$name] -ne $value) {
|
||||
"$name=$value" >> $env:GITHUB_ENV
|
||||
}
|
||||
}
|
||||
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
|
||||
@@ -43,7 +43,7 @@ platform-dependent (e.g. `linux-x86_64`).
|
||||
## Build Requirements
|
||||
|
||||
- **Vala compiler**: Must be the Frida-optimized fork from
|
||||
https://github.com/frida/vala (checks for `-frida` suffix
|
||||
https://github.com/frida-forks/vala (checks for `-frida` suffix
|
||||
in version)
|
||||
- **C/C++ standards**: gnu99/c99 for C, c++17 for C++
|
||||
- **Go >= 1.24**: Required for compiler backend
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
PYTHON ?= $(shell which python3 >/dev/null && echo python3 || echo python)
|
||||
PYTHON ?= $(shell command -v python3 >/dev/null && echo python3 || echo python)
|
||||
|
||||
all $(MAKECMDGOALS):
|
||||
@$(PYTHON) \
|
||||
@@ -8,7 +8,7 @@ all $(MAKECMDGOALS):
|
||||
$(MAKECMDGOALS)
|
||||
|
||||
git-submodules:
|
||||
@if [ ! -f releng/meson/meson.py ]; then \
|
||||
@if [ ! -f releng/meson/meson.py ] || git submodule status 2>/dev/null | grep -q '^-'; then \
|
||||
git submodule update --init --recursive --depth 1; \
|
||||
fi
|
||||
-include git-submodules
|
||||
|
||||
+15
-11
@@ -19,7 +19,7 @@ import traceback
|
||||
from typing import Any, Literal, Mapping, Optional, Sequence, Tuple
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
REPO_ROOT = Path(__file__).absolute().parent.parent
|
||||
NINJA = os.environ.get("NINJA", "ninja")
|
||||
|
||||
|
||||
@@ -592,8 +592,10 @@ def load_meson_options(top_builddir: Path,
|
||||
subprojects: set[str]) -> Sequence[str]:
|
||||
from mesonbuild import coredata
|
||||
|
||||
return [f"-D{adapt_key(k, role)}={v.value}" for k, v in coredata.load(top_builddir).options.items()
|
||||
if option_should_be_forwarded(k, v, role, subprojects)]
|
||||
optstore = coredata.load(top_builddir).optstore
|
||||
|
||||
return [f"-D{adapt_key(k, role)}={v.value}" for k, v in optstore.options.items()
|
||||
if option_should_be_forwarded(k, v, optstore, role, subprojects)]
|
||||
|
||||
|
||||
def adapt_key(k: "OptionKey", role: Role) -> "OptionKey":
|
||||
@@ -603,44 +605,46 @@ def adapt_key(k: "OptionKey", role: Role) -> "OptionKey":
|
||||
|
||||
|
||||
def option_should_be_forwarded(k: "OptionKey",
|
||||
v: "coredata.UserOption[Any]",
|
||||
v: "options.UserOption[Any]",
|
||||
optstore: "options.OptionStore",
|
||||
role: Role,
|
||||
subprojects: set[str]) -> bool:
|
||||
from mesonbuild import coredata
|
||||
from mesonbuild import options
|
||||
from mesonbuild.mesonlib import MachineChoice
|
||||
|
||||
our_project_id = "frida-core" if role == "subproject" else ""
|
||||
is_for_us = k.subproject == our_project_id
|
||||
is_for_child = k.subproject in subprojects
|
||||
|
||||
if k.is_project():
|
||||
if optstore.is_project_option(k):
|
||||
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
|
||||
if k.subproject and k.machine is not coredata.MachineChoice.HOST:
|
||||
if k.subproject and k.machine is not MachineChoice.HOST:
|
||||
return False
|
||||
return is_for_us or is_for_child
|
||||
|
||||
if coredata.CoreData.is_per_machine_option(k):
|
||||
if optstore.is_per_machine_option(k):
|
||||
# The compat build generates its own machine files, so forwarding the
|
||||
# parent's build-machine options would inject a foreign toolchain. In a
|
||||
# native compat build that conjures a compiler-less build machine and
|
||||
# breaks any native: true target.
|
||||
return False
|
||||
|
||||
if k.is_builtin():
|
||||
if optstore.is_builtin_option(k):
|
||||
if k.name in {"buildtype", "genvslite"}:
|
||||
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:
|
||||
if not options.BUILTIN_OPTIONS[k.evolve(subproject=None, machine=MachineChoice.HOST)].yielding:
|
||||
return k.subproject == our_project_id
|
||||
return True
|
||||
|
||||
if k.module == "python":
|
||||
if k.get_module_prefix() == "python":
|
||||
if k.name == "install_env" and v.value == "prefix":
|
||||
return False
|
||||
if not str(v.value):
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
#!/bin/sh
|
||||
|
||||
[ -z "$PYTHON" ] && PYTHON=$(which python3 >/dev/null && echo python3 || echo python)
|
||||
[ -z "$PYTHON" ] && PYTHON=$(command -v python3 >/dev/null && echo python3 || echo python)
|
||||
|
||||
cd $(dirname $0)
|
||||
|
||||
srcroot=$(pwd)
|
||||
|
||||
if [ ! -f releng/meson/meson.py ]; then
|
||||
if [ ! -f releng/meson/meson.py ] || git submodule status 2>/dev/null | grep -q '^-'; then
|
||||
git submodule update --init --recursive --depth 1 || exit $?
|
||||
fi
|
||||
|
||||
|
||||
+394
-35
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida.Agent {
|
||||
public void main (string agent_parameters, ref Frida.UnloadPolicy unload_policy, void * injector_state) {
|
||||
if (Runner.shared_instance == null)
|
||||
@@ -78,6 +80,7 @@ namespace Frida.Agent {
|
||||
private ExitMonitor? exit_monitor;
|
||||
private Gum.Interceptor interceptor;
|
||||
private Gum.Exceptor? exceptor;
|
||||
private bool code_memory_delegated = false;
|
||||
|
||||
private uint child_gating_subscriber_count = 0;
|
||||
private ForkMonitor? fork_monitor;
|
||||
@@ -100,6 +103,9 @@ namespace Frida.Agent {
|
||||
private SpawnMonitor? spawn_monitor;
|
||||
private ThreadSuspendMonitor? thread_suspend_monitor;
|
||||
private UnwindSitter? unwind_sitter;
|
||||
#if ANDROID && (ARM || ARM64)
|
||||
private NativeCloakMirror? native_cloak_mirror;
|
||||
#endif
|
||||
|
||||
private delegate void CompletionNotify ();
|
||||
|
||||
@@ -122,12 +128,37 @@ namespace Frida.Agent {
|
||||
{
|
||||
Gum.MemoryRange? mapped_range = null;
|
||||
|
||||
#if WINDOWS
|
||||
var windows_state = (WindowsInjectorState *) opaque_injector_state;
|
||||
if (windows_state != null) {
|
||||
if (windows_state.mapped_range.size != 0)
|
||||
mapped_range = windows_state.mapped_range;
|
||||
Gum.Cloak.add_range (windows_state.worker_range);
|
||||
if (windows_state.dbghelp_range.size != 0) {
|
||||
Gum.Cloak.add_range (windows_state.dbghelp_range);
|
||||
Gum.Cloak.add_range (windows_state.symsrv_range);
|
||||
Gum.Windows.use_dbghelp_modules ((void *) windows_state.dbghelp_range.base_address,
|
||||
(void *) windows_state.symsrv_range.base_address);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if DARWIN
|
||||
var injector_state = (DarwinInjectorState *) opaque_injector_state;
|
||||
if (injector_state != null)
|
||||
mapped_range = injector_state.mapped_range;
|
||||
#endif
|
||||
|
||||
#if LINUX
|
||||
var linux_state = (LinuxInjectorState *) opaque_injector_state;
|
||||
if (linux_state != null && linux_state.mapped_size != 0) {
|
||||
mapped_range = Gum.MemoryRange () {
|
||||
base_address = linux_state.mapped_base,
|
||||
size = linux_state.mapped_size,
|
||||
};
|
||||
}
|
||||
#endif
|
||||
|
||||
#if PROSPERO
|
||||
var prospero_state = (ProsperoInjectorState *) opaque_injector_state;
|
||||
if (prospero_state != null)
|
||||
@@ -199,6 +230,15 @@ namespace Frida.Agent {
|
||||
return;
|
||||
} else {
|
||||
release_shared_instance ();
|
||||
#if WINDOWS
|
||||
if (windows_state != null) {
|
||||
Gum.Cloak.remove_range (windows_state.worker_range);
|
||||
if (windows_state.dbghelp_range.size != 0) {
|
||||
Gum.Cloak.remove_range (windows_state.dbghelp_range);
|
||||
Gum.Cloak.remove_range (windows_state.symsrv_range);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
ignore_scope = null;
|
||||
@@ -285,25 +325,12 @@ namespace Frida.Agent {
|
||||
}
|
||||
|
||||
~Runner () {
|
||||
var interceptor = this.interceptor;
|
||||
interceptor.begin_transaction ();
|
||||
remove_instrumentation ();
|
||||
|
||||
disable_child_gating ();
|
||||
|
||||
exceptor = null;
|
||||
|
||||
exit_monitor = null;
|
||||
|
||||
interceptor.end_transaction ();
|
||||
|
||||
interceptor.begin_transaction ();
|
||||
|
||||
thread_suspend_monitor = null;
|
||||
unwind_sitter = null;
|
||||
if (code_memory_delegated)
|
||||
Gum.Memory.set_hooks (null);
|
||||
|
||||
invalidate_dbus_context ();
|
||||
|
||||
interceptor.end_transaction ();
|
||||
}
|
||||
|
||||
private void run (owned FileDescriptorTablePadder padder) throws Error {
|
||||
@@ -326,6 +353,9 @@ namespace Frida.Agent {
|
||||
bool enable_unwind_broker = true;
|
||||
bool enable_exit_monitor = true;
|
||||
bool enable_thread_suspend_monitor = true;
|
||||
#if ANDROID && (ARM || ARM64)
|
||||
bool in_emulated_realm = false;
|
||||
#endif
|
||||
foreach (unowned string option in tokens[1:]) {
|
||||
if (option == "eternal")
|
||||
ensure_eternalized ();
|
||||
@@ -341,38 +371,47 @@ namespace Frida.Agent {
|
||||
enable_exit_monitor = false;
|
||||
else if (option == "thread-suspend-monitor:off")
|
||||
enable_thread_suspend_monitor = false;
|
||||
#if ANDROID && (ARM || ARM64)
|
||||
else if (option == "realm:emulated")
|
||||
in_emulated_realm = true;
|
||||
#endif
|
||||
}
|
||||
|
||||
if (exceptor_mode != FULL)
|
||||
Gum.Exceptor.set_mode (exceptor_mode);
|
||||
|
||||
{
|
||||
var interceptor = Gum.Interceptor.obtain ();
|
||||
interceptor.begin_transaction ();
|
||||
|
||||
if (enable_exit_monitor)
|
||||
exit_monitor = new ExitMonitor (this, main_context);
|
||||
|
||||
if (enable_thread_suspend_monitor)
|
||||
thread_suspend_monitor = new ThreadSuspendMonitor (this);
|
||||
|
||||
if (enable_unwind_broker)
|
||||
unwind_sitter = new UnwindSitter (this);
|
||||
|
||||
this.interceptor = interceptor;
|
||||
this.exceptor = Gum.Exceptor.obtain ();
|
||||
|
||||
interceptor.end_transaction ();
|
||||
}
|
||||
interceptor = Gum.Interceptor.obtain ();
|
||||
|
||||
try {
|
||||
yield setup_connection_with_transport_uri (transport_uri);
|
||||
#if ANDROID && (ARM || ARM64)
|
||||
if (in_emulated_realm)
|
||||
yield connect_to_native_realm ();
|
||||
#endif
|
||||
} catch (Error e) {
|
||||
start_error = e;
|
||||
main_loop.quit ();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!can_allocate_code ())
|
||||
delegate_code_memory_to_controller ();
|
||||
|
||||
interceptor.begin_transaction ();
|
||||
|
||||
if (enable_exit_monitor)
|
||||
exit_monitor = new ExitMonitor (this, main_context);
|
||||
|
||||
if (enable_thread_suspend_monitor)
|
||||
thread_suspend_monitor = new ThreadSuspendMonitor (this);
|
||||
|
||||
if (enable_unwind_broker)
|
||||
unwind_sitter = new UnwindSitter (this);
|
||||
|
||||
exceptor = Gum.Exceptor.obtain ();
|
||||
|
||||
interceptor.end_transaction ();
|
||||
|
||||
Gum.ScriptBackend.get_scheduler ().push_job_on_js_thread (Priority.DEFAULT, () => {
|
||||
schedule_idle (start.callback);
|
||||
});
|
||||
@@ -381,6 +420,77 @@ namespace Frida.Agent {
|
||||
padder = null;
|
||||
}
|
||||
|
||||
#if ANDROID && (ARM || ARM64)
|
||||
private async void connect_to_native_realm () throws Error {
|
||||
try {
|
||||
NativeCloak cloak = yield connection.get_proxy (null, ObjectPath.NATIVE_CLOAK, DO_NOT_LOAD_PROPERTIES,
|
||||
null);
|
||||
native_cloak_mirror = new NativeCloakMirror (cloak);
|
||||
native_cloak_mirror.activate ();
|
||||
|
||||
NativeThreadRegistry registry = yield connection.get_proxy (null, ObjectPath.NATIVE_THREAD_REGISTRY,
|
||||
DO_NOT_LOAD_PROPERTIES, null);
|
||||
Gum.ThreadRegistry.set_provider (new NativeThreadProvider (registry));
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.TRANSPORT ("%s", e.message);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private static bool can_allocate_code () {
|
||||
size_t page_size = Gum.query_page_size ();
|
||||
|
||||
void * page = Gum.Memory.allocate (null, page_size, page_size, READ | EXECUTE);
|
||||
if (page == null)
|
||||
return false;
|
||||
|
||||
Gum.Memory.free (page, page_size);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void delegate_code_memory_to_controller () {
|
||||
var hooks = Gum.MemoryHooks () {
|
||||
allocate = allocate_via_controller,
|
||||
protect = protect_via_controller,
|
||||
user_data = this,
|
||||
};
|
||||
Gum.Memory.set_hooks (hooks);
|
||||
|
||||
code_memory_delegated = true;
|
||||
}
|
||||
|
||||
private static void * allocate_via_controller (Gum.AddressSpec? spec, size_t size, size_t alignment,
|
||||
Gum.PageProtection prot, void * user_data) {
|
||||
unowned Runner self = (Runner) user_data;
|
||||
|
||||
uint64 near_address = 0;
|
||||
uint64 max_distance = 0;
|
||||
if (spec != null) {
|
||||
near_address = (uint64) spec.near_address;
|
||||
max_distance = spec.max_distance;
|
||||
}
|
||||
|
||||
try {
|
||||
return (void *) self.controller.allocate_memory (get_process_id (), near_address, max_distance, size,
|
||||
alignment, prot, null);
|
||||
} catch (GLib.Error e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool protect_via_controller (void * address, size_t size, Gum.PageProtection prot,
|
||||
void * user_data) {
|
||||
unowned Runner self = (Runner) user_data;
|
||||
|
||||
try {
|
||||
self.controller.protect_memory (get_process_id (), (uint64) address, size, prot, null);
|
||||
return true;
|
||||
} catch (GLib.Error e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void keep_running_eternalized () {
|
||||
agent_gthread = new Thread<bool> ("frida-eternal-agent", () => {
|
||||
var ignore_scope = new ThreadIgnoreScope (FRIDA_THREAD);
|
||||
@@ -1042,6 +1152,10 @@ namespace Frida.Agent {
|
||||
if (unloading)
|
||||
throw new Error.INVALID_OPERATION ("Agent is already unloading");
|
||||
unloading = true;
|
||||
|
||||
if (code_memory_delegated && !is_eternal)
|
||||
yield remove_instrumentation_while_delegated ();
|
||||
|
||||
perform_unload.begin ();
|
||||
}
|
||||
|
||||
@@ -1087,6 +1201,34 @@ namespace Frida.Agent {
|
||||
}
|
||||
}
|
||||
|
||||
private async void remove_instrumentation_while_delegated () {
|
||||
yield close_all_sessions ();
|
||||
|
||||
remove_instrumentation ();
|
||||
}
|
||||
|
||||
private void remove_instrumentation () {
|
||||
var interceptor = this.interceptor;
|
||||
interceptor.begin_transaction ();
|
||||
|
||||
disable_child_gating ();
|
||||
|
||||
exceptor = null;
|
||||
|
||||
exit_monitor = null;
|
||||
|
||||
interceptor.end_transaction ();
|
||||
|
||||
interceptor.begin_transaction ();
|
||||
|
||||
thread_suspend_monitor = null;
|
||||
unwind_sitter = null;
|
||||
|
||||
interceptor.end_transaction ();
|
||||
|
||||
Gum.shutdown ();
|
||||
}
|
||||
|
||||
private void ensure_eternalized () {
|
||||
if (!_is_eternal) {
|
||||
_is_eternal = true;
|
||||
@@ -1295,7 +1437,7 @@ namespace Frida.Agent {
|
||||
|
||||
private void on_connection_closed (DBusConnection connection, bool remote_peer_vanished, GLib.Error? error) {
|
||||
bool closed_by_us = !remote_peer_vanished && error == null;
|
||||
if (!closed_by_us)
|
||||
if (!closed_by_us && !code_memory_delegated)
|
||||
unload.begin (null);
|
||||
|
||||
Promise<bool> operation = null;
|
||||
@@ -1367,6 +1509,8 @@ namespace Frida.Agent {
|
||||
private Socket? emulated_socket;
|
||||
private BridgeState? emulated_bridge_state;
|
||||
private Thread<void>? emulated_worker;
|
||||
private NativeCloakService? native_cloak;
|
||||
private NativeThreadRegistryService? native_thread_registry;
|
||||
|
||||
private async AgentSessionProvider? try_get_emulated_provider (Cancellable? cancellable) throws IOError {
|
||||
if (get_emulated_request == null)
|
||||
@@ -1406,6 +1550,8 @@ namespace Frida.Agent {
|
||||
emulated_agent = nb_api.load_library_ext (emulated_agent_path, RTLD_LAZY, classloader_namespace);
|
||||
} else {
|
||||
emulated_agent = nb_api.load_library (emulated_agent_path, RTLD_LAZY);
|
||||
if (emulated_agent == null && nb_api.load_library_ext != null)
|
||||
emulated_agent = nb_api.load_library_ext (emulated_agent_path, RTLD_LAZY, null);
|
||||
}
|
||||
if (emulated_agent == null)
|
||||
throw new Error.NOT_SUPPORTED ("Process is not using emulation");
|
||||
@@ -1445,6 +1591,7 @@ namespace Frida.Agent {
|
||||
* code being discarded, which seems like an edge-case the translator doesn't handle.
|
||||
*/
|
||||
parameters.append ("|exceptor:off|exit-monitor:off");
|
||||
parameters.append ("|realm:emulated");
|
||||
|
||||
emulated_bridge_state = new BridgeState (parameters.str);
|
||||
|
||||
@@ -1453,6 +1600,13 @@ namespace Frida.Agent {
|
||||
var connection = yield new DBusConnection (stream, ServerGuid.HOST_SESSION_SERVICE,
|
||||
AUTHENTICATION_SERVER | AUTHENTICATION_ALLOW_ANONYMOUS, null, cancellable);
|
||||
|
||||
native_cloak = new NativeCloakService ();
|
||||
connection.register_object (ObjectPath.NATIVE_CLOAK, (NativeCloak) native_cloak);
|
||||
|
||||
native_thread_registry = new NativeThreadRegistryService ();
|
||||
connection.register_object (ObjectPath.NATIVE_THREAD_REGISTRY,
|
||||
(NativeThreadRegistry) native_thread_registry);
|
||||
|
||||
AgentSessionProvider provider = yield connection.get_proxy (null, ObjectPath.AGENT_SESSION_PROVIDER,
|
||||
DO_NOT_LOAD_PROPERTIES, cancellable);
|
||||
|
||||
@@ -1500,6 +1654,16 @@ namespace Frida.Agent {
|
||||
emulated_worker = null;
|
||||
}
|
||||
|
||||
if (native_thread_registry != null) {
|
||||
native_thread_registry.close ();
|
||||
native_thread_registry = null;
|
||||
}
|
||||
|
||||
if (native_cloak != null) {
|
||||
native_cloak.close ();
|
||||
native_cloak = null;
|
||||
}
|
||||
|
||||
emulated_socket = null;
|
||||
|
||||
if (emulated_agent != null) {
|
||||
@@ -1660,6 +1824,201 @@ namespace Frida.Agent {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if ANDROID && (X86 || X86_64)
|
||||
private sealed class NativeCloakService : Object, NativeCloak, Gum.Cloak.Observer {
|
||||
private MainContext main_context = MainContext.ref_thread_default ();
|
||||
private bool observing = false;
|
||||
|
||||
public uint[] activate (Cancellable? cancellable) {
|
||||
Gum.Cloak.add_observer (this);
|
||||
observing = true;
|
||||
|
||||
uint[] threads = {};
|
||||
Gum.Cloak.enumerate_threads (id => {
|
||||
threads += (uint) id;
|
||||
return true;
|
||||
});
|
||||
return threads;
|
||||
}
|
||||
|
||||
public void close () {
|
||||
if (!observing)
|
||||
return;
|
||||
|
||||
Gum.Cloak.remove_observer (this);
|
||||
observing = false;
|
||||
}
|
||||
|
||||
public void thread_added (Gum.ThreadId id) {
|
||||
schedule (() => {
|
||||
thread_cloaked ((uint) id);
|
||||
return Source.REMOVE;
|
||||
});
|
||||
}
|
||||
|
||||
public void thread_removed (Gum.ThreadId id) {
|
||||
schedule (() => {
|
||||
thread_uncloaked ((uint) id);
|
||||
return Source.REMOVE;
|
||||
});
|
||||
}
|
||||
|
||||
private void schedule (owned SourceFunc function) {
|
||||
var source = new IdleSource ();
|
||||
source.set_callback ((owned) function);
|
||||
source.attach (main_context);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NativeThreadRegistryService : Object, NativeThreadRegistry {
|
||||
private unowned Gum.ThreadRegistry? registry;
|
||||
private ulong added_handler = 0;
|
||||
private ulong removed_handler = 0;
|
||||
private ulong renamed_handler = 0;
|
||||
|
||||
public NativeThreadInfo[] activate (Cancellable? cancellable) {
|
||||
registry = Gum.ThreadRegistry.obtain ();
|
||||
|
||||
NativeThreadInfo[] threads = {};
|
||||
|
||||
registry.lock ();
|
||||
|
||||
added_handler = registry.thread_added.connect (on_thread_added);
|
||||
removed_handler = registry.thread_removed.connect (on_thread_removed);
|
||||
renamed_handler = registry.thread_renamed.connect (on_thread_renamed);
|
||||
|
||||
registry.enumerate_threads (thread => {
|
||||
threads += NativeThreadInfo ((uint) thread.id, thread.name ?? "");
|
||||
return true;
|
||||
});
|
||||
|
||||
registry.unlock ();
|
||||
|
||||
return threads;
|
||||
}
|
||||
|
||||
public void deactivate (Cancellable? cancellable) {
|
||||
close ();
|
||||
}
|
||||
|
||||
public void close () {
|
||||
if (registry == null)
|
||||
return;
|
||||
|
||||
registry.disconnect (added_handler);
|
||||
registry.disconnect (removed_handler);
|
||||
registry.disconnect (renamed_handler);
|
||||
registry = null;
|
||||
}
|
||||
|
||||
private void on_thread_added (Gum.ThreadDetails thread) {
|
||||
thread_added (NativeThreadInfo ((uint) thread.id, thread.name ?? ""));
|
||||
}
|
||||
|
||||
private void on_thread_removed (Gum.ThreadDetails thread) {
|
||||
thread_removed ((uint) thread.id);
|
||||
}
|
||||
|
||||
private void on_thread_renamed (Gum.ThreadDetails thread, string? previous_name) {
|
||||
thread_renamed ((uint) thread.id, thread.name ?? "");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if ANDROID && (ARM || ARM64)
|
||||
private sealed class NativeCloakMirror : Object {
|
||||
public NativeCloak native_cloak {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
public NativeCloakMirror (NativeCloak native_cloak) {
|
||||
Object (native_cloak: native_cloak);
|
||||
}
|
||||
|
||||
public void activate () throws GLib.Error {
|
||||
native_cloak.thread_cloaked.connect (on_thread_cloaked);
|
||||
native_cloak.thread_uncloaked.connect (on_thread_uncloaked);
|
||||
|
||||
foreach (uint id in native_cloak.activate (null))
|
||||
on_thread_cloaked (id);
|
||||
}
|
||||
|
||||
private void on_thread_cloaked (uint id) {
|
||||
if (!Gum.Cloak.has_thread (id))
|
||||
Gum.Cloak.add_thread (id);
|
||||
}
|
||||
|
||||
private void on_thread_uncloaked (uint id) {
|
||||
Gum.Cloak.remove_thread (id);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NativeThreadProvider : Object, Gum.ThreadProvider {
|
||||
public NativeThreadRegistry native_registry {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
private unowned Gum.ThreadRegistry registry;
|
||||
private ulong added_handler = 0;
|
||||
private ulong removed_handler = 0;
|
||||
private ulong renamed_handler = 0;
|
||||
|
||||
public NativeThreadProvider (NativeThreadRegistry native_registry) {
|
||||
Object (native_registry: native_registry);
|
||||
}
|
||||
|
||||
public void activate (Gum.ThreadRegistry registry) {
|
||||
this.registry = registry;
|
||||
|
||||
added_handler = native_registry.thread_added.connect (add_thread);
|
||||
removed_handler = native_registry.thread_removed.connect (on_thread_removed);
|
||||
renamed_handler = native_registry.thread_renamed.connect (on_thread_renamed);
|
||||
|
||||
NativeThreadInfo[] threads;
|
||||
try {
|
||||
threads = native_registry.activate (null);
|
||||
} catch (GLib.Error e) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var thread in threads)
|
||||
add_thread (thread);
|
||||
}
|
||||
|
||||
public void deactivate () {
|
||||
native_registry.disconnect (added_handler);
|
||||
native_registry.disconnect (removed_handler);
|
||||
native_registry.disconnect (renamed_handler);
|
||||
|
||||
try {
|
||||
native_registry.deactivate (null);
|
||||
} catch (GLib.Error e) {
|
||||
}
|
||||
}
|
||||
|
||||
private void add_thread (NativeThreadInfo thread) {
|
||||
var details = Gum.ThreadDetails ();
|
||||
details.id = thread.id;
|
||||
if (thread.name != "") {
|
||||
details.name = thread.name;
|
||||
details.flags = NAME;
|
||||
}
|
||||
|
||||
registry.register (details);
|
||||
}
|
||||
|
||||
private void on_thread_removed (uint id) {
|
||||
registry.unregister (id);
|
||||
}
|
||||
|
||||
private void on_thread_renamed (uint id, string name) {
|
||||
registry.rename (id, (name != "") ? name : null);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private sealed class LiveAgentSession : BaseAgentSession {
|
||||
public uint registration_id {
|
||||
get;
|
||||
|
||||
@@ -25,6 +25,9 @@ if build_agent
|
||||
if host_os_family != 'windows'
|
||||
extra_vala_args += '--pkg=posix'
|
||||
endif
|
||||
if host_os_family == 'windows'
|
||||
extra_vala_args += '--pkg=frida-gum-windows-1.0'
|
||||
endif
|
||||
if host_os_family == 'darwin'
|
||||
extra_vala_args += '--pkg=frida-gum-darwin-1.0'
|
||||
endif
|
||||
@@ -93,8 +96,6 @@ if build_agent
|
||||
install: assets_mode == 'installed' and not need_universal_agent,
|
||||
install_dir: asset_dir,
|
||||
)
|
||||
|
||||
agent_dep = declare_dependency(link_with: agent)
|
||||
endif
|
||||
|
||||
if need_universal_agent
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
@@ -1,797 +0,0 @@
|
||||
namespace Frida {
|
||||
public sealed class BufferBuilder : Object {
|
||||
public ByteOrder byte_order {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
public uint pointer_size {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
public size_t offset {
|
||||
get {
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
|
||||
private ByteArray buffer = new ByteArray ();
|
||||
private size_t cursor = 0;
|
||||
|
||||
private uint64 base_address = 0;
|
||||
private Gee.List<LabelRef>? label_refs;
|
||||
private Gee.Map<string, uint>? label_defs;
|
||||
|
||||
public BufferBuilder (ByteOrder byte_order = HOST, uint pointer_size = (uint) sizeof (size_t)) {
|
||||
Object (
|
||||
byte_order: byte_order,
|
||||
pointer_size: pointer_size
|
||||
);
|
||||
}
|
||||
|
||||
public unowned BufferBuilder seek (size_t offset) {
|
||||
if (buffer.len < offset) {
|
||||
size_t n = offset - buffer.len;
|
||||
Memory.set (get_pointer (offset - n, n), 0, n);
|
||||
}
|
||||
cursor = offset;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder skip (size_t n) {
|
||||
seek (cursor + n);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder align (size_t n) {
|
||||
size_t remainder = cursor % n;
|
||||
if (remainder != 0)
|
||||
skip (n - remainder);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_pointer (uint64 val) {
|
||||
write_pointer (cursor, val);
|
||||
cursor += pointer_size;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_pointer_to_label (string name) {
|
||||
if (label_refs == null)
|
||||
label_refs = new Gee.ArrayList<LabelRef> ();
|
||||
label_refs.add (new LabelRef (name, cursor));
|
||||
return skip (pointer_size);
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_pointer_to_label_if (bool present, string name) {
|
||||
if (present)
|
||||
append_pointer_to_label (name);
|
||||
else
|
||||
append_pointer (0);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_label (string name) throws Error {
|
||||
if (label_defs == null)
|
||||
label_defs = new Gee.HashMap<string, uint> ();
|
||||
if (label_defs.has_key (name))
|
||||
throw new Error.INVALID_ARGUMENT ("Label '%s' already exists", name);
|
||||
label_defs[name] = (uint) cursor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_size (uint64 val) {
|
||||
return append_pointer (val);
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_int8 (int8 val) {
|
||||
write_int8 (cursor, val);
|
||||
cursor += (uint) sizeof (int8);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_uint8 (uint8 val) {
|
||||
write_uint8 (cursor, val);
|
||||
cursor += (uint) sizeof (uint8);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_int16 (int16 val) {
|
||||
write_int16 (cursor, val);
|
||||
cursor += (uint) sizeof (int16);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_uint16 (uint16 val) {
|
||||
write_uint16 (cursor, val);
|
||||
cursor += (uint) sizeof (uint16);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_int32 (int32 val) {
|
||||
write_int32 (cursor, val);
|
||||
cursor += (uint) sizeof (int32);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_uint32 (uint32 val) {
|
||||
write_uint32 (cursor, val);
|
||||
cursor += (uint) sizeof (uint32);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_int64 (int64 val) {
|
||||
write_int64 (cursor, val);
|
||||
cursor += (uint) sizeof (int64);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_uint64 (uint64 val) {
|
||||
write_uint64 (cursor, val);
|
||||
cursor += (uint) sizeof (uint64);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_float (float val) {
|
||||
write_float (cursor, val);
|
||||
cursor += (uint) sizeof (float);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_double (double val) {
|
||||
write_double (cursor, val);
|
||||
cursor += (uint) sizeof (double);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_string (string val, StringTerminator terminator = NUL) {
|
||||
uint size = val.length;
|
||||
if (terminator == NUL)
|
||||
size++;
|
||||
Memory.copy (get_pointer (cursor, size), val, size);
|
||||
cursor += size;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_bytes (Bytes bytes) {
|
||||
return append_data (bytes.get_data ());
|
||||
}
|
||||
|
||||
public unowned BufferBuilder append_data (uint8[] data) {
|
||||
write_data (cursor, data);
|
||||
cursor += data.length;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder write_pointer (size_t offset, uint64 val) {
|
||||
if (pointer_size == 4)
|
||||
write_uint32 (offset, (uint32) val);
|
||||
else
|
||||
write_uint64 (offset, val);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder write_size (size_t offset, uint64 val) {
|
||||
return write_pointer (offset, val);
|
||||
}
|
||||
|
||||
public unowned BufferBuilder write_int8 (size_t offset, int8 val) {
|
||||
*((int8 *) get_pointer (offset, sizeof (int8))) = val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder write_uint8 (size_t offset, uint8 val) {
|
||||
*get_pointer (offset, sizeof (uint8)) = val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder 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 unowned BufferBuilder 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 unowned BufferBuilder 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 unowned BufferBuilder write_uint32 (size_t offset, uint32 val) {
|
||||
uint32 target_val = (byte_order == BIG_ENDIAN)
|
||||
? val.to_big_endian ()
|
||||
: val.to_little_endian ();
|
||||
*((uint32 *) get_pointer (offset, sizeof (uint32))) = target_val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder 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 unowned BufferBuilder write_uint64 (size_t offset, uint64 val) {
|
||||
uint64 target_val = (byte_order == BIG_ENDIAN)
|
||||
? val.to_big_endian ()
|
||||
: val.to_little_endian ();
|
||||
*((uint64 *) get_pointer (offset, sizeof (uint64))) = target_val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder write_float (size_t offset, float val) {
|
||||
return write_uint32 (offset, *((uint32 *) &val));
|
||||
}
|
||||
|
||||
public unowned BufferBuilder write_double (size_t offset, double val) {
|
||||
return write_uint64 (offset, *((uint64 *) &val));
|
||||
}
|
||||
|
||||
public unowned BufferBuilder write_string (size_t offset, string val) {
|
||||
uint size = val.length + 1;
|
||||
Memory.copy (get_pointer (offset, size), val, size);
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferBuilder write_bytes (size_t offset, Bytes bytes) {
|
||||
return write_data (offset, bytes.get_data ());
|
||||
}
|
||||
|
||||
public unowned BufferBuilder write_data (size_t offset, uint8[] data) {
|
||||
Memory.copy (get_pointer (offset, data.length), data, data.length);
|
||||
return this;
|
||||
}
|
||||
|
||||
private uint8 * get_pointer (size_t offset, size_t n) {
|
||||
size_t minimum_size = offset + n;
|
||||
if (buffer.len < minimum_size)
|
||||
buffer.set_size ((uint) minimum_size);
|
||||
|
||||
return (uint8 *) buffer.data + offset;
|
||||
}
|
||||
|
||||
public Bytes try_build (uint64 base_address = 0) throws Error {
|
||||
this.base_address = base_address;
|
||||
|
||||
if (label_refs != null) {
|
||||
foreach (LabelRef r in label_refs)
|
||||
write_pointer (r.offset, address_of (r.name));
|
||||
}
|
||||
|
||||
return ByteArray.free_to_bytes ((owned) buffer);
|
||||
}
|
||||
|
||||
public Bytes build (uint64 base_address = 0) {
|
||||
try {
|
||||
return try_build (base_address);
|
||||
} catch (Error e) {
|
||||
assert_not_reached ();
|
||||
}
|
||||
}
|
||||
|
||||
public uint64 address_of (string label) throws Error {
|
||||
if (label_defs == null || !label_defs.has_key (label))
|
||||
throw new Error.INVALID_OPERATION ("Label '%s' not defined", label);
|
||||
size_t offset = label_defs[label];
|
||||
return base_address + offset;
|
||||
}
|
||||
|
||||
private class LabelRef {
|
||||
public string name;
|
||||
public size_t offset;
|
||||
|
||||
public LabelRef (string name, size_t offset) {
|
||||
this.name = name;
|
||||
this.offset = offset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum StringTerminator {
|
||||
NONE,
|
||||
NUL
|
||||
}
|
||||
|
||||
public sealed class Buffer : Object {
|
||||
public Bytes bytes {
|
||||
get {
|
||||
if (_bytes == null)
|
||||
_bytes = new Bytes.static (_data);
|
||||
return _bytes;
|
||||
}
|
||||
}
|
||||
|
||||
public size_t size {
|
||||
get {
|
||||
return _data.length;
|
||||
}
|
||||
}
|
||||
|
||||
public ByteOrder byte_order {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
public uint pointer_size {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
private Bytes? _bytes;
|
||||
private unowned uint8[] _data;
|
||||
|
||||
public Buffer (Bytes bytes, ByteOrder byte_order = HOST, uint pointer_size = (uint) sizeof (size_t)) {
|
||||
Object (
|
||||
byte_order: byte_order,
|
||||
pointer_size: pointer_size
|
||||
);
|
||||
|
||||
reset_bytes (bytes);
|
||||
}
|
||||
|
||||
public Buffer.from_data (uint8[] data, ByteOrder byte_order = HOST, uint pointer_size = (uint) sizeof (size_t)) {
|
||||
Object (
|
||||
byte_order: byte_order,
|
||||
pointer_size: pointer_size
|
||||
);
|
||||
|
||||
reset_data (data);
|
||||
}
|
||||
|
||||
public void reset_bytes (Bytes bytes) {
|
||||
_bytes = bytes;
|
||||
_data = bytes.get_data ();
|
||||
}
|
||||
|
||||
public void reset_data (uint8[] data) {
|
||||
_bytes = null;
|
||||
_data = data;
|
||||
}
|
||||
|
||||
public unowned uint8[] peek_data () {
|
||||
return _data;
|
||||
}
|
||||
|
||||
public uint64 read_pointer (size_t offset) {
|
||||
return (pointer_size == 4)
|
||||
? read_uint32 (offset)
|
||||
: read_uint64 (offset);
|
||||
}
|
||||
|
||||
public void write_pointer (size_t offset, uint64 val) {
|
||||
if (pointer_size == 4)
|
||||
write_uint32 (offset, (uint32) val);
|
||||
else
|
||||
write_uint64 (offset, val);
|
||||
}
|
||||
|
||||
public int8 read_int8 (size_t offset) {
|
||||
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)
|
||||
? int16.from_big_endian (val)
|
||||
: 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)
|
||||
? uint16.from_big_endian (val)
|
||||
: 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)
|
||||
? int32.from_big_endian (val)
|
||||
: 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)
|
||||
? uint32.from_big_endian (val)
|
||||
: uint32.from_little_endian (val);
|
||||
}
|
||||
|
||||
public unowned Buffer write_uint32 (size_t offset, uint32 val) {
|
||||
uint32 target_val = (byte_order == BIG_ENDIAN)
|
||||
? val.to_big_endian ()
|
||||
: val.to_little_endian ();
|
||||
*((uint32 *) get_pointer (offset, sizeof (uint32))) = target_val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int64 read_int64 (size_t offset) {
|
||||
int64 val = *((int64 *) get_pointer (offset, sizeof (int64)));
|
||||
return (byte_order == BIG_ENDIAN)
|
||||
? int64.from_big_endian (val)
|
||||
: 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)
|
||||
? uint64.from_big_endian (val)
|
||||
: uint64.from_little_endian (val);
|
||||
}
|
||||
|
||||
public unowned Buffer write_uint64 (size_t offset, uint64 val) {
|
||||
uint64 target_val = (byte_order == BIG_ENDIAN)
|
||||
? val.to_big_endian ()
|
||||
: val.to_little_endian ();
|
||||
*((uint64 *) get_pointer (offset, sizeof (uint64))) = target_val;
|
||||
return this;
|
||||
}
|
||||
|
||||
public float read_float (size_t offset) {
|
||||
uint32 bits = read_uint32 (offset);
|
||||
return *((float *) &bits);
|
||||
}
|
||||
|
||||
public double read_double (size_t offset) {
|
||||
uint64 bits = read_uint64 (offset);
|
||||
return *((double *) &bits);
|
||||
}
|
||||
|
||||
public unowned string read_string (size_t offset) throws Error {
|
||||
string * start = (string *) get_pointer (offset, sizeof (char));
|
||||
size_t max_length = _data.length - offset;
|
||||
string * end = memchr (start, 0, max_length);
|
||||
if (end == null)
|
||||
throw new Error.PROTOCOL ("Missing null character");
|
||||
return start;
|
||||
}
|
||||
|
||||
[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) throws Error {
|
||||
string * start = (string *) get_pointer (offset, size);
|
||||
size_t max_length = size_t.min (size, _data.length - offset);
|
||||
string * end = memchr (start, 0, max_length);
|
||||
size_t n;
|
||||
if (end != null)
|
||||
n = end - start;
|
||||
else
|
||||
n = size;
|
||||
return start->substring (0, (long) n);
|
||||
}
|
||||
|
||||
public unowned Buffer write_string (size_t offset, string val) {
|
||||
uint size = val.length + 1;
|
||||
Memory.copy (get_pointer (offset, size), val, size);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Bytes read_bytes (size_t offset, size_t size) {
|
||||
if (_bytes == null)
|
||||
return make_bytes_with_owner ((uint8 *) _data + offset, _data.length - size, this);
|
||||
return _bytes[offset:offset + size];
|
||||
}
|
||||
|
||||
public unowned uint8[] read_data (size_t offset, size_t size) {
|
||||
unowned uint8 * ptr = get_pointer (offset, size);
|
||||
return ((uint8[]) ptr)[:size];
|
||||
}
|
||||
|
||||
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 (_data.length >= minimum_size);
|
||||
return (uint8 *) _data + offset;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class BufferReader {
|
||||
public Buffer buffer {
|
||||
get;
|
||||
}
|
||||
|
||||
public size_t offset {
|
||||
get;
|
||||
}
|
||||
|
||||
public size_t available {
|
||||
get {
|
||||
return _size - _offset;
|
||||
}
|
||||
}
|
||||
|
||||
private size_t _size;
|
||||
|
||||
public BufferReader (Buffer buffer) {
|
||||
reset (buffer);
|
||||
}
|
||||
|
||||
public void reset (Buffer buffer) {
|
||||
_buffer = buffer;
|
||||
_size = buffer.size;
|
||||
_offset = 0;
|
||||
}
|
||||
|
||||
public void reset_at (Buffer buffer, size_t offset) throws Error {
|
||||
_buffer = buffer;
|
||||
_size = buffer.size;
|
||||
seek (offset);
|
||||
}
|
||||
|
||||
public unowned BufferReader seek (size_t offset) throws Error {
|
||||
if (offset > _size)
|
||||
throw new Error.PROTOCOL ("Malformed buffer: truncated");
|
||||
_offset = offset;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferReader skip (size_t n) throws Error {
|
||||
check_available (n);
|
||||
_offset += n;
|
||||
return this;
|
||||
}
|
||||
|
||||
public unowned BufferReader align (size_t alignment) throws Error {
|
||||
size_t mask = alignment - 1;
|
||||
size_t rem = _offset & mask;
|
||||
if (rem != 0)
|
||||
skip (alignment - rem);
|
||||
return this;
|
||||
}
|
||||
|
||||
public uint64 peek_pointer () throws Error {
|
||||
var pointer_size = _buffer.pointer_size;
|
||||
check_available (pointer_size);
|
||||
return _buffer.read_pointer (_offset);
|
||||
}
|
||||
|
||||
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 peek_int8 () throws Error {
|
||||
check_available (sizeof (int8));
|
||||
return _buffer.read_int8 (_offset);
|
||||
}
|
||||
|
||||
public int8 read_int8 () throws Error {
|
||||
check_available (sizeof (int8));
|
||||
var val = _buffer.read_int8 (_offset);
|
||||
_offset += sizeof (int8);
|
||||
return val;
|
||||
}
|
||||
|
||||
public uint8 peek_uint8 () throws Error {
|
||||
check_available (sizeof (uint8));
|
||||
return _buffer.read_uint8 (_offset);
|
||||
}
|
||||
|
||||
public uint8 read_uint8 () throws Error {
|
||||
check_available (sizeof (uint8));
|
||||
var val = _buffer.read_uint8 (_offset);
|
||||
_offset += sizeof (uint8);
|
||||
return val;
|
||||
}
|
||||
|
||||
public int16 peek_int16 () throws Error {
|
||||
check_available (sizeof (int16));
|
||||
return _buffer.read_int16 (_offset);
|
||||
}
|
||||
|
||||
public int16 read_int16 () throws Error {
|
||||
check_available (sizeof (int16));
|
||||
var val = _buffer.read_int16 (_offset);
|
||||
_offset += sizeof (int16);
|
||||
return val;
|
||||
}
|
||||
|
||||
public uint16 peek_uint16 () throws Error {
|
||||
check_available (sizeof (uint16));
|
||||
return _buffer.read_uint16 (_offset);
|
||||
}
|
||||
|
||||
public uint16 read_uint16 () throws Error {
|
||||
check_available (sizeof (uint16));
|
||||
var val = _buffer.read_uint16 (_offset);
|
||||
_offset += sizeof (uint16);
|
||||
return val;
|
||||
}
|
||||
|
||||
public int32 peek_int32 () throws Error {
|
||||
check_available (sizeof (int32));
|
||||
return _buffer.read_int32 (_offset);
|
||||
}
|
||||
|
||||
public int32 read_int32 () throws Error {
|
||||
check_available (sizeof (int32));
|
||||
var val = _buffer.read_int32 (_offset);
|
||||
_offset += sizeof (int32);
|
||||
return val;
|
||||
}
|
||||
|
||||
public uint32 peek_uint32 () throws Error {
|
||||
check_available (sizeof (uint32));
|
||||
return _buffer.read_uint32 (_offset);
|
||||
}
|
||||
|
||||
public uint32 read_uint32 () throws Error {
|
||||
check_available (sizeof (uint32));
|
||||
var val = _buffer.read_uint32 (_offset);
|
||||
_offset += sizeof (uint32);
|
||||
return val;
|
||||
}
|
||||
|
||||
public int64 peek_int64 () throws Error {
|
||||
check_available (sizeof (int64));
|
||||
return _buffer.read_int64 (_offset);
|
||||
}
|
||||
|
||||
public int64 read_int64 () throws Error {
|
||||
check_available (sizeof (int64));
|
||||
var val = _buffer.read_int64 (_offset);
|
||||
_offset += sizeof (int64);
|
||||
return val;
|
||||
}
|
||||
|
||||
public uint64 peek_uint64 () throws Error {
|
||||
check_available (sizeof (uint64));
|
||||
return _buffer.read_uint64 (_offset);
|
||||
}
|
||||
|
||||
public uint64 read_uint64 () throws Error {
|
||||
check_available (sizeof (uint64));
|
||||
var val = _buffer.read_uint64 (_offset);
|
||||
_offset += sizeof (uint64);
|
||||
return val;
|
||||
}
|
||||
|
||||
public float peek_float () throws Error {
|
||||
check_available (sizeof (float));
|
||||
return _buffer.read_float (_offset);
|
||||
}
|
||||
|
||||
public float read_float () throws Error {
|
||||
check_available (sizeof (float));
|
||||
var val = _buffer.read_float (_offset);
|
||||
_offset += sizeof (float);
|
||||
return val;
|
||||
}
|
||||
|
||||
public double peek_double () throws Error {
|
||||
check_available (sizeof (double));
|
||||
return _buffer.read_double (_offset);
|
||||
}
|
||||
|
||||
public double read_double () throws Error {
|
||||
check_available (sizeof (double));
|
||||
var val = _buffer.read_double (_offset);
|
||||
_offset += sizeof (double);
|
||||
return val;
|
||||
}
|
||||
|
||||
public unowned string peek_string () throws Error {
|
||||
check_available (1);
|
||||
return _buffer.read_string (_offset);
|
||||
}
|
||||
|
||||
public unowned string read_string () throws Error {
|
||||
check_available (1);
|
||||
unowned string val = _buffer.read_string (_offset);
|
||||
_offset += val.length + 1;
|
||||
return val;
|
||||
}
|
||||
|
||||
public string peek_fixed_string (size_t size) throws Error {
|
||||
check_available (size);
|
||||
return _buffer.read_fixed_string (_offset, size);
|
||||
}
|
||||
|
||||
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 unowned uint8[] peek_data (size_t size) throws Error {
|
||||
check_available (size);
|
||||
return _buffer.read_data (_offset, size);
|
||||
}
|
||||
|
||||
public unowned uint8[] read_data (size_t size) throws Error {
|
||||
check_available (size);
|
||||
unowned uint8[] slice = _buffer.read_data (_offset, size);
|
||||
_offset += size;
|
||||
return slice;
|
||||
}
|
||||
|
||||
public Bytes read_bytes (size_t size) throws Error {
|
||||
check_available (size);
|
||||
var val = _buffer.read_bytes (_offset, size);
|
||||
_offset += size;
|
||||
return val;
|
||||
}
|
||||
|
||||
public unowned uint8[] read_remaining_data () throws Error {
|
||||
return read_data (available);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
+14
-2
@@ -1,9 +1,13 @@
|
||||
using Efni;
|
||||
|
||||
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);
|
||||
private Gee.Map<ChannelId?, IOStream> unlinked_channels =
|
||||
new Gee.HashMap<ChannelId?, IOStream> (ChannelId.hash, ChannelId.equal);
|
||||
|
||||
~ChannelRegistry () {
|
||||
clear ();
|
||||
@@ -16,25 +20,33 @@ namespace Frida {
|
||||
channel_stream.abandon ();
|
||||
}
|
||||
channels.clear ();
|
||||
unlinked_channels.clear ();
|
||||
}
|
||||
|
||||
public void register (ChannelId id, IOStream stream) {
|
||||
stream.set_data ("channel-registry-entry", new Entry (this, id));
|
||||
lock (channels)
|
||||
lock (channels) {
|
||||
channels[id] = stream;
|
||||
unlinked_channels[id] = stream;
|
||||
}
|
||||
}
|
||||
|
||||
public IOStream link (ChannelId id) throws Error {
|
||||
IOStream? stream;
|
||||
lock (channels)
|
||||
IOStream? unlinked_stream = null;
|
||||
lock (channels) {
|
||||
stream = channels[id];
|
||||
unlinked_channels.unset (id, out unlinked_stream);
|
||||
}
|
||||
if (stream == null)
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid channel ID");
|
||||
return stream;
|
||||
}
|
||||
|
||||
public void unlink (ChannelId id) {
|
||||
IOStream? unlinked_stream = null;
|
||||
lock (channels) {
|
||||
unlinked_channels.unset (id, out unlinked_stream);
|
||||
if (!channels.unset (id))
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
// We need to tease out GDBus' private MainContext as libnice needs to know the MainContext up front :(
|
||||
public async MainContext get_dbus_context () {
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
#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);
|
||||
});
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
#ifndef __FRIDA_DARWIN_H__
|
||||
#define __FRIDA_DARWIN_H__
|
||||
|
||||
#ifdef HAVE_MACOS
|
||||
|
||||
#include <glib.h>
|
||||
#include <xpc/xpc.h>
|
||||
|
||||
G_BEGIN_DECLS
|
||||
|
||||
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);
|
||||
|
||||
G_END_DECLS
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -1,126 +0,0 @@
|
||||
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 Bytes read_all_bytes_sync (File f) throws Error {
|
||||
try {
|
||||
uint8[] contents;
|
||||
f.load_contents (null, out contents, null);
|
||||
return new Bytes.take ((owned) contents);
|
||||
} catch (GLib.Error 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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,15 @@ namespace Frida {
|
||||
return fd;
|
||||
}
|
||||
|
||||
public static FileDescriptor with_size (string name, size_t size) {
|
||||
assert (is_supported ());
|
||||
|
||||
var fd = new FileDescriptor (memfd_create (name, 0));
|
||||
int res = Posix.ftruncate (fd.handle, (Posix.off_t) size);
|
||||
assert (res == 0);
|
||||
return fd;
|
||||
}
|
||||
|
||||
private int memfd_create (string name, uint flags) {
|
||||
return Linux.syscall (LinuxSyscall.MEMFD_CREATE, name, flags);
|
||||
}
|
||||
|
||||
+3
-18
@@ -1,21 +1,16 @@
|
||||
base_sources = [
|
||||
'asset-location.vala',
|
||||
'promise.vala',
|
||||
'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',
|
||||
'xnu-syscalls' / 'xnu-syscalls.vala',
|
||||
'xnu-syscalls' / 'xnu-syscalls-glue.c',
|
||||
]
|
||||
@@ -29,13 +24,6 @@ else
|
||||
extra_vala_args += '--pkg=posix'
|
||||
endif
|
||||
|
||||
if host_os == 'macos'
|
||||
base_sources += [
|
||||
'xpc.vala',
|
||||
'frida-darwin.c',
|
||||
]
|
||||
endif
|
||||
|
||||
if host_os_family == 'darwin'
|
||||
base_sources += 'corefoundation.vala'
|
||||
extra_vala_args += '--pkg=darwin-xnu'
|
||||
@@ -89,14 +77,11 @@ endif
|
||||
if host_os_family != 'windows'
|
||||
base_vala_args += [
|
||||
'--pkg=gio-unix-2.0',
|
||||
'--pkg=posix',
|
||||
]
|
||||
endif
|
||||
if host_os_family == 'darwin'
|
||||
base_vala_args += [
|
||||
'--pkg=corefoundation',
|
||||
'--pkg=darwin-gcd',
|
||||
'--pkg=darwin-xpc',
|
||||
]
|
||||
endif
|
||||
if host_os_family == 'linux'
|
||||
@@ -115,7 +100,7 @@ base = static_library('frida-base-' + api_version, base_sources,
|
||||
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,
|
||||
dependencies: [glib_dep, gobject_dep, gio_dep, libsoup_dep, nice_dep, usrsctp_dep, gee_dep, json_glib_dep, gum_dep, openssl_dep, efni_dep] + extra_deps,
|
||||
install: have_in_tree_payloads,
|
||||
install_dir: [true, header_install_dir, true, false],
|
||||
)
|
||||
@@ -123,7 +108,7 @@ base = static_library('frida-base-' + api_version, base_sources,
|
||||
base_dep = declare_dependency(
|
||||
include_directories: include_directories('.'),
|
||||
link_with: base,
|
||||
dependencies: [nice_dep, json_glib_dep, gum_dep] + extra_deps,
|
||||
dependencies: [nice_dep, json_glib_dep, gum_dep, efni_dep] + extra_deps,
|
||||
)
|
||||
|
||||
base_build_dir = meson.current_build_dir()
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
#if HAVE_NICE
|
||||
namespace Frida {
|
||||
namespace PeerConnection {
|
||||
|
||||
+2
-2
@@ -278,9 +278,9 @@ namespace Frida {
|
||||
|
||||
public uint exit_status;
|
||||
|
||||
public Posix.Signal term_signal;
|
||||
public int term_signal;
|
||||
|
||||
public Posix.Signal stop_signal;
|
||||
public int stop_signal;
|
||||
|
||||
public WaitResult (uint pid, int status) {
|
||||
this.pid = pid;
|
||||
|
||||
+58
-124
@@ -1,19 +1,18 @@
|
||||
namespace Frida {
|
||||
public sealed class Promise<T> {
|
||||
private Impl<T> impl;
|
||||
private Efni.Promise<T> impl;
|
||||
private Future<T>? _future;
|
||||
|
||||
public Future<T> future {
|
||||
get {
|
||||
return impl;
|
||||
if (_future == null)
|
||||
_future = new FutureImpl<T> (impl.future);
|
||||
return _future;
|
||||
}
|
||||
}
|
||||
|
||||
public Promise () {
|
||||
impl = new Impl<T> ();
|
||||
}
|
||||
|
||||
~Promise () {
|
||||
impl.abandon ();
|
||||
impl = new Efni.Promise<T> ();
|
||||
}
|
||||
|
||||
public void resolve (T result) {
|
||||
@@ -24,149 +23,84 @@ namespace Frida {
|
||||
impl.reject (error);
|
||||
}
|
||||
|
||||
private class Impl<T> : Object, Future<T> {
|
||||
private class FutureImpl<T> : Object, Future<T> {
|
||||
private Efni.Future<T> inner;
|
||||
|
||||
public bool ready {
|
||||
get {
|
||||
return _ready;
|
||||
return inner.ready;
|
||||
}
|
||||
}
|
||||
private bool _ready = false;
|
||||
|
||||
public T? value {
|
||||
get {
|
||||
return _value;
|
||||
return inner.value;
|
||||
}
|
||||
}
|
||||
private T? _value;
|
||||
|
||||
public GLib.Error? error {
|
||||
get {
|
||||
return _error;
|
||||
return inner.error;
|
||||
}
|
||||
}
|
||||
private GLib.Error? _error;
|
||||
|
||||
private Gee.ArrayQueue<CompletionFuncEntry>? on_complete;
|
||||
private Gee.ArrayQueue<ThenHandlerEntry<T>>? on_then;
|
||||
public FutureImpl (Efni.Future<T> inner) {
|
||||
this.inner = inner;
|
||||
}
|
||||
|
||||
public async T wait_async (Cancellable? cancellable) throws Frida.Error, IOError {
|
||||
if (_ready)
|
||||
return get_result ();
|
||||
public async T wait_async (Cancellable? cancellable) throws Error, IOError {
|
||||
if (!inner.ready) {
|
||||
bool resumed = false;
|
||||
|
||||
var entry = new CompletionFuncEntry (wait_async.callback);
|
||||
if (on_complete == null)
|
||||
on_complete = new Gee.ArrayQueue<CompletionFuncEntry> ();
|
||||
on_complete.offer (entry);
|
||||
var cancel_source = new CancellableSource (cancellable);
|
||||
cancel_source.set_callback (() => {
|
||||
if (!resumed) {
|
||||
resumed = true;
|
||||
wait_async.callback ();
|
||||
}
|
||||
return Source.REMOVE;
|
||||
});
|
||||
cancel_source.attach (MainContext.get_thread_default ());
|
||||
|
||||
var cancel_source = new CancellableSource (cancellable);
|
||||
cancel_source.set_callback (() => {
|
||||
on_complete.remove (entry);
|
||||
wait_async.callback ();
|
||||
return false;
|
||||
});
|
||||
cancel_source.attach (MainContext.get_thread_default ());
|
||||
inner.then (f => {
|
||||
if (!resumed) {
|
||||
resumed = true;
|
||||
wait_async.callback ();
|
||||
}
|
||||
});
|
||||
|
||||
yield;
|
||||
yield;
|
||||
|
||||
cancel_source.destroy ();
|
||||
cancel_source.destroy ();
|
||||
|
||||
cancellable.set_error_if_cancelled ();
|
||||
cancellable.set_error_if_cancelled ();
|
||||
}
|
||||
|
||||
return get_result ();
|
||||
}
|
||||
|
||||
public void then (owned FutureCompletionHandler<T> handler) {
|
||||
if (_ready) {
|
||||
schedule (() => {
|
||||
handler (this);
|
||||
return Source.REMOVE;
|
||||
});
|
||||
return;
|
||||
inner.then (f => {
|
||||
handler (this);
|
||||
});
|
||||
}
|
||||
|
||||
public T get_result () throws Error, IOError {
|
||||
GLib.Error? e = inner.error;
|
||||
if (e != null) {
|
||||
if (e is Error)
|
||||
throw (Error) e;
|
||||
|
||||
if (e is Efni.Error)
|
||||
throw error_from_efni ((Efni.Error) e);
|
||||
|
||||
if (e is IOError.CANCELLED)
|
||||
throw (IOError) e;
|
||||
|
||||
throw new Error.TRANSPORT ("%s", e.message);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
if (error is IOError.CANCELLED)
|
||||
throw (IOError) error;
|
||||
|
||||
throw new Frida.Error.TRANSPORT ("%s", error.message);
|
||||
}
|
||||
|
||||
return _value;
|
||||
}
|
||||
|
||||
internal void resolve (T value) {
|
||||
assert (!_ready);
|
||||
|
||||
_value = value;
|
||||
transition_to_ready ();
|
||||
}
|
||||
|
||||
internal void reject (GLib.Error error) {
|
||||
assert (!_ready);
|
||||
|
||||
_error = error;
|
||||
transition_to_ready ();
|
||||
}
|
||||
|
||||
internal void abandon () {
|
||||
if (!_ready) {
|
||||
reject (new Frida.Error.INVALID_OPERATION ("Promise abandoned"));
|
||||
}
|
||||
}
|
||||
|
||||
internal void transition_to_ready () {
|
||||
_ready = true;
|
||||
|
||||
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;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
public SourceFunc func;
|
||||
|
||||
public CompletionFuncEntry (owned SourceFunc func) {
|
||||
this.func = (owned) func;
|
||||
}
|
||||
}
|
||||
|
||||
private class ThenHandlerEntry<T> {
|
||||
public FutureCompletionHandler<T> handler;
|
||||
|
||||
public ThenHandlerEntry (owned FutureCompletionHandler<T> handler) {
|
||||
this.handler = (owned) handler;
|
||||
return inner.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -175,9 +109,9 @@ namespace Frida {
|
||||
public abstract bool ready { get; }
|
||||
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 async T wait_async (Cancellable? cancellable) throws Error, IOError;
|
||||
public abstract void then (owned FutureCompletionHandler<T> handler);
|
||||
public abstract T get_result () throws Frida.Error, IOError;
|
||||
public abstract T get_result () throws Error, IOError;
|
||||
}
|
||||
|
||||
public delegate void FutureCompletionHandler<T> (Future<T> future);
|
||||
|
||||
+91
-50
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
[DBus (name = "re.frida.HostSession17")]
|
||||
public interface HostSession : Object {
|
||||
@@ -124,8 +126,43 @@ namespace Frida {
|
||||
|
||||
public abstract async void acknowledge_spawn (HostChildInfo info, SpawnStartState start_state,
|
||||
Cancellable? cancellable) throws GLib.Error;
|
||||
|
||||
public abstract uint64 allocate_memory (uint pid, uint64 near_address, uint64 max_distance, uint64 size,
|
||||
uint64 alignment, Gum.PageProtection prot, Cancellable? cancellable) throws GLib.Error;
|
||||
public abstract void protect_memory (uint pid, uint64 address, uint64 size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws GLib.Error;
|
||||
}
|
||||
|
||||
#if ANDROID
|
||||
[DBus (name = "re.frida.NativeThreadRegistry17")]
|
||||
public interface NativeThreadRegistry : Object {
|
||||
public abstract NativeThreadInfo[] activate (Cancellable? cancellable) throws GLib.Error;
|
||||
public abstract void deactivate (Cancellable? cancellable) throws GLib.Error;
|
||||
|
||||
public signal void thread_added (NativeThreadInfo thread);
|
||||
public signal void thread_removed (uint id);
|
||||
public signal void thread_renamed (uint id, string name);
|
||||
}
|
||||
|
||||
[DBus (name = "re.frida.NativeCloak17")]
|
||||
public interface NativeCloak : Object {
|
||||
public abstract uint[] activate (Cancellable? cancellable) throws GLib.Error;
|
||||
|
||||
public signal void thread_cloaked (uint id);
|
||||
public signal void thread_uncloaked (uint id);
|
||||
}
|
||||
|
||||
public struct NativeThreadInfo {
|
||||
public uint id;
|
||||
public string name;
|
||||
|
||||
public NativeThreadInfo (uint id, string name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
[DBus (name = "re.frida.AgentMessageSink17")]
|
||||
public interface AgentMessageSink : Object {
|
||||
public abstract async void post_messages (AgentMessage[] messages, uint batch_id,
|
||||
@@ -1133,6 +1170,15 @@ namespace Frida {
|
||||
}
|
||||
}
|
||||
|
||||
#if WINDOWS
|
||||
public struct WindowsInjectorState {
|
||||
public Gum.MemoryRange mapped_range;
|
||||
public Gum.MemoryRange worker_range;
|
||||
public Gum.MemoryRange dbghelp_range;
|
||||
public Gum.MemoryRange symsrv_range;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if DARWIN
|
||||
public struct DarwinInjectorState {
|
||||
public Gum.MemoryRange? mapped_range;
|
||||
@@ -1143,6 +1189,8 @@ namespace Frida {
|
||||
public struct LinuxInjectorState {
|
||||
public int frida_ctrlfd;
|
||||
public int agent_ctrlfd;
|
||||
public uint64 mapped_base;
|
||||
public size_t mapped_size;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1281,6 +1329,9 @@ namespace Frida {
|
||||
if (e is Frida.Error)
|
||||
throw (Frida.Error) e;
|
||||
|
||||
if (e is Efni.Error)
|
||||
throw error_from_efni ((Efni.Error) e);
|
||||
|
||||
if (e is IOError.CANCELLED)
|
||||
throw (IOError) e;
|
||||
|
||||
@@ -1294,6 +1345,9 @@ namespace Frida {
|
||||
if (e is Frida.Error)
|
||||
throw (Frida.Error) e;
|
||||
|
||||
if (e is Efni.Error)
|
||||
throw error_from_efni ((Efni.Error) e);
|
||||
|
||||
if (e is IOError.CANCELLED)
|
||||
throw (IOError) e;
|
||||
|
||||
@@ -1306,6 +1360,41 @@ namespace Frida {
|
||||
throw new Frida.Error.TRANSPORT ("%s", e.message);
|
||||
}
|
||||
|
||||
namespace Marshal {
|
||||
public T enum_from_nick<T> (string nick) throws Error {
|
||||
try {
|
||||
return Efni.Marshal.enum_from_nick<T> (nick);
|
||||
} catch (Efni.Error e) {
|
||||
throw error_from_efni (e);
|
||||
}
|
||||
}
|
||||
|
||||
public string enum_to_nick<T> (int val) {
|
||||
return Efni.Marshal.enum_to_nick<T> (val);
|
||||
}
|
||||
}
|
||||
|
||||
public static Frida.Error error_from_efni (Efni.Error e) {
|
||||
unowned string m = e.message;
|
||||
if (e is Efni.Error.SERVER_NOT_RUNNING)
|
||||
return new Frida.Error.SERVER_NOT_RUNNING ("%s", m);
|
||||
if (e is Efni.Error.INVALID_ARGUMENT)
|
||||
return new Frida.Error.INVALID_ARGUMENT ("%s", m);
|
||||
if (e is Efni.Error.INVALID_OPERATION)
|
||||
return new Frida.Error.INVALID_OPERATION ("%s", m);
|
||||
if (e is Efni.Error.PERMISSION_DENIED)
|
||||
return new Frida.Error.PERMISSION_DENIED ("%s", m);
|
||||
if (e is Efni.Error.ADDRESS_IN_USE)
|
||||
return new Frida.Error.ADDRESS_IN_USE ("%s", m);
|
||||
if (e is Efni.Error.TIMED_OUT)
|
||||
return new Frida.Error.TIMED_OUT ("%s", m);
|
||||
if (e is Efni.Error.NOT_SUPPORTED)
|
||||
return new Frida.Error.NOT_SUPPORTED ("%s", m);
|
||||
if (e is Efni.Error.PROTOCOL)
|
||||
return new Frida.Error.PROTOCOL ("%s", m);
|
||||
return new Frida.Error.TRANSPORT ("%s", m);
|
||||
}
|
||||
|
||||
public struct HostApplicationInfo {
|
||||
public string identifier;
|
||||
public string name;
|
||||
@@ -2743,6 +2832,8 @@ namespace Frida {
|
||||
public const string AGENT_SESSION_PROVIDER = "/re/frida/AgentSessionProvider";
|
||||
public const string AGENT_SESSION = "/re/frida/AgentSession";
|
||||
public const string AGENT_CONTROLLER = "/re/frida/AgentController";
|
||||
public const string NATIVE_THREAD_REGISTRY = "/re/frida/NativeThreadRegistry";
|
||||
public const string NATIVE_CLOAK = "/re/frida/NativeCloak";
|
||||
public const string AGENT_MESSAGE_SINK = "/re/frida/AgentMessageSink";
|
||||
public const string GADGET_SESSION = "/re/frida/GadgetSession";
|
||||
public const string CHANNEL = "/re/frida/Channel";
|
||||
@@ -2768,54 +2859,4 @@ namespace Frida {
|
||||
return SERVICE + "/" + id.handle;
|
||||
}
|
||||
}
|
||||
|
||||
namespace Marshal {
|
||||
public static T enum_from_nick<T> (string nick) throws Error {
|
||||
var klass = (EnumClass) typeof (T).class_ref ();
|
||||
var v = klass.get_value_by_nick (nick);
|
||||
if (v == null)
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid %s", klass.get_type ().name ());
|
||||
return (T) v.value;
|
||||
}
|
||||
|
||||
public static string enum_to_nick<T> (int val) {
|
||||
var klass = (EnumClass) typeof (T).class_ref ();
|
||||
unowned EnumValue? v = klass.get_value (val);
|
||||
if (v == null)
|
||||
return "unknown-0x%x".printf (val);
|
||||
return v.value_nick;
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
public bool uint64_equal (uint64? val_a, uint64? val_b) {
|
||||
uint64 a = val_a;
|
||||
uint64 b = val_b;
|
||||
return a == b;
|
||||
}
|
||||
|
||||
public uint bytes_hash (Bytes b) {
|
||||
return b.hash ();
|
||||
}
|
||||
|
||||
public static bool bytes_equal (Bytes a, Bytes b) {
|
||||
return a.compare (b) == 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,5 @@
|
||||
#include "frida-base.h"
|
||||
|
||||
#ifdef HAVE_WINDOWS
|
||||
# include <winsock2.h>
|
||||
#else
|
||||
# include <netinet/in.h>
|
||||
# include <netinet/tcp.h>
|
||||
#endif
|
||||
|
||||
void
|
||||
frida_unix_socket_tune_buffer_sizes (gint fd)
|
||||
{
|
||||
#ifndef HAVE_WINDOWS
|
||||
/* The defaults are typically as low as 4K. */
|
||||
const int buffer_size = 256 * 1024;
|
||||
|
||||
setsockopt (fd, SOL_SOCKET, SO_RCVBUF, &buffer_size, sizeof (buffer_size));
|
||||
setsockopt (fd, SOL_SOCKET, SO_SNDBUF, &buffer_size, sizeof (buffer_size));
|
||||
#endif
|
||||
}
|
||||
|
||||
void
|
||||
frida_tcp_enable_nodelay (GSocket * socket)
|
||||
{
|
||||
g_socket_set_option (socket, IPPROTO_TCP, TCP_NODELAY, TRUE, NULL);
|
||||
}
|
||||
|
||||
const gchar *
|
||||
_frida_version_string (void)
|
||||
{
|
||||
|
||||
+27
-86
@@ -1,99 +1,22 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
public const uint16 DEFAULT_CONTROL_PORT = 27042;
|
||||
public const uint16 DEFAULT_CLUSTER_PORT = 27052;
|
||||
|
||||
public SocketConnectable parse_control_address (string? address, uint16 port = 0) throws Error {
|
||||
return parse_socket_address (address, port, "127.0.0.1", DEFAULT_CONTROL_PORT);
|
||||
return parse_frida_address (address, port, DEFAULT_CONTROL_PORT);
|
||||
}
|
||||
|
||||
public SocketConnectable parse_cluster_address (string? address, uint16 port = 0) throws Error {
|
||||
return parse_socket_address (address, port, "127.0.0.1", DEFAULT_CLUSTER_PORT);
|
||||
return parse_frida_address (address, port, DEFAULT_CLUSTER_PORT);
|
||||
}
|
||||
|
||||
public SocketConnectable parse_socket_address (string? address, uint16 port, string default_address,
|
||||
uint16 default_port) throws Error {
|
||||
if (address == null)
|
||||
address = default_address;
|
||||
if (port == 0)
|
||||
port = default_port;
|
||||
|
||||
#if !WINDOWS
|
||||
if (address.has_prefix ("unix:")) {
|
||||
string path = address.substring (5);
|
||||
|
||||
UnixSocketAddressType type = UnixSocketAddress.abstract_names_supported ()
|
||||
? UnixSocketAddressType.ABSTRACT
|
||||
: UnixSocketAddressType.PATH;
|
||||
|
||||
return new UnixSocketAddress.with_type (path, -1, type);
|
||||
}
|
||||
#endif
|
||||
|
||||
private SocketConnectable parse_frida_address (string? address, uint16 port, uint16 default_port) throws Error {
|
||||
try {
|
||||
return NetworkAddress.parse (address, port);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("%s", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
namespace UnixSocket {
|
||||
public extern void tune_buffer_sizes (int fd);
|
||||
}
|
||||
|
||||
namespace Tcp {
|
||||
public extern void enable_nodelay (Socket socket);
|
||||
}
|
||||
|
||||
namespace Udp {
|
||||
public size_t recv (uint8[] data, DatagramBased source, Cancellable? cancellable, out InetSocketAddress remote_address)
|
||||
throws Error, IOError {
|
||||
var v = InputVector ();
|
||||
v.buffer = data;
|
||||
v.size = data.length;
|
||||
|
||||
InputVector[] vectors = { v };
|
||||
|
||||
var m = InputMessage ();
|
||||
remote_address = null;
|
||||
m.address = &remote_address;
|
||||
m.vectors = vectors;
|
||||
m.num_vectors = vectors.length;
|
||||
|
||||
InputMessage[] messages = { m };
|
||||
|
||||
try {
|
||||
source.receive_messages (messages, 0, 0, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.TRANSPORT ("%s", e.message);
|
||||
}
|
||||
|
||||
return messages[0].bytes_received;
|
||||
}
|
||||
|
||||
public void send (uint8[] data, DatagramBased sink, Cancellable? cancellable) throws Error, IOError {
|
||||
send_to (data, null, sink, cancellable);
|
||||
}
|
||||
|
||||
public void send_to (uint8[] data, InetSocketAddress? dest_addr, DatagramBased sink, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
var v = OutputVector ();
|
||||
v.buffer = data;
|
||||
v.size = data.length;
|
||||
|
||||
OutputVector[] vectors = { v };
|
||||
|
||||
var m = OutputMessage ();
|
||||
m.address = dest_addr;
|
||||
m.vectors = vectors;
|
||||
m.num_vectors = vectors.length;
|
||||
|
||||
OutputMessage[] messages = { m };
|
||||
|
||||
try {
|
||||
sink.send_messages (messages, 0, 0, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.TRANSPORT ("%s", e.message);
|
||||
}
|
||||
return Efni.parse_socket_address (address, port, "127.0.0.1", default_port);
|
||||
} catch (Efni.Error e) {
|
||||
throw error_from_efni (e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1117,6 +1040,9 @@ namespace Frida {
|
||||
construct {
|
||||
websocket.max_incoming_payload_size = (256 * 1024) + 1; // XXX: There's an off-by-one error in libsoup
|
||||
|
||||
if (websocket.get_class ().find_property ("max-total-message-size") != null)
|
||||
websocket.set ("max-total-message-size", websocket.max_incoming_payload_size);
|
||||
|
||||
websocket.closed.connect (on_closed);
|
||||
websocket.message.connect (on_message);
|
||||
}
|
||||
@@ -1166,7 +1092,7 @@ namespace Frida {
|
||||
|
||||
if (recv_queue.len == 0) {
|
||||
#if HAVE_SOUP_WEBSOCKET_BACKPRESSURE
|
||||
websocket.resume_input ();
|
||||
resume_websocket_input ();
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1183,6 +1109,21 @@ namespace Frida {
|
||||
return n;
|
||||
}
|
||||
|
||||
#if HAVE_SOUP_WEBSOCKET_BACKPRESSURE
|
||||
private void resume_websocket_input () {
|
||||
if (main_context.is_owner ()) {
|
||||
websocket.resume_input ();
|
||||
} else {
|
||||
var source = new IdleSource ();
|
||||
source.set_callback (() => {
|
||||
websocket.resume_input ();
|
||||
return Source.REMOVE;
|
||||
});
|
||||
source.attach (main_context);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
public override ssize_t write (uint8[] buffer) {
|
||||
with_state_lock (() => {
|
||||
send_queue.append (buffer);
|
||||
|
||||
@@ -1,336 +0,0 @@
|
||||
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 ();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,432 +0,0 @@
|
||||
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 string[] list_members () throws Error {
|
||||
var scope = peek_scope ();
|
||||
if (scope.dict == null)
|
||||
throw new Error.PROTOCOL ("Dictionary expected, but at %s", scope.val.print (true));
|
||||
|
||||
var members = new Gee.ArrayList<string> ();
|
||||
foreach (var item in scope.val) {
|
||||
string k;
|
||||
Variant v;
|
||||
item.get ("{sv}", out k, out v);
|
||||
|
||||
members.add (k);
|
||||
}
|
||||
return members.to_array ();
|
||||
}
|
||||
|
||||
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 = make_json_reader (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);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Constructs a Json.Reader for the given JSON string, working around the
|
||||
* json_node_copy() bug in unpatched json-glib (GNOME bugzilla #774684).
|
||||
*
|
||||
* Json.Reader's set_root() copies the supplied node via json_node_copy().
|
||||
* For object/array nodes that copy is a thin shell that shares the original
|
||||
* JsonObject/JsonArray via refcount, but the members inside the shared
|
||||
* container have their parent pointers set to the *original* root, not the
|
||||
* shell. If the original is then dropped, json_reader_end_member()'s walk
|
||||
* via json_node_get_parent() touches a freed node — which on builds with
|
||||
* glib checks enabled (e.g. Fedora) trips JSON_NODE_IS_VALID and aborts.
|
||||
*
|
||||
* We keep the original root alive by attaching it to the reader as object
|
||||
* data; the destroy notify drops our reference when the reader is finalized.
|
||||
*/
|
||||
public Json.Reader make_json_reader (string json) throws GLib.Error {
|
||||
return make_json_reader_taking_node (Json.from_string (json));
|
||||
}
|
||||
|
||||
public Json.Reader make_json_reader_taking_node (owned Json.Node root) {
|
||||
var reader = new Json.Reader (root);
|
||||
reader.set_data<Json.Node> ("frida-json-root", (owned) root);
|
||||
return reader;
|
||||
}
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida.Gadget {
|
||||
private sealed class Config : Object, Json.Serializable {
|
||||
public Object interaction {
|
||||
|
||||
@@ -8,7 +8,6 @@ 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'
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
public abstract class BaseAgentSession : Object, AgentSession {
|
||||
public signal void closed ();
|
||||
|
||||
+26
-20
@@ -215,6 +215,7 @@ static void frida_stdio_unregister_stream (FILE * stream);
|
||||
static void frida_stdio_register_dir (DIR * dirp);
|
||||
static void frida_stdio_unregister_dir (DIR * dirp);
|
||||
#endif
|
||||
static void frida_stdio_ensure_registries (void);
|
||||
static void frida_flush_all_streams (int * result);
|
||||
|
||||
static FridaFile * frida_file_get_impl (FILE * stream);
|
||||
@@ -252,7 +253,13 @@ static ssize_t frida_write_nointr (int fd, const void * buf, size_t count);
|
||||
static int frida_close_nointr (int fd);
|
||||
static off_t frida_lseek_nointr (int fd, off_t offset, int whence);
|
||||
|
||||
#ifndef FRIDA_STDIO_OPAQUE_FILE
|
||||
#if defined (HAVE_QNX)
|
||||
G_GNUC_INTERNAL FILE _Stdin, _Stdout, _Stderr;
|
||||
|
||||
G_GNUC_INTERNAL FILE * stdin = &_Stdin;
|
||||
G_GNUC_INTERNAL FILE * stdout = &_Stdout;
|
||||
G_GNUC_INTERNAL FILE * stderr = &_Stderr;
|
||||
#elif !defined (FRIDA_STDIO_OPAQUE_FILE)
|
||||
G_GNUC_INTERNAL FILE __sF[3];
|
||||
|
||||
G_GNUC_INTERNAL FILE * stdin = &__sF[0];
|
||||
@@ -302,33 +309,18 @@ frida_libc_shim_init (void)
|
||||
|
||||
G_LOCK (frida_stdio);
|
||||
|
||||
frida_streams = g_hash_table_new (g_direct_hash, g_direct_equal);
|
||||
#ifdef HAVE_FRIDA_DIR
|
||||
frida_dirs = g_hash_table_new (g_direct_hash, g_direct_equal);
|
||||
#endif
|
||||
frida_stdio_ensure_registries ();
|
||||
|
||||
G_UNLOCK (frida_stdio);
|
||||
|
||||
f0 = frida_file_new (0, FALSE, _IOFBF);
|
||||
#ifndef FRIDA_STDIO_OPAQUE_FILE
|
||||
frida_file_bind_slot (&__sF[0], f0);
|
||||
#else
|
||||
frida_file_bind_slot ((FILE *) &frida_stdio[0], f0);
|
||||
#endif
|
||||
frida_file_bind_slot (stdin, f0);
|
||||
|
||||
f1 = frida_file_new (1, FALSE, _IOLBF);
|
||||
#ifndef FRIDA_STDIO_OPAQUE_FILE
|
||||
frida_file_bind_slot (&__sF[1], f1);
|
||||
#else
|
||||
frida_file_bind_slot ((FILE *) &frida_stdio[1], f1);
|
||||
#endif
|
||||
frida_file_bind_slot (stdout, f1);
|
||||
|
||||
f2 = frida_file_new (2, FALSE, _IONBF);
|
||||
#ifndef FRIDA_STDIO_OPAQUE_FILE
|
||||
frida_file_bind_slot (&__sF[2], f2);
|
||||
#else
|
||||
frida_file_bind_slot ((FILE *) &frida_stdio[2], f2);
|
||||
#endif
|
||||
frida_file_bind_slot (stderr, f2);
|
||||
|
||||
frida_libc_shim_initialized = TRUE;
|
||||
}
|
||||
@@ -1905,6 +1897,7 @@ frida_stdio_register_stream (FILE * stream)
|
||||
{
|
||||
G_LOCK (frida_stdio);
|
||||
|
||||
frida_stdio_ensure_registries ();
|
||||
g_hash_table_add (frida_streams, stream);
|
||||
|
||||
G_UNLOCK (frida_stdio);
|
||||
@@ -1927,6 +1920,7 @@ frida_stdio_register_dir (DIR * dirp)
|
||||
{
|
||||
G_LOCK (frida_stdio);
|
||||
|
||||
frida_stdio_ensure_registries ();
|
||||
g_hash_table_add (frida_dirs, dirp);
|
||||
|
||||
G_UNLOCK (frida_stdio);
|
||||
@@ -1944,6 +1938,18 @@ frida_stdio_unregister_dir (DIR * dirp)
|
||||
|
||||
#endif
|
||||
|
||||
static void
|
||||
frida_stdio_ensure_registries (void)
|
||||
{
|
||||
if (frida_streams != NULL)
|
||||
return;
|
||||
|
||||
frida_streams = g_hash_table_new (g_direct_hash, g_direct_equal);
|
||||
#ifdef HAVE_FRIDA_DIR
|
||||
frida_dirs = g_hash_table_new (g_direct_hash, g_direct_equal);
|
||||
#endif
|
||||
}
|
||||
|
||||
static void
|
||||
frida_flush_all_streams (int * result)
|
||||
{
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
public sealed class PortalClient : Object, AgentSessionProvider {
|
||||
public signal void resume ();
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
public extern void libc_shim_prepare_to_deinit ();
|
||||
#if DARWIN
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
public sealed class ScriptEngine : Object {
|
||||
public signal void message_from_script (AgentScriptId script_id, string json, Bytes? data);
|
||||
|
||||
@@ -34,7 +34,7 @@ struct _FridaCreateArgs
|
||||
|
||||
static FridaDyldUnwindSections * frida_get_cached_sections (GumAddress range_start, GumAddress range_end);
|
||||
static FridaDyldUnwindSections * frida_create_cached_sections (FridaCreateArgs * args);
|
||||
static gboolean frida_fill_info (const GumDarwinSectionDetails * details, FridaFillInfoContext * ctx);
|
||||
static gboolean frida_fill_info (const GumMachoSectionDetails * details, FridaFillInfoContext * ctx);
|
||||
|
||||
void
|
||||
_frida_unwind_sitter_fill_unwind_sections (GumAddress invader_start, GumAddress invader_end, void * info)
|
||||
@@ -70,7 +70,7 @@ frida_create_cached_sections (FridaCreateArgs * args)
|
||||
gsize page_size;
|
||||
gpointer header;
|
||||
GumPageProtection prot;
|
||||
GumDarwinModule * module;
|
||||
GumMachoModule * module;
|
||||
FridaFillInfoContext ctx;
|
||||
|
||||
page_size = gum_query_page_size ();
|
||||
@@ -87,14 +87,14 @@ frida_create_cached_sections (FridaCreateArgs * args)
|
||||
cached_sections = g_slice_new0 (FridaDyldUnwindSections);
|
||||
cached_sections->mh = header;
|
||||
|
||||
module = gum_darwin_module_new_from_memory ("Frida", mach_task_self (), GPOINTER_TO_SIZE (header),
|
||||
GUM_DARWIN_MODULE_FLAGS_NONE, NULL);
|
||||
module = gum_macho_module_new_from_memory ("Frida", mach_task_self (), GPOINTER_TO_SIZE (header),
|
||||
GUM_MACHO_MODULE_FLAGS_NONE, NULL);
|
||||
if (module == NULL)
|
||||
return cached_sections;
|
||||
|
||||
ctx.info = cached_sections;
|
||||
ctx.missing_info = 2;
|
||||
gum_darwin_module_enumerate_sections (module, (GumFoundDarwinSectionFunc) frida_fill_info, &ctx);
|
||||
gum_macho_module_enumerate_sections (module, (GumFoundMachoSectionFunc) frida_fill_info, &ctx);
|
||||
|
||||
g_object_unref (module);
|
||||
|
||||
@@ -102,7 +102,7 @@ frida_create_cached_sections (FridaCreateArgs * args)
|
||||
}
|
||||
|
||||
static gboolean
|
||||
frida_fill_info (const GumDarwinSectionDetails * details, FridaFillInfoContext * ctx)
|
||||
frida_fill_info (const GumMachoSectionDetails * details, FridaFillInfoContext * ctx)
|
||||
{
|
||||
if (strcmp ("__TEXT", details->segment_name) != 0)
|
||||
return TRUE;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "pipe-glue.h"
|
||||
|
||||
#include <efni.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
@@ -66,7 +67,7 @@ _frida_pipe_transport_create_backend (gchar ** local_address, gchar ** remote_ad
|
||||
|
||||
fcntl (fd, F_SETFD, FD_CLOEXEC);
|
||||
setsockopt (fd, SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, sizeof (no_sigpipe));
|
||||
frida_unix_socket_tune_buffer_sizes (fd);
|
||||
efni_unix_socket_tune_buffer_sizes (fd);
|
||||
}
|
||||
|
||||
status = fileport_makeport (sockets[0], &local_wrapper);
|
||||
|
||||
+3
-1
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
public sealed class PipeTransport : Object {
|
||||
public string local_address {
|
||||
@@ -157,7 +159,7 @@ namespace Frida {
|
||||
UnixSocketAddressType type = UnixSocketAddress.abstract_names_supported ()
|
||||
? UnixSocketAddressType.ABSTRACT
|
||||
: UnixSocketAddressType.PATH;
|
||||
var server_address = new UnixSocketAddress.with_type (path, -1, type);
|
||||
var server_address = new UnixSocketAddress.with_type (path.to_utf8 (), type);
|
||||
|
||||
if (role == "server") {
|
||||
var socket = new Socket (SocketFamily.UNIX, SocketType.STREAM, SocketProtocol.DEFAULT);
|
||||
|
||||
+61
-49
@@ -14,7 +14,7 @@ if not meson.get_compiler('vala').version().endswith('-frida')
|
||||
Frida currently relies on features not yet upstream. Grab the Frida-optimized
|
||||
Vala sources from:
|
||||
|
||||
https://github.com/frida/vala
|
||||
https://github.com/frida-forks/vala
|
||||
|
||||
and compile them with Meson.''')
|
||||
endif
|
||||
@@ -349,9 +349,13 @@ glib_options = [
|
||||
'selinux=disabled',
|
||||
'xattr=false',
|
||||
'libmount=disabled',
|
||||
'sysprof=disabled',
|
||||
'tests=false',
|
||||
'nls=disabled',
|
||||
]
|
||||
if host_os_family in ['darwin', 'qnx', 'none'] or host_os == 'android' or libc == 'uclibc'
|
||||
glib_options += 'iconv=external'
|
||||
endif
|
||||
if optimize_for_prod
|
||||
glib_options += [
|
||||
'glib_debug=disabled',
|
||||
@@ -408,13 +412,27 @@ json_glib_dep = dependency('json-glib-1.0', version: '>=1.8', default_options: [
|
||||
'introspection=disabled',
|
||||
'gtk_doc=disabled',
|
||||
'tests=false',
|
||||
'nls=disabled',
|
||||
])
|
||||
efni_dep = dependency('efni-1.0', default_options: ['default_library=static'])
|
||||
efni_libs = []
|
||||
if efni_dep.type_name() == 'internal'
|
||||
efni_libs += subproject('efni').get_variable('efni')
|
||||
endif
|
||||
efni_vapidir = efni_dep.get_variable('vapidir', default_value: '')
|
||||
if efni_vapidir != ''
|
||||
vala_flags += '--vapidir=' + efni_vapidir
|
||||
endif
|
||||
foreach pkg : efni_dep.get_variable('vala_packages', default_value: '').split()
|
||||
vala_flags += '--pkg=' + pkg
|
||||
endforeach
|
||||
libsoup_dep = dependency('libsoup-3.0', default_options: [
|
||||
'default_library=static',
|
||||
'sqlite:default_library=static',
|
||||
'gssapi=disabled',
|
||||
'ntlm=disabled',
|
||||
'brotli=disabled',
|
||||
'zstd=disabled',
|
||||
'tls_check=false',
|
||||
'introspection=disabled',
|
||||
'vapi=disabled',
|
||||
@@ -428,7 +446,13 @@ if libsoup_dep.type_name() == 'internal' \
|
||||
vala_flags += '--define=HAVE_SOUP_WEBSOCKET_BACKPRESSURE'
|
||||
endif
|
||||
brotlidec_dep = dependency('libbrotlidec', default_options: ['default_library=static'])
|
||||
capstone_dep = dependency('capstone', default_options: ['default_library=static'])
|
||||
capstone_dep = dependency('capstone', default_options: [
|
||||
'default_library=static',
|
||||
'archs=all',
|
||||
'use_arch_registration=true',
|
||||
'x86_att_disable=true',
|
||||
'cli=disabled',
|
||||
])
|
||||
if capstone_dep.type_name() != 'internal' \
|
||||
and not cc.has_function('cs_arch_register_x86', dependencies: [capstone_dep])
|
||||
add_project_arguments(
|
||||
@@ -442,9 +466,9 @@ endif
|
||||
quickjs_dep = dependency('quickjs', required: get_option('barebone_backend'), default_options: [
|
||||
'default_library=static',
|
||||
'libc=false',
|
||||
'bignum=true',
|
||||
'atomics=disabled',
|
||||
'stack_check=disabled',
|
||||
'stack_check=' + ((host_os_family == 'none') ? 'enabled' : 'disabled'),
|
||||
'stack_mode=' + ((host_os_family == 'none') ? 'optimize' : 'default'),
|
||||
])
|
||||
lzfse_dep = dependency('lzfse', required: false, default_options: ['default_library=static'])
|
||||
lzfse_from_system = false
|
||||
@@ -480,6 +504,7 @@ endif
|
||||
|
||||
if host_os == 'android'
|
||||
minizip_dep = dependency('minizip', required: false, default_options: [
|
||||
'default_library=static',
|
||||
'zlib=enabled',
|
||||
'lzma=disabled',
|
||||
])
|
||||
@@ -573,7 +598,11 @@ if compiler_backend_opt.allowed()
|
||||
have_compiler_backend = true
|
||||
cdata.set('HAVE_COMPILER_BACKEND', 1)
|
||||
compiler_backend_mode = lines[1]
|
||||
go_config = lines[2]
|
||||
go_config = configure_file(
|
||||
input: 'tools' / 'cgo' / 'go-config.json.in',
|
||||
output: 'go-config.json',
|
||||
configuration: {'GO_CONFIG': lines[2]},
|
||||
)
|
||||
|
||||
if compiler_backend_mode == 'c-archive'
|
||||
vala_flags += '--define=COMPILER_BACKEND_LINKED'
|
||||
@@ -697,54 +726,32 @@ 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(),
|
||||
required: get_option('connectivity').enabled(),
|
||||
modules: cc.get_argument_syntax() == 'msvc' ? ['OpenSSL::SSL'] : [],
|
||||
default_options: openssl_options,
|
||||
)
|
||||
|
||||
idun_libs = []
|
||||
have_idund_blob = false
|
||||
if have_fruity_backend
|
||||
backend_deps_private += dependency('libnghttp2', default_options: ['default_library=static'])
|
||||
backend_reqs_private += 'libnghttp2'
|
||||
|
||||
if host_os != 'macos'
|
||||
backend_deps_private += dependency('libngtcp2', default_options: ['default_library=static'])
|
||||
backend_reqs_private += 'libngtcp2'
|
||||
|
||||
ngtcp2_crypto_quictls_dep = dependency('libngtcp2_crypto_quictls', required: false, default_options: ['default_library=static'])
|
||||
if ngtcp2_crypto_quictls_dep.found()
|
||||
backend_deps_private += ngtcp2_crypto_quictls_dep
|
||||
backend_reqs_private += 'libngtcp2_crypto_quictls'
|
||||
else
|
||||
backend_deps_private += dependency('libngtcp2_crypto_ossl', default_options: ['default_library=static'])
|
||||
backend_reqs_private += 'libngtcp2_crypto_ossl'
|
||||
vala_flags += '--define=HAVE_NGTCP2_CRYPTO_OSSL'
|
||||
idun_dep = dependency('idun-1.0', default_options: ['default_library=static'])
|
||||
backend_reqs_private += 'idun-1.0'
|
||||
if idun_dep.type_name() == 'internal'
|
||||
idun_sp = subproject('idun')
|
||||
idun_libs += idun_sp.get_variable('idun')
|
||||
if assets_mode == 'embedded' and idun_sp.get_variable('build_daemon')
|
||||
idund_raw = idun_sp.get_variable('idund')
|
||||
have_idund_blob = true
|
||||
vala_flags += '--define=HAVE_IDUND_BLOB'
|
||||
endif
|
||||
|
||||
if have_frida_glib
|
||||
libusb_dep = dependency('libusb-1.0', default_options: ['default_library=static'])
|
||||
else
|
||||
subproject('libusb', default_options: ['default_library=static'])
|
||||
libusb_dep = dependency('libusb-1.0', default_options: ['default_library=static'])
|
||||
endif
|
||||
backend_deps_private += libusb_dep
|
||||
backend_reqs_private += 'libusb-1.0'
|
||||
|
||||
lwip_options = [
|
||||
'default_library=static',
|
||||
'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
|
||||
idun_vapidir = idun_dep.get_variable('vapidir', default_value: '')
|
||||
if idun_vapidir != ''
|
||||
vala_flags += '--vapidir=' + idun_vapidir
|
||||
endif
|
||||
foreach pkg : idun_dep.get_variable('vala_packages', default_value: '').split()
|
||||
vala_flags += '--pkg=' + pkg
|
||||
endforeach
|
||||
endif
|
||||
|
||||
if quickjs_dep.found()
|
||||
@@ -774,8 +781,12 @@ endif
|
||||
|
||||
if host_os == 'android'
|
||||
termux_elf_cleaner = find_program('termux-elf-cleaner', native: true)
|
||||
libselinux_dep = dependency('libselinux', version: '>=3.0', default_options: ['default_library=static'])
|
||||
libsepol_dep = dependency('libsepol', version: '>=3.0', default_options: ['default_library=static'])
|
||||
selinux_options = [
|
||||
'default_library=static',
|
||||
'regex=disabled',
|
||||
]
|
||||
libselinux_dep = dependency('libselinux', version: '>=3.0', default_options: selinux_options)
|
||||
libsepol_dep = dependency('libsepol', version: '>=3.0', default_options: selinux_options)
|
||||
backend_deps_private += [libselinux_dep, libsepol_dep]
|
||||
backend_reqs_private += ['libselinux', 'libsepol']
|
||||
else
|
||||
@@ -979,12 +990,13 @@ compile_js_agent = files('tools' / 'compile-js-agent.py')
|
||||
|
||||
mapper_opt = get_option('mapper')
|
||||
if mapper_opt.auto()
|
||||
have_mapper = host_os_family == 'darwin'
|
||||
have_mapper = host_os_family in ['windows', 'darwin', 'linux']
|
||||
else
|
||||
have_mapper = mapper_opt.enabled()
|
||||
endif
|
||||
if have_mapper
|
||||
cdata.set('HAVE_MAPPER', 1)
|
||||
vala_flags += '--define=HAVE_MAPPER'
|
||||
endif
|
||||
|
||||
configure_file(
|
||||
|
||||
+1
-1
Submodule releng updated: 1089fe24c2...164a6a4117.
@@ -359,5 +359,11 @@
|
||||
<true/>
|
||||
<key>com.apple.private.amfi.can-execute-cdhash</key>
|
||||
<true/>
|
||||
<key>com.apple.private.FairPlayIOKitUserClient.access</key>
|
||||
<true/>
|
||||
<key>com.apple.security.iokit-user-client-class</key>
|
||||
<array>
|
||||
<string>com_apple_driver_FairPlayIOKitUserClient</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida.Server {
|
||||
private static Application application;
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
[CCode (gir_namespace = "FridaDroidy", gir_version = "1.0")]
|
||||
namespace Frida.Droidy {
|
||||
public sealed class DeviceTracker : Object {
|
||||
public signal void device_attached (DeviceDetails details);
|
||||
using Efni;
|
||||
|
||||
[CCode (gir_namespace = "FridaAdb", gir_version = "1.0")]
|
||||
namespace Frida {
|
||||
public sealed class AdbDeviceTracker : Object {
|
||||
public signal void device_attached (AdbDeviceDetails details);
|
||||
public signal void device_detached (string serial);
|
||||
|
||||
private Client? client;
|
||||
private AdbClient? client;
|
||||
private Gee.HashMap<string, DeviceEntry> devices = new Gee.HashMap<string, DeviceEntry> ();
|
||||
private Cancellable io_cancellable = new Cancellable ();
|
||||
|
||||
public async void open (Cancellable? cancellable = null) throws Error, IOError {
|
||||
client = yield Client.open (cancellable);
|
||||
client = yield AdbClient.open (cancellable);
|
||||
client.message.connect (on_message);
|
||||
|
||||
try {
|
||||
@@ -20,7 +22,7 @@ namespace Frida.Droidy {
|
||||
client.message.disconnect (on_message);
|
||||
client = null;
|
||||
|
||||
client = yield Client.open (cancellable);
|
||||
client = yield AdbClient.open (cancellable);
|
||||
var devices_encoded = yield client.request_data ("host:track-devices", cancellable);
|
||||
yield update_devices (devices_encoded, cancellable);
|
||||
}
|
||||
@@ -117,12 +119,12 @@ namespace Frida.Droidy {
|
||||
var still_attached = devices.has_key (entry.serial);
|
||||
if (still_attached) {
|
||||
entry.announced = true;
|
||||
device_attached (new DeviceDetails (entry.serial, entry.name));
|
||||
device_attached (new AdbDeviceDetails (entry.serial, entry.name));
|
||||
}
|
||||
}
|
||||
|
||||
private async string detect_name (string device_serial, Cancellable? cancellable) throws Error, IOError {
|
||||
var output = yield ShellCommand.run ("getprop ro.product.model", device_serial, cancellable);
|
||||
var output = yield AdbShellCommand.run ("getprop ro.product.model", device_serial, cancellable);
|
||||
return output.chomp ();
|
||||
}
|
||||
|
||||
@@ -149,7 +151,7 @@ namespace Frida.Droidy {
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class DeviceDetails : Object {
|
||||
public sealed class AdbDeviceDetails : Object {
|
||||
public string serial {
|
||||
get;
|
||||
construct;
|
||||
@@ -160,16 +162,16 @@ namespace Frida.Droidy {
|
||||
construct;
|
||||
}
|
||||
|
||||
public DeviceDetails (string serial, string name) {
|
||||
public AdbDeviceDetails (string serial, string name) {
|
||||
Object (serial: serial, name: name);
|
||||
}
|
||||
}
|
||||
|
||||
namespace ShellCommand {
|
||||
namespace AdbShellCommand {
|
||||
private const int CHUNK_SIZE = 4096;
|
||||
|
||||
public static async string run (string command, string device_serial, Cancellable? cancellable = null) throws Error, IOError {
|
||||
var client = yield Client.open (cancellable);
|
||||
var client = yield AdbClient.open (cancellable);
|
||||
|
||||
try {
|
||||
yield client.request ("host:transport:" + device_serial, cancellable);
|
||||
@@ -205,8 +207,8 @@ namespace Frida.Droidy {
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ShellSession : Object {
|
||||
public signal void output (StdioPipe pipe, Bytes bytes);
|
||||
public sealed class AdbShellSession : Object {
|
||||
public signal void output (AdbStdioPipe pipe, Bytes bytes);
|
||||
public signal void closed ();
|
||||
|
||||
private IOStream stream;
|
||||
@@ -232,7 +234,7 @@ namespace Frida.Droidy {
|
||||
public async void open (string device_serial, Cancellable? cancellable = null) throws Error, IOError {
|
||||
assert (state == CLOSED);
|
||||
|
||||
var client = yield Client.open (cancellable);
|
||||
var client = yield AdbClient.open (cancellable);
|
||||
|
||||
try {
|
||||
yield client.request ("host:transport:" + device_serial, cancellable);
|
||||
@@ -285,7 +287,7 @@ namespace Frida.Droidy {
|
||||
return result.stdout_text;
|
||||
}
|
||||
|
||||
public async ShellCommandResult run (string command, Cancellable? cancellable) throws Error, IOError {
|
||||
public async AdbShellCommandResult run (string command, Cancellable? cancellable) throws Error, IOError {
|
||||
if (state == CLOSED)
|
||||
throw new Error.INVALID_OPERATION ("Shell session is closed");
|
||||
|
||||
@@ -524,7 +526,7 @@ namespace Frida.Droidy {
|
||||
public string command;
|
||||
private SourceFunc? handler;
|
||||
|
||||
public ShellCommandResult? result;
|
||||
public AdbShellCommandResult? result;
|
||||
public GLib.Error? error;
|
||||
|
||||
public ByteArray stdout_buffer = new ByteArray ();
|
||||
@@ -550,7 +552,7 @@ namespace Frida.Droidy {
|
||||
Bytes stdout_bytes = new Bytes.take ((owned) stdout_terminated);
|
||||
Bytes stderr_bytes = new Bytes.take ((owned) stderr_terminated);
|
||||
|
||||
result = new ShellCommandResult (status, stdout_bytes, stderr_bytes);
|
||||
result = new AdbShellCommandResult (status, stdout_bytes, stderr_bytes);
|
||||
|
||||
handler ();
|
||||
handler = null;
|
||||
@@ -589,12 +591,12 @@ namespace Frida.Droidy {
|
||||
}
|
||||
}
|
||||
|
||||
public enum StdioPipe {
|
||||
public enum AdbStdioPipe {
|
||||
STDOUT,
|
||||
STDERR
|
||||
}
|
||||
|
||||
public sealed class ShellCommandResult : Object {
|
||||
public sealed class AdbShellCommandResult : Object {
|
||||
public uint8 status {
|
||||
get;
|
||||
construct;
|
||||
@@ -622,7 +624,7 @@ namespace Frida.Droidy {
|
||||
construct;
|
||||
}
|
||||
|
||||
public ShellCommandResult (uint8 status, Bytes stdout_bytes, Bytes stderr_bytes) {
|
||||
public AdbShellCommandResult (uint8 status, Bytes stdout_bytes, Bytes stderr_bytes) {
|
||||
Object (
|
||||
status: status,
|
||||
stdout_bytes: stdout_bytes,
|
||||
@@ -631,12 +633,12 @@ namespace Frida.Droidy {
|
||||
}
|
||||
}
|
||||
|
||||
namespace FileSync {
|
||||
namespace AdbFileSync {
|
||||
private const size_t MAX_DATA_SIZE = 65536;
|
||||
|
||||
public static async void send (InputStream content, FileMetadata metadata, string remote_path, string device_serial,
|
||||
public static async void send (InputStream content, AdbFileMetadata metadata, string remote_path, string device_serial,
|
||||
Cancellable? cancellable = null) throws Error, IOError {
|
||||
var client = yield Client.open (cancellable);
|
||||
var client = yield AdbClient.open (cancellable);
|
||||
|
||||
try {
|
||||
yield client.request ("host:transport:" + device_serial, cancellable);
|
||||
@@ -686,7 +688,7 @@ namespace Frida.Droidy {
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class FileMetadata : Object {
|
||||
public sealed class AdbFileMetadata : Object {
|
||||
public uint32 mode {
|
||||
get;
|
||||
set;
|
||||
@@ -700,16 +702,16 @@ namespace Frida.Droidy {
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class JDWPTracker : Object {
|
||||
public sealed class AdbJDWPTracker : Object {
|
||||
public signal void debugger_attached (uint pid);
|
||||
public signal void debugger_detached (uint pid);
|
||||
|
||||
private Client? client;
|
||||
private AdbClient? client;
|
||||
private Gee.HashSet<uint> debugger_pids = new Gee.HashSet<uint> ();
|
||||
private Cancellable io_cancellable = new Cancellable ();
|
||||
|
||||
public async void open (string device_serial, Cancellable? cancellable = null) throws Error, IOError {
|
||||
client = yield Client.open (cancellable);
|
||||
client = yield AdbClient.open (cancellable);
|
||||
client.message.connect (on_message);
|
||||
|
||||
try {
|
||||
@@ -768,7 +770,7 @@ namespace Frida.Droidy {
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class Client : Object {
|
||||
public sealed class AdbClient : Object {
|
||||
public signal void closed ();
|
||||
public signal void message (string payload);
|
||||
|
||||
@@ -793,7 +795,7 @@ namespace Frida.Droidy {
|
||||
private const uint16 ADB_SERVER_DEFAULT_PORT = 5037;
|
||||
private const size_t MAX_MESSAGE_LENGTH = 65536;
|
||||
|
||||
public static async Client open (Cancellable? cancellable = null) throws Error, IOError {
|
||||
public static async AdbClient open (Cancellable? cancellable = null) throws Error, IOError {
|
||||
SocketConnectable? connectable = null;
|
||||
string? env_socket_address = Environment.get_variable ("ADB_SERVER_SOCKET");
|
||||
string? env_server_address = Environment.get_variable ("ANDROID_ADB_SERVER_ADDRESS");
|
||||
@@ -813,7 +815,7 @@ namespace Frida.Droidy {
|
||||
else if (socket_type == "local" || socket_type == "localfilesystem") {
|
||||
connectable = new UnixSocketAddress (socket_address);
|
||||
} else if (socket_type == "localabstract" && UnixSocketAddress.abstract_names_supported ()) {
|
||||
connectable = new UnixSocketAddress.with_type (socket_address, socket_address.length,
|
||||
connectable = new UnixSocketAddress.with_type (socket_address.to_utf8 (),
|
||||
ABSTRACT_PADDED);
|
||||
}
|
||||
#endif
|
||||
@@ -847,10 +849,10 @@ namespace Frida.Droidy {
|
||||
throw new Error.NOT_SUPPORTED ("%s", e.message);
|
||||
}
|
||||
|
||||
return new Client (stream);
|
||||
return new AdbClient (stream);
|
||||
}
|
||||
|
||||
public Client (IOStream stream) {
|
||||
public AdbClient (IOStream stream) {
|
||||
Object (stream: stream);
|
||||
}
|
||||
|
||||
@@ -896,10 +898,10 @@ namespace Frida.Droidy {
|
||||
yield request_with_type (message, RequestType.PROTOCOL_CHANGE, cancellable);
|
||||
}
|
||||
|
||||
public async SyncSession request_sync_session (Cancellable? cancellable = null) throws Error, IOError {
|
||||
public async AdbSyncSession request_sync_session (Cancellable? cancellable = null) throws Error, IOError {
|
||||
yield request ("sync:", cancellable);
|
||||
|
||||
var session = new SyncSession (this);
|
||||
var session = new AdbSyncSession (this);
|
||||
|
||||
PendingResponse pending = null;
|
||||
pending = new PendingResponse (RequestType.SYNC, () => {
|
||||
@@ -1154,15 +1156,15 @@ namespace Frida.Droidy {
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SyncSession : Object {
|
||||
public Client client {
|
||||
public sealed class AdbSyncSession : Object {
|
||||
public AdbClient client {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
private Promise<bool> io_request = new Promise<bool> ();
|
||||
|
||||
public SyncSession (Client client) {
|
||||
public AdbSyncSession (AdbClient client) {
|
||||
Object (client: client);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
public sealed class AgentContainer : Object, AgentSessionProvider {
|
||||
public DBusConnection connection {
|
||||
@@ -9,9 +11,7 @@ namespace Frida {
|
||||
[CCode (has_target = false)]
|
||||
private delegate void AgentMainFunc (string data, ref UnloadPolicy unload_policy, void * injector_state);
|
||||
private AgentMainFunc main_impl;
|
||||
#if LINUX
|
||||
private FileDescriptor agent_ctrlfd_for_peer;
|
||||
#else
|
||||
#if !LINUX
|
||||
private PipeTransport transport;
|
||||
#endif
|
||||
private string transport_address;
|
||||
@@ -38,8 +38,7 @@ namespace Frida {
|
||||
if (Posix.socketpair (Posix.AF_UNIX, Posix.SOCK_STREAM, 0, agent_ctrlfds) != 0)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to allocate socketpair");
|
||||
var agent_ctrlfd = new FileDescriptor (agent_ctrlfds[0]);
|
||||
container.agent_ctrlfd_for_peer = new FileDescriptor (agent_ctrlfds[1]);
|
||||
container.transport_address = "";
|
||||
container.transport_address = "socket:%d".printf (agent_ctrlfds[1]);
|
||||
|
||||
try {
|
||||
Socket socket = new Socket.from_fd (agent_ctrlfd.handle);
|
||||
@@ -114,18 +113,10 @@ namespace Frida {
|
||||
|
||||
private bool run () {
|
||||
UnloadPolicy unload_policy = IMMEDIATE;
|
||||
void * injector_state = null;
|
||||
|
||||
#if LINUX
|
||||
var s = LinuxInjectorState ();
|
||||
s.frida_ctrlfd = -1;
|
||||
s.agent_ctrlfd = agent_ctrlfd_for_peer.steal ();
|
||||
injector_state = &s;
|
||||
#endif
|
||||
|
||||
string agent_parameters = transport_address + "|exit-monitor:off|thread-suspend-monitor:off";
|
||||
|
||||
main_impl (agent_parameters, ref unload_policy, injector_state);
|
||||
main_impl (agent_parameters, ref unload_policy, null);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
public sealed class AndroidHelperClient : Object {
|
||||
public AndroidHelperTransport transport {
|
||||
@@ -5,10 +7,92 @@ namespace Frida {
|
||||
construct;
|
||||
}
|
||||
|
||||
private AdbShellSession? shell;
|
||||
|
||||
public AndroidHelperClient (AndroidHelperTransport transport) {
|
||||
Object (transport: transport);
|
||||
}
|
||||
|
||||
public static async AndroidHelperClient open (string serial, Cancellable? cancellable) throws Error, IOError {
|
||||
string instance_id = Uuid.string_random ().replace ("-", "");
|
||||
string helper_path = "/data/local/tmp/frida-helper-" + instance_id + ".dex";
|
||||
|
||||
var helper_dex = new MemoryInputStream.from_bytes (
|
||||
new Bytes.static (Frida.Data.Android.get_helper_dex_blob ().data));
|
||||
var helper_meta = new AdbFileMetadata ();
|
||||
helper_meta.mode = 0100644;
|
||||
helper_meta.time_modified = new DateTime.now_utc ();
|
||||
yield AdbFileSync.send (helper_dex, helper_meta, helper_path, serial, cancellable);
|
||||
|
||||
var shell = new AdbShellSession ();
|
||||
try {
|
||||
var output = new StringBuilder ();
|
||||
bool waiting = false;
|
||||
var output_handler = shell.output.connect ((pipe, bytes) => {
|
||||
if (pipe == STDOUT) {
|
||||
output.append ((string) bytes.get_data ());
|
||||
if (waiting)
|
||||
open.callback ();
|
||||
}
|
||||
});
|
||||
try {
|
||||
yield shell.open (serial, cancellable);
|
||||
|
||||
shell.send_command (("CLASSPATH=%s app_process /data/local/tmp " +
|
||||
"--nice-name=re.frida.helper re.frida.Helper %s; rm -f %s; echo BYE.")
|
||||
.printf (helper_path, instance_id, helper_path));
|
||||
|
||||
while (!output.str.has_prefix ("READY.\n")) {
|
||||
waiting = true;
|
||||
yield;
|
||||
waiting = false;
|
||||
|
||||
if (output.str.has_prefix ("BYE.\n"))
|
||||
throw new Error.NOT_SUPPORTED ("Unable to start helper");
|
||||
}
|
||||
} finally {
|
||||
shell.disconnect (output_handler);
|
||||
}
|
||||
|
||||
var client = yield AdbClient.open (cancellable);
|
||||
try {
|
||||
yield client.request ("host:transport:" + serial, cancellable);
|
||||
yield client.request_protocol_change ("localabstract:/frida-helper-" + instance_id,
|
||||
cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
client.close.begin ();
|
||||
throw e;
|
||||
}
|
||||
|
||||
var helper = new AndroidHelperClient (new AndroidHelperStreamTransport (client.stream));
|
||||
helper.shell = shell;
|
||||
helper.transport.closed.connect (helper.release_shell);
|
||||
|
||||
return helper;
|
||||
} catch (GLib.Error e) {
|
||||
shell.close.begin ();
|
||||
if (e is IOError.CANCELLED)
|
||||
throw (IOError) e;
|
||||
throw new Error.NOT_SUPPORTED ("%s", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public async void close (Cancellable? cancellable) throws IOError {
|
||||
yield transport.close (cancellable);
|
||||
|
||||
if (shell != null) {
|
||||
yield shell.close (cancellable);
|
||||
shell = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void release_shell () {
|
||||
if (shell != null) {
|
||||
shell.close.begin ();
|
||||
shell = null;
|
||||
}
|
||||
}
|
||||
|
||||
public async HostApplicationInfo get_frontmost_application (FrontmostQueryOptions options,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
var stanza = new Json.Builder ();
|
||||
@@ -408,13 +492,13 @@ namespace Frida {
|
||||
}
|
||||
|
||||
public interface AndroidHelperTransport : Object {
|
||||
public signal void closed ();
|
||||
|
||||
public abstract async void close (Cancellable? cancellable) throws IOError;
|
||||
public abstract async Json.Node request (Json.Node stanza, Cancellable? cancellable) throws Error, IOError;
|
||||
}
|
||||
|
||||
public sealed class AndroidHelperStreamTransport : Object, AndroidHelperTransport {
|
||||
public signal void closed ();
|
||||
|
||||
public IOStream stream {
|
||||
get;
|
||||
construct;
|
||||
|
||||
Binary file not shown.
@@ -18,7 +18,6 @@ import android.graphics.drawable.Drawable;
|
||||
import android.os.Looper;
|
||||
import android.os.Process;
|
||||
import android.util.Base64;
|
||||
import android.util.Base64OutputStream;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
@@ -645,7 +644,7 @@ public class HelperBackend {
|
||||
"Unable to find application with identifier '" + pkgName + "'" +
|
||||
((uid != 0) ? " belonging to uid " + uid : ""));
|
||||
} catch (Throwable e) {
|
||||
return error("NOT_SUPPORTED", e.toString());
|
||||
return error("NOT_SUPPORTED", describe(e));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -697,10 +696,13 @@ public class HelperBackend {
|
||||
intent.setClassName(pkgName, activity);
|
||||
}
|
||||
|
||||
if (mStartActivityAsUser != null)
|
||||
startActivityViaAtm(intent, uid, pkgName);
|
||||
else
|
||||
startActivityViaAm(intent, uid, pkgName);
|
||||
String callingPackage = ourCallingPackage();
|
||||
|
||||
int code = (mStartActivityAsUser != null)
|
||||
? startActivityViaAtm(intent, uid, callingPackage)
|
||||
: startActivityViaAm(intent, uid, callingPackage);
|
||||
if (code < 0 || code > 3)
|
||||
return error("NOT_SUPPORTED", "Activity launch was refused (start code " + code + ")");
|
||||
|
||||
return okVoid();
|
||||
} catch (NameNotFoundException e) {
|
||||
@@ -708,11 +710,18 @@ public class HelperBackend {
|
||||
"Unable to find application with identifier '" + pkgName + "'" +
|
||||
((uid != 0) ? " belonging to uid " + uid : ""));
|
||||
} catch (Throwable e) {
|
||||
return error("NOT_SUPPORTED", e.toString());
|
||||
return error("NOT_SUPPORTED", describe(e));
|
||||
}
|
||||
}
|
||||
|
||||
private void startActivityViaAtm(Intent intent, int uid, String callingPackage) throws Exception {
|
||||
private String ourCallingPackage() {
|
||||
String[] packages = mPackageManager.getPackagesForUid(Process.myUid());
|
||||
if (packages != null && packages.length > 0)
|
||||
return packages[0];
|
||||
return "com.android.shell";
|
||||
}
|
||||
|
||||
private int startActivityViaAtm(Intent intent, int uid, String callingPackage) throws Exception {
|
||||
if (mStartActivityAsUser == null)
|
||||
throw new UnsupportedOperationException("startActivityAsUser unavailable");
|
||||
|
||||
@@ -729,10 +738,11 @@ public class HelperBackend {
|
||||
args[mStartActivityCallingPackageIndex] = callingPackage;
|
||||
args[mStartActivityUserIdIndex] = (uid != 0) ? uid : 0;
|
||||
|
||||
mStartActivityAsUser.invoke(mActivityTaskManager, args);
|
||||
Object result = mStartActivityAsUser.invoke(mActivityTaskManager, args);
|
||||
return (result instanceof Integer) ? (Integer) result : 0;
|
||||
}
|
||||
|
||||
private void startActivityViaAm(Intent intent, int uid, String callingPackage) throws Exception {
|
||||
private int startActivityViaAm(Intent intent, int uid, String callingPackage) throws Exception {
|
||||
if (mStartActivityLegacy == null)
|
||||
throw new UnsupportedOperationException("legacy startActivity unavailable");
|
||||
|
||||
@@ -753,7 +763,8 @@ public class HelperBackend {
|
||||
if (mLegacyStartUserIdIndex != -1)
|
||||
args[mLegacyStartUserIdIndex] = (uid != 0) ? uid : 0;
|
||||
|
||||
mStartActivityLegacy.invoke(mActivityManagerService, args);
|
||||
Object result = mStartActivityLegacy.invoke(mActivityManagerService, args);
|
||||
return (result instanceof Integer) ? (Integer) result : 0;
|
||||
}
|
||||
|
||||
private JSONArray sendBroadcast(JSONArray request) throws JSONException {
|
||||
@@ -782,7 +793,7 @@ public class HelperBackend {
|
||||
"Unable to find application with identifier '" + pkgName + "'" +
|
||||
((uid != 0) ? " belonging to uid " + uid : ""));
|
||||
} catch (Throwable e) {
|
||||
return error("NOT_SUPPORTED", e.toString());
|
||||
return error("NOT_SUPPORTED", describe(e));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -810,7 +821,7 @@ public class HelperBackend {
|
||||
"Unable to find application with identifier '" + pkgName + "'" +
|
||||
((uid != 0) ? " belonging to uid " + uid : ""));
|
||||
} catch (Throwable e) {
|
||||
return error("NOT_SUPPORTED", e.toString());
|
||||
return error("NOT_SUPPORTED", describe(e));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -837,7 +848,7 @@ public class HelperBackend {
|
||||
|
||||
return okBoolean(false);
|
||||
} catch (Throwable e) {
|
||||
return error("NOT_SUPPORTED", e.toString());
|
||||
return error("NOT_SUPPORTED", describe(e));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -869,6 +880,17 @@ public class HelperBackend {
|
||||
return r;
|
||||
}
|
||||
|
||||
private static String describe(Throwable t) {
|
||||
Throwable cause = t;
|
||||
while (cause instanceof InvocationTargetException && cause.getCause() != null)
|
||||
cause = cause.getCause();
|
||||
|
||||
String message = cause.getMessage();
|
||||
return (message != null)
|
||||
? cause.getClass().getName() + ": " + message
|
||||
: cause.getClass().getName();
|
||||
}
|
||||
|
||||
private String getFrontmostPackageName() {
|
||||
List<ActivityManager.RunningTaskInfo> tasks = mActivityManager.getRunningTasks(1);
|
||||
if (tasks.isEmpty()) {
|
||||
@@ -959,10 +981,10 @@ public class HelperBackend {
|
||||
icon.setBounds(0, 0, width, height);
|
||||
icon.draw(canvas);
|
||||
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
bitmap.compress(CompressFormat.PNG, 100, new Base64OutputStream(output, Base64.NO_WRAP));
|
||||
ByteArrayOutputStream png = new ByteArrayOutputStream();
|
||||
bitmap.compress(CompressFormat.PNG, 100, png);
|
||||
|
||||
return output.toString();
|
||||
return Base64.encodeToString(png.toByteArray(), Base64.NO_WRAP);
|
||||
}
|
||||
|
||||
private Map<String, List<RunningAppProcessInfo>> getAppProcesses() {
|
||||
|
||||
+1
-1
@@ -158,7 +158,7 @@ if is_shared
|
||||
else
|
||||
pkg_kwargs += {
|
||||
'libraries': core_public_lib,
|
||||
'requires_private': ['gmodule-2.0', 'gee-0.8', 'libsoup-3.0', 'frida-gum-1.0', 'frida-gumjs-inspector-1.0', 'libbrotlidec'] + backend_reqs_private,
|
||||
'requires_private': ['gmodule-2.0', 'gee-0.8', 'libsoup-3.0', 'efni-1.0', 'frida-gum-1.0', 'frida-gumjs-inspector-1.0', 'libbrotlidec'] + backend_reqs_private,
|
||||
'libraries_private': backend_libs_private,
|
||||
}
|
||||
endif
|
||||
|
||||
+143
-109
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public sealed class AgentConnection : Object, AsyncInitable {
|
||||
@@ -26,6 +28,7 @@ namespace Frida.Barebone {
|
||||
private uint64 kernel_base;
|
||||
private Machine machine;
|
||||
private Allocator allocator;
|
||||
private Allocator data_allocator;
|
||||
private Gee.List<ModuleInfo> kernel_modules;
|
||||
private Gee.List<SymbolInfo> kernel_symbols;
|
||||
private Gee.Map<string, uint64?> kernel_notes;
|
||||
@@ -39,9 +42,9 @@ namespace Frida.Barebone {
|
||||
private Allocation config_allocation;
|
||||
private Allocation? agent_stack;
|
||||
|
||||
private Promise<bool>? listening;
|
||||
private Efni.Promise<bool>? listening;
|
||||
|
||||
private Gee.Map<uint16, Promise<Variant>> pending_requests = new Gee.HashMap<uint16, Promise<Variant>> ();
|
||||
private Gee.Map<uint16, Efni.Promise<Variant>> pending_requests = new Gee.HashMap<uint16, Efni.Promise<Variant>> ();
|
||||
private uint16 next_request_id = 1;
|
||||
|
||||
private const size_t AGENT_STACK_SIZE = 512 * 1024;
|
||||
@@ -55,8 +58,8 @@ namespace Frida.Barebone {
|
||||
|
||||
public AgentConnection (BareboneInjectedAgentConfig agent_config, BareboneImageConfig? image_config,
|
||||
BareboneKernelKind kernel_kind, KernelRelocation? relocation, uint64 kernel_base, Machine machine,
|
||||
Allocator allocator, Gee.List<ModuleInfo> kernel_modules, Gee.List<SymbolInfo> kernel_symbols,
|
||||
Gee.Map<string, uint64?> kernel_notes) {
|
||||
Allocator allocator, Allocator? data_allocator, Gee.List<ModuleInfo> kernel_modules,
|
||||
Gee.List<SymbolInfo> kernel_symbols, Gee.Map<string, uint64?> kernel_notes) {
|
||||
this.agent_config = agent_config;
|
||||
this.image_config = image_config;
|
||||
this.kernel_kind = kernel_kind;
|
||||
@@ -64,16 +67,17 @@ namespace Frida.Barebone {
|
||||
this.kernel_base = kernel_base;
|
||||
this.machine = machine;
|
||||
this.allocator = allocator;
|
||||
this.data_allocator = data_allocator ?? allocator;
|
||||
this.kernel_modules = kernel_modules;
|
||||
this.kernel_symbols = kernel_symbols;
|
||||
this.kernel_notes = kernel_notes;
|
||||
}
|
||||
|
||||
public async void open (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void open (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
try {
|
||||
yield init_async (Priority.DEFAULT, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
throw_api_error (e);
|
||||
Efni.throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +86,7 @@ namespace Frida.Barebone {
|
||||
* transport with it, such as the Linux kernel module exposing /dev/frida.
|
||||
*/
|
||||
public static async AgentConnection open_resident (IOStream stream, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var connection = new AgentConnection.resident ();
|
||||
|
||||
connection.adopt_hostlink_streams (stream);
|
||||
@@ -103,7 +107,7 @@ namespace Frida.Barebone {
|
||||
private const uint8 TRANSPORT_KIND_PIPE_VSOCK = 4;
|
||||
private const uint8 TRANSPORT_KIND_PIPE_GOLDFISH = 5;
|
||||
|
||||
private async bool init_async (int io_priority, Cancellable? cancellable) throws Error, IOError {
|
||||
private async bool init_async (int io_priority, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
progress ("Preparing the agent", 0.0);
|
||||
|
||||
var transport_tag = yield resolve_transport (cancellable);
|
||||
@@ -171,12 +175,12 @@ namespace Frida.Barebone {
|
||||
KernelFlavor flavor;
|
||||
if (kind == XNU) {
|
||||
if (kernel_base == 0)
|
||||
throw new Error.NOT_SUPPORTED ("Missing kernel_base");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Missing kernel_base");
|
||||
flavor = new XnuKernelFlavor (machine, kernel_base, symbols);
|
||||
} else if (kind == LINUX) {
|
||||
if (kernel_base == 0)
|
||||
throw new Error.NOT_SUPPORTED ("Missing kernel_base");
|
||||
flavor = new LinuxKernelFlavor (machine, kernel_base, allocator, symbols);
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Missing kernel_base");
|
||||
flavor = new LinuxKernelFlavor (machine, kernel_base, symbols);
|
||||
} else if (kind == WIN9X) {
|
||||
flavor = new Win9xKernelFlavor (machine, symbols);
|
||||
} else if (kind == WINNT) {
|
||||
@@ -191,7 +195,7 @@ namespace Frida.Barebone {
|
||||
try {
|
||||
elf = new Gum.ElfModule.from_blob (agent_config.image);
|
||||
} catch (Gum.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("%s", e.message);
|
||||
throw new Efni.Error.INVALID_ARGUMENT ("%s", e.message);
|
||||
}
|
||||
|
||||
var raw_elf = debugger.make_buffer (new Bytes (elf.get_file_data ()));
|
||||
@@ -238,7 +242,7 @@ namespace Frida.Barebone {
|
||||
return true;
|
||||
});
|
||||
if (start_address == 0)
|
||||
throw new Error.INVALID_ARGUMENT ("Invalid agent: no _start symbol found");
|
||||
throw new Efni.Error.INVALID_ARGUMENT ("Invalid agent: no _start symbol found");
|
||||
|
||||
XnuLayout? xnu_layout = null;
|
||||
bool xnu_reads_its_own_processes = symbols.has_key ("proc_pid")
|
||||
@@ -296,12 +300,12 @@ namespace Frida.Barebone {
|
||||
config_builder.close ();
|
||||
|
||||
var config_blob = config_builder.end ().get_data_as_bytes ();
|
||||
config_allocation = yield allocator.allocate (config_blob.get_size (), 8, cancellable);
|
||||
config_allocation = yield data_allocator.allocate (config_blob.get_size (), 8, cancellable);
|
||||
|
||||
yield machine.write_virtual (config_allocation.virtual_address, config_blob.get_data (),
|
||||
cancellable);
|
||||
|
||||
yield protect_unless_already (machine, allocator, config_allocation.virtual_address,
|
||||
yield protect_unless_already (machine, data_allocator, config_allocation.virtual_address,
|
||||
config_allocation.size, READ | WRITE, cancellable);
|
||||
|
||||
var ia32 = machine as IA32Machine;
|
||||
@@ -316,11 +320,19 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
progress ("Starting the agent", 0.75);
|
||||
yield machine.invoke (start_address, {
|
||||
config_allocation.virtual_address,
|
||||
config_allocation.size
|
||||
},
|
||||
cancellable);
|
||||
var start_gdb = machine.debugger as GDB.Client;
|
||||
if (start_gdb != null)
|
||||
start_gdb.suppress_solo = true;
|
||||
try {
|
||||
yield machine.invoke (start_address, {
|
||||
config_allocation.virtual_address,
|
||||
config_allocation.size
|
||||
},
|
||||
cancellable);
|
||||
} finally {
|
||||
if (start_gdb != null)
|
||||
start_gdb.suppress_solo = false;
|
||||
}
|
||||
|
||||
if (x64 != null)
|
||||
x64.call_stack = 0;
|
||||
@@ -341,14 +353,14 @@ namespace Frida.Barebone {
|
||||
return true;
|
||||
}
|
||||
|
||||
private async void wait_to_be_greeted (Cancellable? cancellable) throws Error, IOError {
|
||||
private async void wait_to_be_greeted (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (listening == null)
|
||||
return;
|
||||
|
||||
var timeout = new TimeoutSource (GREETING_TIMEOUT_MS);
|
||||
timeout.set_callback (() => {
|
||||
if (!listening.future.ready)
|
||||
listening.reject (new Error.TIMED_OUT ("The agent never announced itself"));
|
||||
listening.reject (new Efni.Error.TIMED_OUT ("The agent never announced itself"));
|
||||
return false;
|
||||
});
|
||||
timeout.attach (MainContext.get_thread_default ());
|
||||
@@ -360,7 +372,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
|
||||
private async Variant resolve_transport (Cancellable? cancellable) throws Error, IOError {
|
||||
private async Variant resolve_transport (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (agent_config.transport is BareboneHostlinkTransportConfig)
|
||||
return yield connect_virtio_transport ((BareboneHostlinkTransportConfig) agent_config.transport, cancellable);
|
||||
if (agent_config.transport is BareboneVsockTransportConfig) {
|
||||
@@ -397,11 +409,11 @@ namespace Frida.Barebone {
|
||||
new Variant.variant (new Variant.string (config.socket_path))
|
||||
});
|
||||
}
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported transport config");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unsupported transport config");
|
||||
}
|
||||
|
||||
private async void connect_serial_transport (BareboneSerialTransportConfig config,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
try {
|
||||
#if WINDOWS
|
||||
adopt_hostlink_streams (WindowsNamedPipe.open_client (config.path));
|
||||
@@ -411,20 +423,20 @@ namespace Frida.Barebone {
|
||||
cancellable));
|
||||
#endif
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.TRANSPORT ("Unable to reach the serial port of the guest: %s", e.message);
|
||||
throw new Efni.Error.TRANSPORT ("Unable to reach the serial port of the guest: %s", e.message);
|
||||
}
|
||||
|
||||
listening = new Promise<bool> ();
|
||||
listening = new Efni.Promise<bool> ();
|
||||
}
|
||||
|
||||
private async void open_pipe_listener (string path, Cancellable? cancellable) throws Error, IOError {
|
||||
private async void open_pipe_listener (string path, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
FileUtils.unlink (path);
|
||||
var service = new SocketService ();
|
||||
try {
|
||||
SocketAddress effective;
|
||||
service.add_address (new UnixSocketAddress (path), STREAM, DEFAULT, null, out effective);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.TRANSPORT ("Unable to listen on %s: %s", path, e.message);
|
||||
throw new Efni.Error.TRANSPORT ("Unable to listen on %s: %s", path, e.message);
|
||||
}
|
||||
service.incoming.connect ((connection) => {
|
||||
if (pipe_stream == null) {
|
||||
@@ -441,7 +453,7 @@ namespace Frida.Barebone {
|
||||
pipe_service = service;
|
||||
}
|
||||
|
||||
private async void establish_hostlink (Cancellable? cancellable) throws Error, IOError {
|
||||
private async void establish_hostlink (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (pipe_listener_wanted) {
|
||||
while (pipe_stream == null) {
|
||||
pipe_accept_handler = establish_hostlink.callback;
|
||||
@@ -472,7 +484,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async Variant connect_virtio_transport (BareboneHostlinkTransportConfig config, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var qmp = yield QmpClient.open (config.qmp, 0, cancellable);
|
||||
var link = yield qmp.open_hostlink (config.bus, cancellable);
|
||||
this.qmp = qmp;
|
||||
@@ -510,7 +522,7 @@ namespace Frida.Barebone {
|
||||
output = hostlink.get_output_stream ();
|
||||
}
|
||||
|
||||
private void rebase_layout (Layout layout, uint64 preferred_base, KernelRelocation reloc) throws Error {
|
||||
private void rebase_layout (Layout layout, uint64 preferred_base, KernelRelocation reloc) throws Efni.Error {
|
||||
foreach (var s in layout.symbols)
|
||||
s.offset = reloc.runtime_offset (preferred_base + s.offset);
|
||||
foreach (var m in layout.modules) {
|
||||
@@ -549,7 +561,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
|
||||
private async void give_the_memory_back (Cancellable? cancellable) throws Error, IOError {
|
||||
private async void give_the_memory_back (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var timeout = new TimeoutSource (LEAVE_INTERVAL_MS);
|
||||
timeout.set_callback (give_the_memory_back.callback);
|
||||
timeout.attach (MainContext.get_thread_default ());
|
||||
@@ -573,7 +585,7 @@ namespace Frida.Barebone {
|
||||
yield flavor.settle (cancellable);
|
||||
}
|
||||
|
||||
private async void wait_for_agent_to_leave (Cancellable? cancellable) throws Error, IOError {
|
||||
private async void wait_for_agent_to_leave (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (left_flag == 0)
|
||||
return;
|
||||
|
||||
@@ -605,13 +617,13 @@ namespace Frida.Barebone {
|
||||
// same data. The process receives the code as it is, thus only the writable half needs a new
|
||||
// location, in memory that both sides can address.
|
||||
public async void place_winnt_user_agent (uint pid, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var response = yield execute_command (Command.PLACE_AGENT_IN_PROCESS,
|
||||
new Variant.uint32 (pid), cancellable);
|
||||
if (!response.is_of_type (VariantType.UINT32))
|
||||
throw new Error.PROTOCOL ("Invalid place_agent_in_process response format");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid place_agent_in_process response format");
|
||||
if (response.get_uint32 () == 0)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to place the agent in the process");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unable to place the agent in the process");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -619,7 +631,7 @@ namespace Frida.Barebone {
|
||||
* copy reports having woken up in.
|
||||
*/
|
||||
public async uint inject_agent_into_process (uint pid, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
if (kernel_kind == WINNT) {
|
||||
yield place_winnt_user_agent (pid, cancellable);
|
||||
return yield start_winnt_agent_in_process (pid, cancellable);
|
||||
@@ -631,12 +643,12 @@ namespace Frida.Barebone {
|
||||
// The copy cannot answer from the thread that starts it. Thus ask again until it reports its
|
||||
// process id.
|
||||
private async uint start_winnt_agent_in_process (uint pid, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
for (uint attempt = 0; attempt != INJECT_MAX_ATTEMPTS; attempt++) {
|
||||
var response = yield execute_command (Command.START_AGENT_IN_PROCESS,
|
||||
new Variant.uint32 (pid), cancellable);
|
||||
if (!response.is_of_type (VariantType.UINT32))
|
||||
throw new Error.PROTOCOL ("Invalid start_agent_in_process response format");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid start_agent_in_process response format");
|
||||
|
||||
uint reached = response.get_uint32 ();
|
||||
if (reached != 0)
|
||||
@@ -649,19 +661,19 @@ namespace Frida.Barebone {
|
||||
timeout.destroy ();
|
||||
}
|
||||
|
||||
throw new Error.TIMED_OUT ("Timed out while starting the agent in the process");
|
||||
throw new Efni.Error.TIMED_OUT ("Timed out while starting the agent in the process");
|
||||
}
|
||||
|
||||
public signal void spawn_added (uint pid, string command_line, uint holder_pid);
|
||||
|
||||
public async Application[] enumerate_applications (string[] identifiers, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var selected = new VariantBuilder (new VariantType ("as"));
|
||||
foreach (unowned string identifier in identifiers)
|
||||
selected.add ("s", identifier);
|
||||
var response = yield execute_command (Command.ENUMERATE_APPLICATIONS, selected.end (), cancellable);
|
||||
if (!response.check_format_string ("a(sss)", false))
|
||||
throw new Error.PROTOCOL ("Invalid enumerate_applications response format");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid enumerate_applications response format");
|
||||
|
||||
var applications = new Application[response.n_children ()];
|
||||
for (size_t i = 0; i != applications.length; i++) {
|
||||
@@ -676,11 +688,11 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async Shortcut[] enumerate_shortcuts (uint helper_pid, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var response = yield execute_command (Command.ENUMERATE_SHORTCUTS,
|
||||
new Variant.boolean (false), cancellable, helper_pid);
|
||||
if (!response.check_format_string ("a(ssss)", false))
|
||||
throw new Error.PROTOCOL ("Invalid enumerate_shortcuts response format");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid enumerate_shortcuts response format");
|
||||
|
||||
var shortcuts = new Shortcut[response.n_children ()];
|
||||
for (size_t i = 0; i != shortcuts.length; i++) {
|
||||
@@ -727,51 +739,59 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
|
||||
public async void gate_spawns (bool on, Cancellable? cancellable) throws Error, IOError {
|
||||
public async void gate_spawns (bool on, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
yield execute_command (Command.GATE_SPAWNS, new Variant.boolean (on), cancellable);
|
||||
}
|
||||
|
||||
public async void arm_named_spawn (string name, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
yield execute_command (Command.ARM_NAMED_SPAWN, new Variant.string (name), cancellable);
|
||||
}
|
||||
|
||||
public async void disarm_named_spawn (string name, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
yield execute_command (Command.DISARM_NAMED_SPAWN, new Variant.string (name), cancellable);
|
||||
}
|
||||
|
||||
public async uint spawn_process (uint helper_pid, string command_line, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
return yield ask_for_a_spawn (helper_pid, new Variant.string (command_line), cancellable);
|
||||
}
|
||||
|
||||
// A kernel that starts programs itself takes the words as they are, since a line to be
|
||||
// split again is what Windows asks for and nothing else does.
|
||||
public async uint spawn_program (string[] words, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
return yield ask_for_a_spawn (0, new Variant.strv (words), cancellable);
|
||||
}
|
||||
|
||||
private async uint ask_for_a_spawn (uint helper_pid, Variant payload, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var response = yield execute_command (Command.SPAWN_PROCESS, payload, cancellable,
|
||||
helper_pid);
|
||||
if (!response.is_of_type (VariantType.UINT32))
|
||||
throw new Error.PROTOCOL ("Invalid spawn_process response format");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid spawn_process response format");
|
||||
|
||||
return response.get_uint32 ();
|
||||
}
|
||||
|
||||
public async void resume_process (uint helper_pid, uint pid, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
yield execute_command (Command.RESUME_PROCESS, new Variant.uint32 (pid), cancellable,
|
||||
helper_pid);
|
||||
}
|
||||
|
||||
public async void detach_from_process (uint pid, Cancellable? cancellable) throws Error, IOError {
|
||||
public async void detach_from_process (uint pid, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
yield execute_command (Command.DETACH_FROM_PROCESS, new Variant.uint32 (pid), cancellable);
|
||||
}
|
||||
|
||||
public async uint inject_into_process (uint pid, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
// The agent cannot answer from the context that does the work. Thus it reports the result at
|
||||
// the next request.
|
||||
for (uint attempt = 0; attempt != INJECT_MAX_ATTEMPTS; attempt++) {
|
||||
var response = yield execute_command (Command.INJECT_INTO_PROCESS,
|
||||
new Variant.uint32 (pid), cancellable);
|
||||
if (!response.is_of_type (VariantType.UINT32))
|
||||
throw new Error.PROTOCOL ("Invalid inject_into_process response format");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid inject_into_process response format");
|
||||
|
||||
uint reached = response.get_uint32 ();
|
||||
if (reached != 0)
|
||||
@@ -784,19 +804,19 @@ namespace Frida.Barebone {
|
||||
timeout.destroy ();
|
||||
}
|
||||
|
||||
throw new Error.TIMED_OUT ("Timed out while injecting into process");
|
||||
throw new Efni.Error.TIMED_OUT ("Timed out while injecting into process");
|
||||
}
|
||||
|
||||
public async HostProcessInfo[] enumerate_processes (Scope scope, uint[] pids, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
bool include_icons = scope == FULL;
|
||||
var selected = new VariantBuilder (new VariantType ("au"));
|
||||
foreach (uint pid in pids)
|
||||
selected.add ("u", pid);
|
||||
var request = new Variant.tuple ({ new Variant.boolean (include_icons), selected.end () });
|
||||
var response = yield execute_command (Command.ENUMERATE_PROCESSES, request, cancellable);
|
||||
if (!response.check_format_string ("a(usssaay)", false))
|
||||
throw new Error.PROTOCOL ("Invalid enumerate_processes response format");
|
||||
if (!response.check_format_string ("a(usssusuxaay)", false))
|
||||
throw new Efni.Error.PROTOCOL ("Invalid enumerate_processes response format");
|
||||
|
||||
var processes = new HostProcessInfo[response.n_children ()];
|
||||
for (size_t i = 0; i != processes.length; i++) {
|
||||
@@ -810,9 +830,21 @@ namespace Frida.Barebone {
|
||||
unowned string command_line = entry.get_child_value (2).get_string ();
|
||||
if (command_line != "")
|
||||
parameters["argv"] = argv_from_command_line (command_line);
|
||||
|
||||
parameters["uid"] = new Variant.uint32 (entry.get_child_value (4).get_uint32 ());
|
||||
|
||||
unowned string user = entry.get_child_value (5).get_string ();
|
||||
if (user != "")
|
||||
parameters["user"] = user;
|
||||
|
||||
parameters["ppid"] = new Variant.int64 (entry.get_child_value (6).get_uint32 ());
|
||||
|
||||
int64 started = entry.get_child_value (7).get_int64 ();
|
||||
if (started != 0)
|
||||
parameters["started"] = new DateTime.from_unix_utc (started).format_iso8601 ();
|
||||
}
|
||||
if (include_icons)
|
||||
parameters["icons"] = icons_from_resources (entry.get_child_value (4));
|
||||
parameters["icons"] = icons_from_resources (entry.get_child_value (8));
|
||||
|
||||
unowned string description = entry.get_child_value (3).get_string ();
|
||||
string name = (description != "") ? description : basename_of (path);
|
||||
@@ -986,30 +1018,30 @@ namespace Frida.Barebone {
|
||||
private const uint32 MAX_ICON_DIMENSION = 256;
|
||||
|
||||
public async AgentScriptId create_script (string source, uint destination, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var payload = new Variant ("s", source);
|
||||
var response = yield execute_command (Command.CREATE_SCRIPT, payload, cancellable, destination);
|
||||
if (!response.check_format_string ("u", false))
|
||||
throw new Error.PROTOCOL ("Invalid create_script response format");
|
||||
throw new Efni.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, uint destination, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var payload = new Variant ("u", script_id.handle);
|
||||
yield execute_command (Command.LOAD_SCRIPT, payload, cancellable, destination);
|
||||
}
|
||||
|
||||
public async void destroy_script (AgentScriptId script_id, uint destination, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var payload = new Variant ("u", script_id.handle);
|
||||
yield execute_command (Command.DESTROY_SCRIPT, payload, cancellable, destination);
|
||||
}
|
||||
|
||||
public async void post_script_message (AgentScriptId script_id, string message, Bytes? data, uint destination,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var payload = new Variant ("(us@ay)", script_id.handle, message,
|
||||
new Variant.from_bytes (new VariantType ("ay"), data ?? new Bytes (new uint8[0]), true));
|
||||
yield execute_command (Command.POST_SCRIPT_MESSAGE, payload, cancellable, destination);
|
||||
@@ -1017,26 +1049,26 @@ namespace Frida.Barebone {
|
||||
|
||||
// Zero selects the agent in the kernel. A different value selects a process that has a copy.
|
||||
private async Variant execute_command (Command command, Variant payload, Cancellable? cancellable,
|
||||
uint destination = 0) throws Error, IOError {
|
||||
uint destination = 0) throws Efni.Error, IOError {
|
||||
uint16 request_id = next_request_id++;
|
||||
|
||||
Bytes frame = frame_message (command, request_id, destination, payload);
|
||||
|
||||
var promise = new Promise<Variant> ();
|
||||
var promise = new Efni.Promise<Variant> ();
|
||||
pending_requests[request_id] = promise;
|
||||
|
||||
try {
|
||||
yield write_frame (frame, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
pending_requests.unset (request_id);
|
||||
throw new Error.TRANSPORT ("%s", e.message);
|
||||
throw new Efni.Error.TRANSPORT ("%s", e.message);
|
||||
}
|
||||
|
||||
var timeout_source = new TimeoutSource (COMMAND_TIMEOUT_MS);
|
||||
timeout_source.set_callback (() => {
|
||||
Promise<Variant>? p;
|
||||
Efni.Promise<Variant>? p;
|
||||
if (pending_requests.unset (request_id, out p))
|
||||
p.reject (new Error.TIMED_OUT ("The %s command timed out", command.to_nick ()));
|
||||
p.reject (new Efni.Error.TIMED_OUT ("The %s command timed out", command.to_nick ()));
|
||||
return Source.REMOVE;
|
||||
});
|
||||
timeout_source.attach (MainContext.get_thread_default ());
|
||||
@@ -1044,29 +1076,29 @@ namespace Frida.Barebone {
|
||||
Variant response = null;
|
||||
try {
|
||||
response = yield promise.future.wait_async (cancellable);
|
||||
} catch (Error e) {
|
||||
if (!(e is Error.TIMED_OUT))
|
||||
} catch (Efni.Error e) {
|
||||
if (!(e is Efni.Error.TIMED_OUT))
|
||||
throw e;
|
||||
string? fault = yield describe_agent_fault (cancellable);
|
||||
if (fault == null)
|
||||
throw e;
|
||||
throw new Error.TIMED_OUT ("%s; %s", e.message, fault);
|
||||
throw new Efni.Error.TIMED_OUT ("%s; %s", e.message, fault);
|
||||
} finally {
|
||||
timeout_source.destroy ();
|
||||
}
|
||||
|
||||
if (!response.check_format_string ("(bv)", false))
|
||||
throw new Error.PROTOCOL ("Malformed reply from agent");
|
||||
throw new Efni.Error.PROTOCOL ("Malformed reply from agent");
|
||||
bool succeeded;
|
||||
Variant detail;
|
||||
response.get ("(bv)", out succeeded, out detail);
|
||||
if (!succeeded)
|
||||
throw new Error.NOT_SUPPORTED ("%s", detail.get_string ());
|
||||
throw new Efni.Error.NOT_SUPPORTED ("%s", detail.get_string ());
|
||||
|
||||
return detail;
|
||||
}
|
||||
|
||||
private async string? describe_agent_fault (Cancellable? cancellable) throws Error, IOError {
|
||||
private async string? describe_agent_fault (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (fault_record == 0)
|
||||
return null;
|
||||
|
||||
@@ -1113,7 +1145,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void process_incoming_messages () {
|
||||
reading = new Promise<bool> ();
|
||||
reading = new Efni.Promise<bool> ();
|
||||
try {
|
||||
while (true) {
|
||||
size_t header_size = 4;
|
||||
@@ -1141,7 +1173,7 @@ namespace Frida.Barebone {
|
||||
if (byte_order != ByteOrder.HOST)
|
||||
message = message.byteswap ();
|
||||
if (!message.check_format_string ("(yquv)", false))
|
||||
throw new Error.PROTOCOL ("Invalid message format");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid message format");
|
||||
|
||||
uint8 command_code;
|
||||
uint16 request_id;
|
||||
@@ -1154,7 +1186,7 @@ namespace Frida.Barebone {
|
||||
listening.resolve (true);
|
||||
} else if (command_code == Command.SPAWN_ADDED) {
|
||||
if (!payload.check_format_string ("(us)", false))
|
||||
throw new Error.PROTOCOL ("Invalid spawn added payload format");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid spawn added payload format");
|
||||
|
||||
uint32 pid;
|
||||
unowned string command_line;
|
||||
@@ -1163,7 +1195,7 @@ namespace Frida.Barebone {
|
||||
spawn_added (pid, command_line, destination);
|
||||
} else if (command_code == Command.SCRIPT_MESSAGE) {
|
||||
if (!payload.check_format_string ("(usay)", false))
|
||||
throw new Error.PROTOCOL ("Invalid script message payload format");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid script message payload format");
|
||||
|
||||
uint32 script_handle;
|
||||
unowned string json;
|
||||
@@ -1188,7 +1220,7 @@ namespace Frida.Barebone {
|
||||
result = yield protect_memory (payload, io_cancellable);
|
||||
else
|
||||
result = yield patch_code (payload, io_cancellable);
|
||||
} catch (Error e) {
|
||||
} catch (Efni.Error e) {
|
||||
result = (command_code == Command.REMAP_WRITABLE_PAGES)
|
||||
? new Variant.uint64 (0)
|
||||
: new Variant.boolean (false);
|
||||
@@ -1198,7 +1230,7 @@ namespace Frida.Barebone {
|
||||
|
||||
yield send_reply (request_id, result);
|
||||
} else if (command_code == Command.REPLY) {
|
||||
Promise<Variant>? promise;
|
||||
Efni.Promise<Variant>? promise;
|
||||
if (pending_requests.unset (request_id, out promise))
|
||||
promise.resolve (payload);
|
||||
}
|
||||
@@ -1209,9 +1241,9 @@ namespace Frida.Barebone {
|
||||
reading.resolve (true);
|
||||
}
|
||||
|
||||
private Promise<bool>? reading;
|
||||
private Efni.Promise<bool>? reading;
|
||||
|
||||
private async void fill_until_n_bytes_available (size_t minimum) throws Error, IOError {
|
||||
private async void fill_until_n_bytes_available (size_t minimum) throws Efni.Error, IOError {
|
||||
size_t available = input.get_available ();
|
||||
while (available < minimum) {
|
||||
if (input.get_buffer_size () < minimum)
|
||||
@@ -1222,17 +1254,17 @@ namespace Frida.Barebone {
|
||||
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");
|
||||
throw new Efni.Error.TRANSPORT ("Connection closed");
|
||||
}
|
||||
|
||||
if (n == 0)
|
||||
throw new Error.TRANSPORT ("Connection closed");
|
||||
throw new Efni.Error.TRANSPORT ("Connection closed");
|
||||
|
||||
available += n;
|
||||
}
|
||||
}
|
||||
|
||||
private async Variant remap_writable_pages (Variant payload, Cancellable? cancellable) throws Error, IOError {
|
||||
private async Variant remap_writable_pages (Variant payload, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var physical_addresses = new Gee.ArrayList<uint64?> ();
|
||||
for (size_t i = 0; i != payload.n_children (); i++) {
|
||||
uint64 va = payload.get_child_value (i).get_uint64 ();
|
||||
@@ -1244,7 +1276,7 @@ namespace Frida.Barebone {
|
||||
return new Variant.uint64 (allocation.virtual_address);
|
||||
}
|
||||
|
||||
private async Variant protect_memory (Variant payload, Cancellable? cancellable) throws Error, IOError {
|
||||
private async Variant protect_memory (Variant payload, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
uint64 address;
|
||||
uint64 size;
|
||||
uint32 prot;
|
||||
@@ -1259,7 +1291,7 @@ namespace Frida.Barebone {
|
||||
// CTRR/KTRR locks kernel text read-only against the guest CPU, so the agent cannot patch it
|
||||
// even through a writable alias. The physical-memory bridge writes the backing store directly,
|
||||
// which the lock does not cover, letting us land hooks in kernel and kext text.
|
||||
private async Variant patch_code (Variant payload, Cancellable? cancellable) throws Error, IOError {
|
||||
private async Variant patch_code (Variant payload, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
uint64 va;
|
||||
Variant bytes_value;
|
||||
payload.get ("(t@ay)", out va, out bytes_value);
|
||||
@@ -1289,7 +1321,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void write_frame (Bytes frame, Cancellable? cancellable) throws GLib.Error {
|
||||
var ours = new Promise<bool> ();
|
||||
var ours = new Efni.Promise<bool> ();
|
||||
var theirs = write_turn;
|
||||
write_turn = ours;
|
||||
|
||||
@@ -1310,7 +1342,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
|
||||
private Promise<bool>? write_turn;
|
||||
private Efni.Promise<bool>? write_turn;
|
||||
|
||||
private Bytes frame_message (Command command, uint16 request_id, uint destination, Variant payload) {
|
||||
var message = new Variant ("(yquv)", (uint8) command, request_id, destination, payload);
|
||||
@@ -1324,31 +1356,33 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private enum Command {
|
||||
CREATE_SCRIPT = 1,
|
||||
LOAD_SCRIPT = 2,
|
||||
DESTROY_SCRIPT = 3,
|
||||
POST_SCRIPT_MESSAGE = 4,
|
||||
REMAP_WRITABLE_PAGES = 5,
|
||||
MEMORY_PROTECT = 6,
|
||||
PATCH_CODE = 7,
|
||||
ENUMERATE_PROCESSES = 8,
|
||||
INJECT_INTO_PROCESS = 9,
|
||||
DETACH_FROM_PROCESS = 11,
|
||||
PLACE_AGENT_IN_PROCESS = 12,
|
||||
START_AGENT_IN_PROCESS = 13,
|
||||
SPAWN_PROCESS = 14,
|
||||
RESUME_PROCESS = 15,
|
||||
STOP = 16,
|
||||
GATE_SPAWNS = 17,
|
||||
ENUMERATE_APPLICATIONS = 18,
|
||||
ENUMERATE_SHORTCUTS = 19,
|
||||
ENUMERATE_APPLICATIONS = 1,
|
||||
ENUMERATE_SHORTCUTS = 2,
|
||||
ENUMERATE_PROCESSES = 3,
|
||||
GATE_SPAWNS = 4,
|
||||
ARM_NAMED_SPAWN = 5,
|
||||
DISARM_NAMED_SPAWN = 6,
|
||||
SPAWN_PROCESS = 7,
|
||||
RESUME_PROCESS = 8,
|
||||
STOP = 9,
|
||||
INJECT_INTO_PROCESS = 10,
|
||||
PLACE_AGENT_IN_PROCESS = 11,
|
||||
START_AGENT_IN_PROCESS = 12,
|
||||
REMAP_WRITABLE_PAGES = 14,
|
||||
MEMORY_PROTECT = 15,
|
||||
PATCH_CODE = 16,
|
||||
DETACH_FROM_PROCESS = 17,
|
||||
CREATE_SCRIPT = 18,
|
||||
DESTROY_SCRIPT = 19,
|
||||
LOAD_SCRIPT = 20,
|
||||
POST_SCRIPT_MESSAGE = 21,
|
||||
REPLY = 128,
|
||||
SCRIPT_MESSAGE = 129,
|
||||
SPAWN_ADDED = 130,
|
||||
READY = 131;
|
||||
|
||||
public string to_nick () {
|
||||
return Marshal.enum_to_nick<Command> (this);
|
||||
return Efni.Marshal.enum_to_nick<Command> (this);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,44 +1,36 @@
|
||||
## Getting the SDK and the devkit
|
||||
|
||||
The agent is built against the bare soft-float SDK, which carries picolibc and the
|
||||
compiler runtime, and against a GumJS devkit built for the same flavor. Which flavor
|
||||
is the target's, listed under Targets below; this walks through the XNU one. No
|
||||
prebuilt bundles are published for these, so build both:
|
||||
compiler runtime, and against a GumJS devkit built for the same machine. Which machine
|
||||
is the target's, listed under Targets below; this walks through the XNU one. The SDK
|
||||
is published prebuilt, and the devkit is built from frida-gum:
|
||||
|
||||
machine=none-arm64-softfloat_nopic
|
||||
machine=none-arm64-softfloat_pic
|
||||
|
||||
releng/deps.py build --bundle=sdk --host=$machine
|
||||
mkdir -p ~/sdk-$machine
|
||||
tar -C ~/sdk-$machine -xf deps/sdk-$machine.tar.xz
|
||||
sdk=~/sdk-$machine
|
||||
releng/deps.py sync sdk $machine $sdk
|
||||
|
||||
gum=~/src/frida-gum
|
||||
mkdir -p $gum/build/$machine
|
||||
(cd $gum/build/$machine \
|
||||
&& FRIDA_DEPS=$HOME/src/frida-core/deps CC=clang CXX=clang++ AR=llvm-ar \
|
||||
RANLIB=llvm-ranlib NM=llvm-nm STRIP=llvm-strip \
|
||||
../../configure --host=$machine --enable-gumjs \
|
||||
--with-devkits=gumjs \
|
||||
&& python3 ../../releng/meson/meson.py configure -Ddevkit_symbol_scope=original \
|
||||
&& ninja)
|
||||
&& CC=clang CXX=clang++ ../../configure --host=$machine --enable-gumjs \
|
||||
--with-devkits=gumjs --with-devkit-symbol-scope=original \
|
||||
&& make)
|
||||
|
||||
## Building
|
||||
|
||||
sdk=~/sdk-$machine
|
||||
export GUMJS_DEVKIT_DIR=$gum/build/$machine/bindings/gumjs/devkit
|
||||
export CC="clang -I$sdk/include -I$sdk/include/glib-2.0 -I$sdk/lib/glib-2.0/include \
|
||||
-I$sdk/include/capstone -I$sdk/include/json-glib-1.0"
|
||||
export RUSTFLAGS="-L native=$sdk/lib"
|
||||
|
||||
RUSTC_BOOTSTRAP=1 cargo build --release --features xnu \
|
||||
--target aarch64-unknown-none-softfloat --target-dir target-xnu \
|
||||
-Z build-std=core,alloc,compiler_builtins
|
||||
--target ./aarch64-unknown-none-pic.json -Z json-target-spec \
|
||||
--target-dir target-xnu -Z build-std=core,alloc,compiler_builtins
|
||||
|
||||
Rust names no bare-metal target for the Windows guests, so the agent spells them
|
||||
out and they are asked for by path:
|
||||
|
||||
RUSTC_BOOTSTRAP=1 cargo build --release --features win9x \
|
||||
--target ./i686-unknown-none-pic.json -Z json-target-spec \
|
||||
--target-dir target-win9x -Z build-std=core,alloc,compiler_builtins
|
||||
Every flavor names its target by path, as Rust has no built-in one for a
|
||||
position-independent bare-metal image. The others differ only in feature, machine
|
||||
and target spec, listed under Targets below.
|
||||
|
||||
## Targets
|
||||
|
||||
@@ -58,7 +50,7 @@ and NT's 64-bit half is called in the Microsoft ABI.
|
||||
|
||||
| Flavor | Machine | Rust target |
|
||||
|---------|-----------------------------------|----------------------------------|
|
||||
| `xnu` | `none-arm64-softfloat_nopic` | `aarch64-unknown-none-softfloat` |
|
||||
| `xnu` | `none-arm64-softfloat_pic` | `aarch64-unknown-none-pic.json` |
|
||||
| `win9x` | `none-x86-softfloat_pic` | `i686-unknown-none-pic.json` |
|
||||
| `winnt` | `none-x86-softfloat_pic` | `i686-unknown-none-pic.json` |
|
||||
| `winnt` | `none-x86_64-softfloat_pic_msabi` | `x86_64-unknown-none-pic.json` |
|
||||
@@ -72,7 +64,9 @@ half of Gum's platform backend (`gum_xnu.rs` / `gum_windows.rs` / `gum_linux.rs`
|
||||
## Development loop
|
||||
|
||||
export FRIDA_BAREBONE_CONFIG=$PWD/etc/xnu.json
|
||||
cargo build --release --features xnu --target aarch64-unknown-none-softfloat \
|
||||
RUSTC_BOOTSTRAP=1 cargo build --release --features xnu \
|
||||
--target ./aarch64-unknown-none-pic.json -Z json-target-spec \
|
||||
--target-dir target-xnu -Z build-std=core,alloc,compiler_builtins \
|
||||
&& make -C ~/src/frida-python \
|
||||
&& killall -9 qemu-system-aarch64 && sleep 2 \
|
||||
&& frida -D barebone -p 0
|
||||
|
||||
@@ -89,6 +89,8 @@ SECTIONS {
|
||||
___tracepoint_sched_process_fork = .; . += 4;
|
||||
___tracepoint_sched_process_exit = .; . += 4;
|
||||
___tracepoint_sched_process_exec = .; . += 4;
|
||||
___tracepoint_task_rename = .; . += 4;
|
||||
___set_task_comm = .; . += 4;
|
||||
_vunmap = .; . += 4;
|
||||
_arm_copy_to_user = .; . += 4;
|
||||
_down_read = .; . += 4;
|
||||
@@ -97,6 +99,7 @@ SECTIONS {
|
||||
_get_user_pages_remote = .; . += 4;
|
||||
_user_mode_thread = .; . += 4;
|
||||
_fget_task = .; . += 4;
|
||||
_find_task_by_vpid = .; . += 4;
|
||||
___start_BTF = .; . += 4;
|
||||
___stop_BTF = .; . += 4;
|
||||
_call_usermodehelper_setup = .; . += 4;
|
||||
|
||||
@@ -86,6 +86,8 @@ SECTIONS {
|
||||
___tracepoint_sched_process_fork = .; . += 8;
|
||||
___tracepoint_sched_process_exit = .; . += 8;
|
||||
___tracepoint_sched_process_exec = .; . += 8;
|
||||
___tracepoint_task_rename = .; . += 8;
|
||||
___set_task_comm = .; . += 8;
|
||||
_vunmap = .; . += 8;
|
||||
___arch_copy_to_user = .; . += 8;
|
||||
_down_read = .; . += 8;
|
||||
@@ -97,6 +99,7 @@ SECTIONS {
|
||||
_user_mode_thread = .; . += 8;
|
||||
_apply_to_existing_page_range = .; . += 8;
|
||||
_caches_clean_inval_pou = .; . += 8;
|
||||
_do_madvise = .; . += 8;
|
||||
_fget_task = .; . += 8;
|
||||
_find_task_by_vpid = .; . += 8;
|
||||
___start_BTF = .; . += 8;
|
||||
|
||||
@@ -100,6 +100,7 @@ SECTIONS {
|
||||
__copy_from_user = .; . += 4;
|
||||
_access_process_vm = .; . += 4;
|
||||
_fget_task = .; . += 4;
|
||||
_find_task_by_vpid = .; . += 4;
|
||||
_init_net = .; . += 4;
|
||||
_sock_create_kern = .; . += 4;
|
||||
_kernel_connect = .; . += 4;
|
||||
|
||||
@@ -91,6 +91,8 @@ SECTIONS {
|
||||
___tracepoint_sched_process_fork = .; . += 8;
|
||||
___tracepoint_sched_process_exit = .; . += 8;
|
||||
___tracepoint_sched_process_exec = .; . += 8;
|
||||
___tracepoint_task_rename = .; . += 8;
|
||||
___set_task_comm = .; . += 8;
|
||||
_vunmap = .; . += 8;
|
||||
__copy_to_user = .; . += 8;
|
||||
_down_read = .; . += 8;
|
||||
@@ -106,6 +108,7 @@ SECTIONS {
|
||||
__copy_from_user = .; . += 8;
|
||||
_access_process_vm = .; . += 8;
|
||||
_fget_task = .; . += 8;
|
||||
_find_task_by_vpid = .; . += 8;
|
||||
_init_net = .; . += 8;
|
||||
_sock_create_kern = .; . += 8;
|
||||
_kernel_connect = .; . += 8;
|
||||
|
||||
@@ -33,7 +33,12 @@ fn main() {
|
||||
.clang_arg(format!("{}-none-elf", target.split('-').next().unwrap()))
|
||||
.clang_args(cc_clang_args)
|
||||
.clang_arg(format!("-I{}", devkit_dir.to_str().unwrap()))
|
||||
.clang_arg("-include")
|
||||
.clang_arg("stddef.h")
|
||||
.clang_arg("-include")
|
||||
.clang_arg("stdint.h")
|
||||
.blocklist_type("max_align_t")
|
||||
.blocklist_function("memcpy|memmove|memset|memcmp|bcmp|strlen")
|
||||
.merge_extern_blocks(true)
|
||||
.generate()
|
||||
.expect("Unable to generate bindings");
|
||||
|
||||
@@ -11,21 +11,22 @@ how it is told about the kernel around it, and how the host reaches it.
|
||||
## Building
|
||||
|
||||
Three things, in order. First an SDK for this kernel -- picolibc, GLib, QuickJS, capstone and the
|
||||
rest, built for `macos-arm64-kernel`:
|
||||
rest, built for `macos-arm64e-kernel` and published prebuilt:
|
||||
|
||||
cd frida-core
|
||||
python3 -m releng.deps build --host macos-arm64-kernel
|
||||
releng/deps.py sync sdk macos-arm64e-kernel ~/sdk-macos-arm64e-kernel
|
||||
|
||||
That fetches the same sources every other flavour is built from, six of them pinned to a commit
|
||||
that says what a Darwin kernel is not; see below. Then a GumJS devkit against it:
|
||||
It is built from the same sources every other flavour is, six of them pinned to a commit that
|
||||
says what a Darwin kernel is not; see below. Then a GumJS devkit against it:
|
||||
|
||||
cd frida-gum
|
||||
./configure --host=macos-arm64-kernel --enable-gumjs --disable-v8 --with-devkits=gumjs
|
||||
./configure --host=macos-arm64e-kernel --enable-gumjs --with-devkits=gumjs \
|
||||
--with-devkit-symbol-scope=original
|
||||
make
|
||||
|
||||
Then the kext itself:
|
||||
|
||||
make FRIDA_SDK=.../deps/sdk-macos-arm64-kernel \
|
||||
make FRIDA_SDK=~/sdk-macos-arm64e-kernel \
|
||||
GUMJS_DEVKIT_DIR=.../frida-gum/build/bindings/gumjs/devkit
|
||||
|
||||
which builds the agent as a static library for the kernel's ABI, `frida-kext.c` against the Kernel
|
||||
|
||||
@@ -453,6 +453,7 @@ pub struct ThreadSlots {
|
||||
pub set: fn(u32, *mut c_void),
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt", feature = "xnu-core"))]
|
||||
pub fn use_thread_slots(slots: &'static ThreadSlots) {
|
||||
unsafe { SLOTS = Some(slots) };
|
||||
}
|
||||
|
||||
@@ -6,11 +6,9 @@ use crate::{
|
||||
_GInterfaceInfo, _GTypeInfo, GObject, GObjectClass, GPrivate, GType, GumAddress,
|
||||
GumExportDetails,
|
||||
GumExportType_GUM_EXPORT_FUNCTION, GumFoundExportFunc, GumMemoryRange, GumModule,
|
||||
GumFoundSymbolFunc, GumModuleInterface, GumSymbolDetails, GumSymbolType_GUM_SYMBOL_FUNCTION,
|
||||
GumSymbolType_GUM_SYMBOL_OBJECT, GumSymbolType_GUM_SYMBOL_UNKNOWN, GumThreadId, GumTlsKey,
|
||||
gssize, g_free, g_object_get_type, g_object_new,
|
||||
GumModuleInterface, GumThreadId, GumTlsKey, g_free, g_object_get_type, g_object_new,
|
||||
g_once_init_enter, g_once_init_leave, g_strdup, g_type_add_interface_static,
|
||||
g_type_class_peek_parent, g_type_register_static, gchar, gboolean, gpointer, gsize, guint,
|
||||
g_type_class_peek_parent, g_type_register_static, gchar, gpointer, gsize, guint,
|
||||
},
|
||||
gthread, kernel, libc,
|
||||
};
|
||||
@@ -24,9 +22,16 @@ use core::sync::atomic::{AtomicU32, Ordering};
|
||||
#[cfg(feature = "linux")]
|
||||
use crate::gum_linux::enumerate_exports_in_range;
|
||||
#[cfg(any(feature = "linux", feature = "linux-injected"))]
|
||||
use crate::bindings::{
|
||||
GumFoundSymbolFunc, GumSymbolDetails, GumSymbolType_GUM_SYMBOL_FUNCTION,
|
||||
GumSymbolType_GUM_SYMBOL_OBJECT, GumSymbolType_GUM_SYMBOL_UNKNOWN, gboolean, gssize,
|
||||
};
|
||||
#[cfg(any(feature = "linux", feature = "linux-injected"))]
|
||||
use crate::gum_modules::enumerate_symbols_in_range;
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
use crate::gum_windows::enumerate_exports_in_range;
|
||||
use crate::gum_windows::{enumerate_exports_in_range, enumerate_imports_in_module};
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
use crate::bindings::{GumFoundImportFunc, GumImportDetails, GumImportType_GUM_IMPORT_FUNCTION};
|
||||
#[cfg(any(feature = "xnu-core", feature = "linux-injected"))]
|
||||
use crate::gum_injected::enumerate_exports_in_range;
|
||||
|
||||
@@ -181,6 +186,11 @@ extern "C" fn gum_native_module_iface_init(g_iface: gpointer, _iface_data: gpoin
|
||||
(*iface).get_path = Some(crate::signed_to_be_called_back(gum_native_module_get_path, 0));
|
||||
(*iface).get_range = Some(crate::signed_to_be_called_back(gum_native_module_get_range, 0));
|
||||
(*iface).enumerate_exports = Some(crate::signed_to_be_called_back(gum_native_module_enumerate_exports, 0));
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
{
|
||||
(*iface).enumerate_imports =
|
||||
Some(crate::signed_to_be_called_back(gum_native_module_enumerate_imports, 0));
|
||||
}
|
||||
(*iface).find_export_by_name = Some(crate::signed_to_be_called_back(gum_native_module_find_export_by_name, 0));
|
||||
#[cfg(any(feature = "linux", feature = "linux-injected"))]
|
||||
{
|
||||
@@ -314,6 +324,32 @@ unsafe extern "C" fn gum_native_module_enumerate_exports(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
unsafe extern "C" fn gum_native_module_enumerate_imports(
|
||||
self_: *mut GumModule,
|
||||
func: GumFoundImportFunc,
|
||||
user_data: gpointer,
|
||||
) {
|
||||
unsafe {
|
||||
let module = self_ as *mut GumNativeModule;
|
||||
let base = (*module).range.base_address;
|
||||
|
||||
let mut on_import = |library: *const gchar, name: *const gchar, slot: u64, address: u64| {
|
||||
let details = GumImportDetails {
|
||||
type_: GumImportType_GUM_IMPORT_FUNCTION,
|
||||
name,
|
||||
module: library,
|
||||
address,
|
||||
slot,
|
||||
};
|
||||
|
||||
func.unwrap()(&details as *const GumImportDetails, user_data) != 0
|
||||
};
|
||||
|
||||
enumerate_imports_in_module(base, &mut on_import);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "linux", feature = "linux-injected"))]
|
||||
unsafe extern "C" fn gum_native_module_enumerate_symbols(
|
||||
self_: *mut GumModule,
|
||||
@@ -365,6 +401,9 @@ const SYMBOL_IS_FUNCTION: u8 = 2;
|
||||
/// it returns false.
|
||||
pub(crate) type FoundExportCallback<'a> = dyn FnMut(*const gchar, u64) -> bool + 'a;
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
pub(crate) type FoundImportCallback<'a> = dyn FnMut(*const gchar, *const gchar, u64, u64) -> bool + 'a;
|
||||
|
||||
// Code slabs the agent allocates are normal writable RAM, so Gum can keep a real writable alias to
|
||||
// them across the slab's lifetime. Pre-existing kernel text is write-protected — CTRR-locked on
|
||||
// Apple silicon, STRICT_KERNEL_RWX on Linux — and can only be modified through a separate path, so
|
||||
@@ -401,24 +440,6 @@ pub(crate) fn unregister_slab(start: u64) {
|
||||
slab_unlock();
|
||||
}
|
||||
|
||||
// For callers that must not block, primarily a fault handler, which can interrupt the code
|
||||
// that holds the lock. Report a busy registry and let the caller decide.
|
||||
pub(crate) fn is_agent_slab_if_idle(address: u64) -> Option<bool> {
|
||||
if SLAB_LOCK
|
||||
.compare_exchange(0, 1, Ordering::Acquire, Ordering::Relaxed)
|
||||
.is_err()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let found = unsafe {
|
||||
(*core::ptr::addr_of!(SLABS))
|
||||
.iter()
|
||||
.any(|&(begin, end)| address >= begin && address < end)
|
||||
};
|
||||
slab_unlock();
|
||||
Some(found)
|
||||
}
|
||||
|
||||
pub(crate) fn is_agent_slab(address: u64) -> bool {
|
||||
slab_lock();
|
||||
let found = unsafe {
|
||||
@@ -435,7 +456,8 @@ pub(crate) fn is_agent_slab(address: u64) -> bool {
|
||||
mod symbolication {
|
||||
use super::*;
|
||||
use crate::bindings::{
|
||||
GArray, GumAddress, GumDebugSymbolDetails, g_array_append_vals, g_array_new, gconstpointer,
|
||||
GArray, GumAddress, GumDebugSymbolDetails, g_array_append_vals, g_array_new, gboolean,
|
||||
gconstpointer,
|
||||
};
|
||||
use core::ffi::CStr;
|
||||
|
||||
@@ -483,6 +505,11 @@ mod symbolication {
|
||||
return crate::xnu_mapped::export_named(name);
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
if crate::kernel::in_copy() {
|
||||
return crate::kernel::export_named(name);
|
||||
}
|
||||
|
||||
let table = unsafe { &*ptr::addr_of!(crate::SYMBOL_TABLE) };
|
||||
|
||||
match table.find_symbol_by_name(name) {
|
||||
|
||||
@@ -8,26 +8,34 @@ use crate::{
|
||||
FridaCommand,
|
||||
bindings::{
|
||||
_GumPageProtection_GUM_PAGE_EXECUTE, _GumPageProtection_GUM_PAGE_READ,
|
||||
_GumPageProtection_GUM_PAGE_WRITE, _GumRwxSupport_GUM_RWX_FULL,
|
||||
_GumRwxSupport_GUM_RWX_NONE, GArray,
|
||||
GumDebugSymbolDetails, GumFoundRangeFunc, GumFoundThreadFunc, GumMemoryRange,
|
||||
GumModuleRegistry, GumPageProtection, GumRangeDetails, GumRwxSupport, GumThreadDetails,
|
||||
GumThreadFlags, GumThreadId, GumThreadRegistry, gum_barebone_register_thread,
|
||||
gum_barebone_unregister_thread,
|
||||
g_array_append_vals, g_array_new, g_object_unref, g_strdup, g_variant_get_boolean,
|
||||
g_variant_get_uint64, g_variant_new, g_variant_new_fixed_array, g_variant_type_free,
|
||||
g_variant_type_new, g_variant_unref, gboolean, gchar, gconstpointer, gpointer, gsize, guint,
|
||||
gum_barebone_register_module,
|
||||
gum_barebone_try_remap_writable_pages as _gum_barebone_try_remap_writable_pages,
|
||||
gum_mprotect, gum_query_page_size,
|
||||
_GumPageProtection_GUM_PAGE_WRITE, _GumRwxSupport_GUM_RWX_NONE,
|
||||
GumFoundRangeFunc, GumFoundThreadFunc, GumMemoryRange,
|
||||
GumCpuContext, GumModuleRegistry, GumPageProtection, GumRangeDetails, GumRwxSupport,
|
||||
GumThreadDetails, GumThreadFlags, GumThreadFlags_GUM_THREAD_FLAGS_CPU_CONTEXT,
|
||||
GumThreadFlags_GUM_THREAD_FLAGS_STATE, GumThreadId,
|
||||
GumThreadRegistry, gum_barebone_register_thread, g_variant_get_uint64,
|
||||
g_variant_new_fixed_array, g_variant_type_free, g_variant_type_new, g_variant_unref,
|
||||
gboolean, gchar, gconstpointer, gpointer, gsize, guint, gum_mprotect, gum_query_page_size,
|
||||
},
|
||||
gum::{self, FoundExportCallback},
|
||||
host_rpc, kernel, libc,
|
||||
};
|
||||
#[cfg(feature = "xnu-core")]
|
||||
use crate::bindings::{g_object_unref, gum_barebone_register_module};
|
||||
#[cfg(feature = "linux-injected")]
|
||||
use crate::bindings::{
|
||||
GError, GumBareboneStreamOps, g_io_error_from_errno, g_io_error_quark, g_set_error_literal,
|
||||
g_strerror, gint, gssize, gum_barebone_unregister_thread,
|
||||
};
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
use crate::bindings::{
|
||||
g_variant_get_boolean, g_variant_new,
|
||||
gum_barebone_try_remap_writable_pages as _gum_barebone_try_remap_writable_pages,
|
||||
};
|
||||
use alloc::collections::{BTreeMap, BTreeSet};
|
||||
#[cfg(feature = "xnu-core")]
|
||||
use alloc::format;
|
||||
use alloc::vec::Vec;
|
||||
use core::ffi::CStr;
|
||||
use core::mem::size_of;
|
||||
use core::ptr;
|
||||
|
||||
@@ -40,13 +48,6 @@ const MODULE_DIRECTORY: &str = "/System/Library/Extensions/";
|
||||
#[cfg(feature = "xnu-core")]
|
||||
const MODULE_SUFFIX: &str = ".kext";
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
const KERNEL_PATH: &str = "/boot/vmlinux";
|
||||
#[cfg(feature = "linux-injected")]
|
||||
const MODULE_DIRECTORY: &str = "/lib/modules/";
|
||||
#[cfg(feature = "linux-injected")]
|
||||
const MODULE_SUFFIX: &str = ".ko";
|
||||
|
||||
const SHADOW_HEADER: usize = 24;
|
||||
|
||||
#[cfg(feature = "xnu-core")]
|
||||
@@ -137,7 +138,7 @@ fn remap_agent_pages(first_page: gpointer, _n_pages: guint) -> gpointer {
|
||||
fn writable_in_place(first_page: gpointer, n_pages: guint) -> bool {
|
||||
let size = n_pages as usize * unsafe { gum_query_page_size() } as usize;
|
||||
|
||||
kernel::set_protection(first_page as u64, size, _GumPageProtection_GUM_PAGE_RWX)
|
||||
kernel::set_protection(first_page as u64, size, GUM_PAGE_RWX)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
@@ -175,8 +176,53 @@ fn remap_agent_pages_through_host(first_page: gpointer, n_pages: guint) -> gpoin
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "linux-injected", not(target_arch = "arm")))]
|
||||
const GUM_PAGE_RWX: u32 = 7;
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
const _GumPageProtection_GUM_PAGE_RWX: u32 = 7;
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_barebone_query_stream_ops() -> *const GumBareboneStreamOps {
|
||||
if kernel::in_copy() { &STREAM_OPS } else { ptr::null() }
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
static STREAM_OPS: GumBareboneStreamOps = GumBareboneStreamOps {
|
||||
poll: Some(crate::linux::user::frida_poll),
|
||||
read: Some(read_descriptor),
|
||||
write: Some(write_descriptor),
|
||||
close: Some(close_descriptor),
|
||||
};
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
unsafe extern "C" fn read_descriptor(handle: gpointer, buffer: gpointer, count: gsize,
|
||||
error: *mut *mut GError) -> gssize {
|
||||
transferred(crate::linux::user::read(handle as i32, buffer as *mut u8, count as usize), error)
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
unsafe extern "C" fn write_descriptor(handle: gpointer, buffer: gconstpointer, count: gsize,
|
||||
error: *mut *mut GError) -> gssize {
|
||||
transferred(crate::linux::user::write(handle as i32, buffer as *const u8, count as usize),
|
||||
error)
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
unsafe extern "C" fn close_descriptor(handle: gpointer, error: *mut *mut GError) -> gboolean {
|
||||
(transferred(crate::linux::user::close(handle as i32), error) >= 0) as gboolean
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
fn transferred(result: isize, error: *mut *mut GError) -> gssize {
|
||||
if result < 0 {
|
||||
let errno = -result as gint;
|
||||
unsafe {
|
||||
g_set_error_literal(error, g_io_error_quark(), g_io_error_from_errno(errno) as gint,
|
||||
g_strerror(errno))
|
||||
};
|
||||
return -1;
|
||||
}
|
||||
result as gssize
|
||||
}
|
||||
|
||||
unsafe fn what_changed(first_page: u64, shadow: *const u8, total: usize) -> Option<(usize, usize)> {
|
||||
let live = unsafe { core::slice::from_raw_parts(first_page as *const u8, total) };
|
||||
@@ -221,17 +267,13 @@ pub extern "C" fn gum_memory_dispose_writable_pages(writable: gpointer, _n_pages
|
||||
#[cfg(feature = "xnu-kext")]
|
||||
if let Some(base) = crate::xnu::the_page_behind(writable as u64) {
|
||||
let size = _n_pages as usize * unsafe { gum_query_page_size() } as usize;
|
||||
unsafe {
|
||||
libc::__clear_cache(base as *const u8, (base + size as u64) as *const u8);
|
||||
}
|
||||
libc::__clear_cache(base as *const u8, (base + size as u64) as *const u8);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(executable) = aliases().remove(&(writable as u64)) {
|
||||
let size = _n_pages as usize * unsafe { gum_query_page_size() } as usize;
|
||||
unsafe {
|
||||
libc::__clear_cache(executable as *const u8, (executable + size as u64) as *const u8);
|
||||
}
|
||||
libc::__clear_cache(executable as *const u8, (executable + size as u64) as *const u8);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -239,10 +281,8 @@ pub extern "C" fn gum_memory_dispose_writable_pages(writable: gpointer, _n_pages
|
||||
#[cfg(all(feature = "linux-injected", not(target_arch = "arm")))]
|
||||
{
|
||||
let size = _n_pages as usize * unsafe { gum_query_page_size() } as usize;
|
||||
unsafe {
|
||||
libc::__clear_cache(writable as *const u8,
|
||||
(writable as u64 + size as u64) as *const u8);
|
||||
}
|
||||
libc::__clear_cache(writable as *const u8,
|
||||
(writable as u64 + size as u64) as *const u8);
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -366,6 +406,7 @@ fn protect_here(address: u64, size: usize, prot: u32) -> bool {
|
||||
ask_the_host_to_protect(address, size, prot)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
pub fn ask_the_host_to_protect(address: u64, size: usize, prot: u32) -> bool {
|
||||
if !crate::transport_is_up() {
|
||||
return true;
|
||||
@@ -381,6 +422,7 @@ pub fn ask_the_host_to_protect(address: u64, size: usize, prot: u32) -> bool {
|
||||
granted
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
fn the_host_grants_it(address: u64, size: usize, prot: u32) -> bool {
|
||||
unsafe {
|
||||
let payload = g_variant_new(c"(ttu)".as_ptr(), address, size as u64, prot);
|
||||
@@ -401,6 +443,7 @@ fn the_host_grants_it(address: u64, size: usize, prot: u32) -> bool {
|
||||
// bridge, which leaves this CPU's TLB holding the stale translation. Stalker
|
||||
// flips a slab page RW then RX in place, so without this the freeze never takes
|
||||
// effect and executing the page faults with a permission abort.
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
unsafe fn flush_tlb_range(address: u64, size: u64) {
|
||||
let page_size = unsafe { gum_query_page_size() } as u64;
|
||||
let start = address & !(page_size - 1);
|
||||
@@ -409,7 +452,7 @@ unsafe fn flush_tlb_range(address: u64, size: u64) {
|
||||
unsafe { flush_pages(start, end, page_size) };
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "arm")]
|
||||
#[cfg(all(not(feature = "xnu-kext"), target_arch = "arm"))]
|
||||
unsafe fn flush_pages(start: u64, end: u64, page_size: u64) {
|
||||
unsafe {
|
||||
core::arch::asm!("dsb ish", options(nostack, preserves_flags));
|
||||
@@ -423,7 +466,7 @@ unsafe fn flush_pages(start: u64, end: u64, page_size: u64) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
#[cfg(all(not(feature = "xnu-kext"), target_arch = "aarch64"))]
|
||||
unsafe fn flush_pages(start: u64, end: u64, page_size: u64) {
|
||||
unsafe {
|
||||
core::arch::asm!("dsb ish", options(nostack, preserves_flags));
|
||||
@@ -503,7 +546,7 @@ fn release_pages_now(at: gpointer, size: gsize) {
|
||||
|
||||
#[cfg(feature = "xnu-kext")]
|
||||
fn remember_slab_of(at: gpointer, size: gsize) {
|
||||
unsafe { gum::register_slab(at as u64, size as usize) };
|
||||
gum::register_slab(at as u64, size as usize);
|
||||
crate::xnu::remember_what_we_took(at as u64, size as usize, true);
|
||||
}
|
||||
|
||||
@@ -551,13 +594,11 @@ pub extern "C" fn gum_memory_allocate(
|
||||
let ptr = kernel::alloc_heap(size as usize);
|
||||
#[cfg(not(feature = "xnu-core"))]
|
||||
let _ = address;
|
||||
unsafe {
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
core::ptr::write_bytes(ptr, 0, size as usize);
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
unsafe { core::ptr::write_bytes(ptr, 0, size as usize) };
|
||||
|
||||
if may_run {
|
||||
gum::register_slab(ptr as u64, size as usize);
|
||||
}
|
||||
if may_run {
|
||||
gum::register_slab(ptr as u64, size as usize);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
@@ -663,7 +704,7 @@ pub extern "C" fn gum_barebone_on_registry_deactivating(_registry: *mut GumModul
|
||||
pub extern "C" fn gum_barebone_on_thread_registry_activating(registry: *mut GumThreadRegistry) {
|
||||
unsafe { THREAD_REGISTRY = registry };
|
||||
|
||||
kernel::enumerate_threads(&mut |thread| announce_thread(thread.id));
|
||||
kernel::enumerate_threads(&mut |thread| announce_thread(thread.id), false);
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "linux-injected", feature = "xnu-core"))]
|
||||
@@ -672,12 +713,12 @@ pub extern "C" fn gum_barebone_on_thread_registry_deactivating(_registry: *mut G
|
||||
unsafe { THREAD_REGISTRY = ptr::null_mut() };
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "linux-injected", feature = "xnu-core"))]
|
||||
#[cfg(feature = "linux-injected")]
|
||||
pub(crate) fn thread_appeared(id: u32) {
|
||||
announce_thread(id);
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "linux-injected", feature = "xnu-core"))]
|
||||
#[cfg(feature = "linux-injected")]
|
||||
pub(crate) fn thread_vanished(id: u32) {
|
||||
let registry = unsafe { THREAD_REGISTRY };
|
||||
if registry.is_null() {
|
||||
@@ -706,17 +747,97 @@ static mut THREAD_REGISTRY: *mut GumThreadRegistry = ptr::null_mut();
|
||||
#[cfg(any(feature = "linux-injected", feature = "xnu-core"))]
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_barebone_enumerate_threads(func: GumFoundThreadFunc, user_data: gpointer,
|
||||
_flags: GumThreadFlags) {
|
||||
flags: GumThreadFlags) {
|
||||
let Some(emit) = func else {
|
||||
return;
|
||||
};
|
||||
|
||||
let with_registers = (flags & GumThreadFlags_GUM_THREAD_FLAGS_CPU_CONTEXT) != 0;
|
||||
kernel::enumerate_threads(&mut |thread| {
|
||||
let mut details: GumThreadDetails = unsafe { core::mem::zeroed() };
|
||||
details.id = thread.id as GumThreadId;
|
||||
|
||||
if let Some(state) = thread.state {
|
||||
details.flags |= GumThreadFlags_GUM_THREAD_FLAGS_STATE;
|
||||
details.state = state;
|
||||
}
|
||||
|
||||
if let Some(cpu) = thread.cpu_state {
|
||||
details.flags |= GumThreadFlags_GUM_THREAD_FLAGS_CPU_CONTEXT;
|
||||
details.cpu_context = cpu_context_from(&cpu);
|
||||
}
|
||||
|
||||
unsafe { emit(&details, user_data) };
|
||||
});
|
||||
}, with_registers);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn cpu_context_from(state: &kernel::CpuState) -> GumCpuContext {
|
||||
GumCpuContext {
|
||||
pc: state.pc,
|
||||
sp: state.sp,
|
||||
nzcv: state.nzcv,
|
||||
x: state.x,
|
||||
fp: state.fp,
|
||||
lr: state.lr,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
fn cpu_context_from(state: &kernel::CpuState) -> GumCpuContext {
|
||||
GumCpuContext {
|
||||
rip: state.rip,
|
||||
r15: state.r15,
|
||||
r14: state.r14,
|
||||
r13: state.r13,
|
||||
r12: state.r12,
|
||||
r11: state.r11,
|
||||
r10: state.r10,
|
||||
r9: state.r9,
|
||||
r8: state.r8,
|
||||
rdi: state.rdi,
|
||||
rsi: state.rsi,
|
||||
rbp: state.rbp,
|
||||
rsp: state.rsp,
|
||||
rbx: state.rbx,
|
||||
rdx: state.rdx,
|
||||
rcx: state.rcx,
|
||||
rax: state.rax,
|
||||
xmm: ptr::null_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
fn cpu_context_from(state: &kernel::CpuState) -> GumCpuContext {
|
||||
GumCpuContext {
|
||||
eip: state.eip,
|
||||
edi: state.edi,
|
||||
esi: state.esi,
|
||||
ebp: state.ebp,
|
||||
esp: state.esp,
|
||||
ebx: state.ebx,
|
||||
edx: state.edx,
|
||||
ecx: state.ecx,
|
||||
eax: state.eax,
|
||||
xmm: ptr::null_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "arm")]
|
||||
fn cpu_context_from(state: &kernel::CpuState) -> GumCpuContext {
|
||||
GumCpuContext {
|
||||
cpsr: state.cpsr,
|
||||
pc: state.pc,
|
||||
sp: state.sp,
|
||||
r8: state.r8,
|
||||
r9: state.r9,
|
||||
r10: state.r10,
|
||||
r11: state.r11,
|
||||
r12: state.r12,
|
||||
lr: state.lr,
|
||||
r: state.r,
|
||||
..unsafe { core::mem::zeroed() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "linux-injected", feature = "xnu-core"))]
|
||||
@@ -730,7 +851,7 @@ pub extern "C" fn _gum_process_enumerate_ranges(
|
||||
return;
|
||||
};
|
||||
|
||||
let mut report = |base: u64, size: u64, protection: u32| {
|
||||
let report = |base: u64, size: u64, protection: u32| {
|
||||
if (protection & prot as u32) != prot as u32 {
|
||||
return;
|
||||
}
|
||||
@@ -864,3 +985,47 @@ pub(crate) unsafe fn enumerate_exports_in_range(
|
||||
pub extern "C" fn gum_load_symbols(_path: *const gchar) -> gboolean {
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_thread_get_system_error() -> gint {
|
||||
match errno_slot() {
|
||||
Some(slot) => unsafe { *slot },
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_thread_set_system_error(value: gint) {
|
||||
if let Some(slot) = errno_slot() {
|
||||
unsafe { *slot = value };
|
||||
}
|
||||
}
|
||||
|
||||
// errno is thread-local behind a function that hands back its address:
|
||||
// __errno_location on glibc and musl, __errno on Bionic.
|
||||
#[cfg(feature = "linux-injected")]
|
||||
fn errno_slot() -> Option<*mut gint> {
|
||||
use core::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
if !crate::kernel::in_copy() {
|
||||
return None;
|
||||
}
|
||||
|
||||
static LOCATE: AtomicUsize = AtomicUsize::new(0);
|
||||
let mut locate = LOCATE.load(Ordering::Relaxed);
|
||||
if locate == 0 {
|
||||
locate = crate::kernel::export_named("__errno_location") as usize;
|
||||
if locate == 0 {
|
||||
locate = crate::kernel::export_named("__errno") as usize;
|
||||
}
|
||||
if locate == 0 {
|
||||
return None;
|
||||
}
|
||||
LOCATE.store(locate, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
let locate: unsafe extern "C" fn() -> *mut gint = unsafe { core::mem::transmute(locate) };
|
||||
Some(unsafe { locate() })
|
||||
}
|
||||
@@ -6,15 +6,14 @@ use crate::{
|
||||
bindings::{
|
||||
_GumPageProtection_GUM_PAGE_EXECUTE, _GumPageProtection_GUM_PAGE_READ,
|
||||
_GumPageProtection_GUM_PAGE_WRITE, _GumRwxSupport_GUM_RWX_NONE, GArray,
|
||||
GumDebugSymbolDetails, GumMemoryRange, GumModuleRegistry, GumPageProtection, GumRwxSupport,
|
||||
g_array_append_vals, g_array_new, g_object_unref, g_pattern_spec_free, g_pattern_spec_match_string,
|
||||
GumDebugSymbolDetails, GumModuleRegistry, GumPageProtection, GumRwxSupport,
|
||||
g_array_append_vals, g_array_new, g_pattern_spec_free, g_pattern_spec_match_string,
|
||||
g_pattern_spec_new, g_strdup, gboolean, gchar, gconstpointer, gpointer, gsize, guint,
|
||||
gum_barebone_register_module, gum_mprotect,
|
||||
gum_mprotect,
|
||||
},
|
||||
gum::{self, FoundExportCallback},
|
||||
kernel,
|
||||
};
|
||||
use alloc::format;
|
||||
use core::ffi::CStr;
|
||||
use core::ptr;
|
||||
|
||||
|
||||
@@ -3,26 +3,240 @@
|
||||
|
||||
use crate::{
|
||||
bindings::{
|
||||
_GumPageProtection_GUM_PAGE_EXECUTE, _GumRwxSupport_GUM_RWX_FULL, GumMemoryRange,
|
||||
GumModuleRegistry, GumPageProtection, GumRwxSupport, g_object_unref, gboolean, gpointer,
|
||||
gsize, guint, gum_barebone_register_module, gum_mprotect, GumFoundRangeFunc,
|
||||
GumFoundThreadFunc, GumModifyThreadFlags, GumModifyThreadFunc, GumRangeDetails,
|
||||
GumThreadDetails, GumThreadFlags, GumThreadId, GumThreadRegistry,
|
||||
_GumPageProtection_GUM_PAGE_EXECUTE, _GumRwxSupport_GUM_RWX_FULL, GError,
|
||||
GIOErrorEnum_G_IO_ERROR_BROKEN_PIPE, GIOErrorEnum_G_IO_ERROR_FAILED,
|
||||
GIOErrorEnum_G_IO_ERROR_INVALID_ARGUMENT, GIOErrorEnum_G_IO_ERROR_NOT_FOUND,
|
||||
GIOErrorEnum_G_IO_ERROR_PERMISSION_DENIED, GumBareboneStreamOps, GumMemoryRange,
|
||||
GumModuleRegistry, GumPageProtection, GumRwxSupport, g_free, g_io_error_quark, g_malloc,
|
||||
g_object_unref, g_set_error_literal, g_utf8_to_utf16, g_utf16_to_utf8, gboolean, gchar,
|
||||
gint, gpointer, gsize, gssize, guint, gum_barebone_register_module, gum_mprotect,
|
||||
GumFoundRangeFunc, GumFoundThreadFunc, GumModifyThreadFlags, GumModifyThreadFunc,
|
||||
GumRangeDetails, GumThreadDetails, GumThreadFlags, GumThreadId, GumThreadRegistry,
|
||||
gconstpointer, gum_thread_details_copy,
|
||||
},
|
||||
gum::{self, FoundExportCallback},
|
||||
gum::{self, FoundExportCallback, FoundImportCallback},
|
||||
kernel,
|
||||
};
|
||||
use crate::bindings::{GumCpuContext, GumThreadFlags_GUM_THREAD_FLAGS_CPU_CONTEXT};
|
||||
use alloc::ffi::CString;
|
||||
#[cfg(not(feature = "winnt"))]
|
||||
use alloc::format;
|
||||
use alloc::string::String;
|
||||
use alloc::vec::Vec;
|
||||
use core::ptr;
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
macro_rules! windows_fn {
|
||||
($($argument:ty),* $(,)?) => { unsafe extern "stdcall" fn($($argument),*) };
|
||||
($($argument:ty),* $(,)? => $result:ty) => {
|
||||
unsafe extern "stdcall" fn($($argument),*) -> $result
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
macro_rules! windows_fn {
|
||||
($($argument:ty),* $(,)?) => { unsafe extern "win64" fn($($argument),*) };
|
||||
($($argument:ty),* $(,)? => $result:ty) => {
|
||||
unsafe extern "win64" fn($($argument),*) -> $result
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
macro_rules! windows_fn {
|
||||
($($argument:ty),* $(,)?) => { unsafe extern "C" fn($($argument),*) };
|
||||
($($argument:ty),* $(,)? => $result:ty) => {
|
||||
unsafe extern "C" fn($($argument),*) -> $result
|
||||
};
|
||||
}
|
||||
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use windows_fn;
|
||||
|
||||
pub struct FileApi {
|
||||
pub read_file: windows_fn!(usize, *mut u8, u32, *mut u32, usize => i32),
|
||||
pub write_file: windows_fn!(usize, *const u8, u32, *mut u32, usize => i32),
|
||||
pub close_handle: windows_fn!(usize => i32),
|
||||
pub format_message: windows_fn!(u32, usize, u32, u32, *mut u8, u32, usize => u32),
|
||||
}
|
||||
|
||||
pub struct TextApi {
|
||||
pub multi_byte_to_wide_char: windows_fn!(u32, u32, *const u8, i32, *mut u16, i32 => i32),
|
||||
pub wide_char_to_multi_byte:
|
||||
windows_fn!(u32, u32, *const u16, i32, *mut u8, i32, usize, usize => i32),
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_barebone_query_platform() -> *const crate::bindings::gchar {
|
||||
c"windows".as_ptr() as *const crate::bindings::gchar
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_thread_get_system_error() -> crate::bindings::gint {
|
||||
kernel::thread_error() as crate::bindings::gint
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_thread_set_system_error(value: crate::bindings::gint) {
|
||||
kernel::set_thread_error(value as u32)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_barebone_ansi_string_to_utf8(str_ansi: *const gchar, length: gint) -> *mut gchar {
|
||||
let ansi = unsafe { bytes_of(str_ansi as *const u8, length) };
|
||||
match kernel::text_api() {
|
||||
Some(api) => ansi_to_utf8(api, ansi),
|
||||
None => handed_to_glib(ansi.iter().map(|&byte| byte as char).collect::<String>().as_bytes()),
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_barebone_ansi_string_from_utf8(str_utf8: *const gchar) -> *mut gchar {
|
||||
match kernel::text_api() {
|
||||
Some(api) => ansi_from_utf8(api, str_utf8),
|
||||
None => {
|
||||
let utf8 = unsafe { core::ffi::CStr::from_ptr(str_utf8) }.to_str().unwrap();
|
||||
let latin1: Vec<u8> =
|
||||
utf8.chars().map(|c| if (c as u32) <= 0xff { c as u8 } else { b'?' }).collect();
|
||||
handed_to_glib(&latin1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn bytes_of<'a>(str: *const u8, length: gint) -> &'a [u8] {
|
||||
let length = if length < 0 {
|
||||
unsafe { core::ffi::CStr::from_ptr(str as *const core::ffi::c_char) }.to_bytes().len()
|
||||
} else {
|
||||
length as usize
|
||||
};
|
||||
unsafe { core::slice::from_raw_parts(str, length) }
|
||||
}
|
||||
|
||||
fn ansi_to_utf8(api: &TextApi, ansi: &[u8]) -> *mut gchar {
|
||||
let count = unsafe {
|
||||
(api.multi_byte_to_wide_char)(CP_ACP, 0, ansi.as_ptr(), ansi.len() as i32,
|
||||
ptr::null_mut(), 0)
|
||||
};
|
||||
let mut wide = alloc::vec![0u16; count as usize];
|
||||
unsafe {
|
||||
(api.multi_byte_to_wide_char)(CP_ACP, 0, ansi.as_ptr(), ansi.len() as i32,
|
||||
wide.as_mut_ptr(), count);
|
||||
g_utf16_to_utf8(wide.as_ptr(), count as _, ptr::null_mut(), ptr::null_mut(),
|
||||
ptr::null_mut())
|
||||
}
|
||||
}
|
||||
|
||||
fn ansi_from_utf8(api: &TextApi, utf8: *const gchar) -> *mut gchar {
|
||||
unsafe {
|
||||
let wide = g_utf8_to_utf16(utf8, -1, ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
|
||||
let size = (api.wide_char_to_multi_byte)(CP_ACP, 0, wide, -1, ptr::null_mut(), 0, 0, 0);
|
||||
let ansi = g_malloc(size as gsize) as *mut u8;
|
||||
(api.wide_char_to_multi_byte)(CP_ACP, 0, wide, -1, ansi, size, 0, 0);
|
||||
g_free(wide as gpointer);
|
||||
ansi as *mut gchar
|
||||
}
|
||||
}
|
||||
|
||||
fn handed_to_glib(bytes: &[u8]) -> *mut gchar {
|
||||
unsafe {
|
||||
let copy = g_malloc((bytes.len() + 1) as gsize) as *mut u8;
|
||||
ptr::copy_nonoverlapping(bytes.as_ptr(), copy, bytes.len());
|
||||
*copy.add(bytes.len()) = 0;
|
||||
copy as *mut gchar
|
||||
}
|
||||
}
|
||||
|
||||
const CP_ACP: u32 = 0;
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_barebone_query_stream_ops() -> *const GumBareboneStreamOps {
|
||||
if kernel::in_copy() { &STREAM_OPS } else { ptr::null() }
|
||||
}
|
||||
|
||||
static STREAM_OPS: GumBareboneStreamOps = GumBareboneStreamOps {
|
||||
poll: Some(kernel::poll_handles),
|
||||
read: Some(read_handle),
|
||||
write: Some(write_handle),
|
||||
close: Some(close_handle),
|
||||
};
|
||||
|
||||
unsafe extern "C" fn read_handle(handle: gpointer, buffer: gpointer, count: gsize,
|
||||
error: *mut *mut GError) -> gssize {
|
||||
let mut transferred = 0u32;
|
||||
let succeeded = unsafe {
|
||||
(kernel::file_api().read_file)(handle as usize, buffer as *mut u8, count as u32,
|
||||
&mut transferred, 0)
|
||||
};
|
||||
if succeeded == 0 {
|
||||
return failed(error);
|
||||
}
|
||||
transferred as gssize
|
||||
}
|
||||
|
||||
unsafe extern "C" fn write_handle(handle: gpointer, buffer: gconstpointer, count: gsize,
|
||||
error: *mut *mut GError) -> gssize {
|
||||
let mut transferred = 0u32;
|
||||
let succeeded = unsafe {
|
||||
(kernel::file_api().write_file)(handle as usize, buffer as *const u8, count as u32,
|
||||
&mut transferred, 0)
|
||||
};
|
||||
if succeeded == 0 {
|
||||
return failed(error);
|
||||
}
|
||||
transferred as gssize
|
||||
}
|
||||
|
||||
unsafe extern "C" fn close_handle(handle: gpointer, error: *mut *mut GError) -> gboolean {
|
||||
let succeeded = unsafe { (kernel::file_api().close_handle)(handle as usize) };
|
||||
if succeeded == 0 {
|
||||
failed(error);
|
||||
return 0;
|
||||
}
|
||||
1
|
||||
}
|
||||
|
||||
fn failed(error: *mut *mut GError) -> gssize {
|
||||
let code = kernel::thread_error();
|
||||
let message = CString::new(describe_error(code)).unwrap();
|
||||
unsafe {
|
||||
g_set_error_literal(error, g_io_error_quark(), io_error_from_win32(code) as gint,
|
||||
message.as_ptr())
|
||||
};
|
||||
-1
|
||||
}
|
||||
|
||||
fn describe_error(code: u32) -> String {
|
||||
let mut ansi = [0u8; 512];
|
||||
let length = unsafe {
|
||||
(kernel::file_api().format_message)(
|
||||
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, code, 0,
|
||||
ansi.as_mut_ptr(), ansi.len() as u32, 0)
|
||||
};
|
||||
let utf8 = ansi_to_utf8(kernel::text_api().unwrap(), &ansi[..length as usize]);
|
||||
let message = unsafe { core::ffi::CStr::from_ptr(utf8) }.to_str().unwrap().trim_end();
|
||||
let described = String::from(message);
|
||||
unsafe { g_free(utf8 as gpointer) };
|
||||
described
|
||||
}
|
||||
|
||||
fn io_error_from_win32(code: u32) -> u32 {
|
||||
match code {
|
||||
ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => GIOErrorEnum_G_IO_ERROR_NOT_FOUND,
|
||||
ERROR_ACCESS_DENIED => GIOErrorEnum_G_IO_ERROR_PERMISSION_DENIED,
|
||||
ERROR_INVALID_HANDLE | ERROR_INVALID_PARAMETER => GIOErrorEnum_G_IO_ERROR_INVALID_ARGUMENT,
|
||||
ERROR_BROKEN_PIPE => GIOErrorEnum_G_IO_ERROR_BROKEN_PIPE,
|
||||
_ => GIOErrorEnum_G_IO_ERROR_FAILED,
|
||||
}
|
||||
}
|
||||
|
||||
const FORMAT_MESSAGE_IGNORE_INSERTS: u32 = 0x200;
|
||||
const FORMAT_MESSAGE_FROM_SYSTEM: u32 = 0x1000;
|
||||
const ERROR_FILE_NOT_FOUND: u32 = 2;
|
||||
const ERROR_PATH_NOT_FOUND: u32 = 3;
|
||||
const ERROR_ACCESS_DENIED: u32 = 5;
|
||||
const ERROR_INVALID_HANDLE: u32 = 6;
|
||||
const ERROR_INVALID_PARAMETER: u32 = 87;
|
||||
const ERROR_BROKEN_PIPE: u32 = 109;
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn gum_barebone_query_stack_size() -> crate::bindings::gsize {
|
||||
if crate::on_js_thread() {
|
||||
@@ -170,7 +384,7 @@ pub(crate) fn watch_the_loader() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
#[cfg(feature = "winnt")]
|
||||
pub(crate) fn forget_the_loader() {
|
||||
let Some(entries) = kernel::loader_entry_points() else {
|
||||
return;
|
||||
@@ -194,7 +408,7 @@ pub(crate) fn loader_load() -> gpointer {
|
||||
unsafe { LOADER_LOAD }
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
#[cfg(feature = "win9x")]
|
||||
pub(crate) fn loader_load_with_flags() -> gpointer {
|
||||
unsafe { LOADER_LOAD_WITH_FLAGS }
|
||||
}
|
||||
@@ -412,10 +626,6 @@ fn forget_the_threads() {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn thread_appeared(id: u32) {
|
||||
announce_thread(id);
|
||||
}
|
||||
|
||||
pub(crate) fn thread_appeared_at(id: u32, routine: usize, parameter: usize) {
|
||||
let registry = unsafe { THREAD_REGISTRY };
|
||||
if registry.is_null() {
|
||||
@@ -657,6 +867,14 @@ const INTEGER_OVERFLOW: u32 = 0xc000_0095;
|
||||
const BREAKPOINT: u32 = 0x8000_0003;
|
||||
const SINGLE_STEP: u32 = 0x8000_0004;
|
||||
|
||||
pub(crate) unsafe fn enumerate_imports_in_module(base: u64, callback: &mut FoundImportCallback) {
|
||||
if crate::running_in_a_process() {
|
||||
kernel::enumerate_imports(base as _, &mut |library, name, slot, address| {
|
||||
callback(library as *const crate::bindings::gchar, name as *const crate::bindings::gchar, slot, address)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn enumerate_exports_in_range(
|
||||
start_address: u64,
|
||||
end_address: u64,
|
||||
|
||||
@@ -101,6 +101,7 @@ impl Drop for Hostlink {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "xnu-kext")]
|
||||
pub fn a_turn_is_wanted() -> bool {
|
||||
unsafe { frida_kmod_link_pending() }
|
||||
}
|
||||
@@ -115,5 +116,6 @@ unsafe extern "C" {
|
||||
fn frida_kmod_link_close();
|
||||
fn frida_kmod_link_send(data: *const c_void, size: usize) -> c_int;
|
||||
fn frida_kmod_link_recv(data: *mut c_void, size: usize) -> isize;
|
||||
#[cfg(feature = "xnu-kext")]
|
||||
fn frida_kmod_link_pending() -> bool;
|
||||
}
|
||||
@@ -404,15 +404,12 @@ const ALMOST_FOREVER: u32 = u32::MAX - 1;
|
||||
const STATUS_PENDING: i32 = 0x103;
|
||||
const SYNCHRONIZATION_EVENT: u32 = 1;
|
||||
const EVENT_ALL_ACCESS: u32 = 0x1f_0003;
|
||||
const EXECUTIVE: u32 = 0;
|
||||
const KERNEL_MODE: u32 = 0;
|
||||
|
||||
const KEY_READ: u32 = 0x2_0019;
|
||||
const GENERIC_READ: u32 = 0x8000_0000;
|
||||
const GENERIC_WRITE: u32 = 0x4000_0000;
|
||||
const SYNCHRONIZE: u32 = 0x0010_0000;
|
||||
const FILE_OPEN: u32 = 1;
|
||||
const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x20;
|
||||
const OBJ_CASE_INSENSITIVE: usize = 0x40;
|
||||
const OBJ_KERNEL_HANDLE: usize = 0x200;
|
||||
|
||||
|
||||
@@ -51,7 +51,9 @@ const F_MULTIPORT: u64 = 1u64 << 1;
|
||||
|
||||
const INT_VRING: u32 = 1;
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PCI_CONFIG_ADDRESS: u16 = 0xcf8;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PCI_CONFIG_DATA: u16 = 0xcfc;
|
||||
|
||||
const PCI_VENDOR_VIRTIO: u16 = 0x1af4;
|
||||
@@ -62,14 +64,18 @@ const PCI_COMMAND: u8 = 0x04;
|
||||
const PCI_CAP_LIST_POINTER: u8 = 0x34;
|
||||
const PCI_INTERRUPT_LINE: u8 = 0x3c;
|
||||
const PCI_BASE_ADDRESS_0: u8 = 0x10;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PCI_INTERRUPT_PIN: u8 = 0x3d;
|
||||
const PCI_COMMAND_INTX_DISABLE: u32 = 0x400;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const ISA_BRIDGE_DEVFN: u8 = 0x08;
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
|
||||
const ECAM_DEVFN_SHIFT: usize = 12;
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
|
||||
const ECAM_BUS_SIZE: u64 = 256 * 4096;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PIRQ_ROUTE: u8 = 0x60;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PIRQ_DISABLED: u32 = 1 << 7;
|
||||
|
||||
const PCI_COMMAND_MEMORY: u32 = 1 << 1;
|
||||
@@ -867,6 +873,7 @@ extern "C" fn isr_wake(token: *mut c_void, _refcon: *mut c_void, _nub: *mut c_vo
|
||||
crate::nudge_the_loop(token as *const u8);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xnu-core"))]
|
||||
pub fn a_turn_is_wanted() -> bool {
|
||||
A_TURN_IS_WANTED.load(core::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -903,9 +910,7 @@ impl Regs {
|
||||
while r8(p.common, COMMON_STATUS) != 0 {
|
||||
left -= 1;
|
||||
if left == 0 {
|
||||
unsafe {
|
||||
kernel::log("virtio: reset not taken\n");
|
||||
}
|
||||
kernel::log("virtio: reset not taken\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1021,6 +1026,7 @@ impl Regs {
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct Bus {
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64", feature = "linux-injected"))]
|
||||
number: u8,
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
|
||||
config: *mut u8,
|
||||
@@ -1035,7 +1041,11 @@ impl Bus {
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
|
||||
fn first(ecam: u64) -> Self {
|
||||
let config = kernel::map_io(ecam, ECAM_BUS_SIZE) as *mut u8;
|
||||
Bus { number: 0, config }
|
||||
Bus {
|
||||
#[cfg(feature = "linux-injected")]
|
||||
number: 0,
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
@@ -1046,7 +1056,9 @@ impl Bus {
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
|
||||
fn function(&self, devfn: u8) -> PciDevice {
|
||||
PciDevice {
|
||||
#[cfg(feature = "linux-injected")]
|
||||
bus: self.number,
|
||||
#[cfg(feature = "linux-injected")]
|
||||
devfn,
|
||||
config: unsafe { self.config.add((devfn as usize) << ECAM_DEVFN_SHIFT) },
|
||||
}
|
||||
@@ -1055,7 +1067,9 @@ impl Bus {
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct PciDevice {
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64", feature = "linux-injected"))]
|
||||
bus: u8,
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64", feature = "linux-injected"))]
|
||||
devfn: u8,
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
|
||||
config: *mut u8,
|
||||
@@ -1207,6 +1221,7 @@ impl PciDevice {
|
||||
.find(|candidate| (candidate & PIRQ_DISABLED) == 0)
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64", feature = "linux-injected"))]
|
||||
fn line_in_config(&self) -> Option<u32> {
|
||||
match self.read_config_byte(PCI_INTERRUPT_LINE) {
|
||||
0 => None,
|
||||
@@ -1232,6 +1247,7 @@ impl PciDevice {
|
||||
(self.read_config(offset) >> ((offset & 3) * 8)) as u8
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
fn write_config_byte(&self, offset: u8, value: u8) {
|
||||
let shift = (offset & 3) * 8;
|
||||
let others = self.read_config(offset) & !(0xff << shift);
|
||||
|
||||
@@ -8,8 +8,6 @@ use core::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use crate::kernel;
|
||||
|
||||
const AF_VSOCK: c_int = 40;
|
||||
const SOCK_STREAM: c_int = 1;
|
||||
const VMADDR_CID_HOST: u32 = 2;
|
||||
|
||||
@@ -87,13 +87,13 @@ fn write_identity(company: &[u8], program: &[u8], into: &mut [u8]) -> usize {
|
||||
};
|
||||
|
||||
let mut written = 0;
|
||||
let mut put = |byte: u8, into: &mut [u8], written: &mut usize| {
|
||||
let put = |byte: u8, into: &mut [u8], written: &mut usize| {
|
||||
if *written != into.len() {
|
||||
into[*written] = byte;
|
||||
*written += 1;
|
||||
}
|
||||
};
|
||||
let mut put_word = |word: &[u8], into: &mut [u8], written: &mut usize| {
|
||||
let put_word = |word: &[u8], into: &mut [u8], written: &mut usize| {
|
||||
for byte in word {
|
||||
if byte.is_ascii_alphanumeric() {
|
||||
put(byte.to_ascii_lowercase(), into, written);
|
||||
|
||||
@@ -37,6 +37,7 @@ pub type ThreadEntry = unsafe extern "C" fn(parameter: *mut c_void, wait_result:
|
||||
|
||||
pub struct ThreadInfo {
|
||||
pub id: u32,
|
||||
pub state: Option<crate::bindings::GumThreadState>,
|
||||
pub cpu_state: Option<CpuState>,
|
||||
}
|
||||
|
||||
|
||||
+163
-67
@@ -25,19 +25,12 @@ use core::ptr;
|
||||
use core::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use bindings::{
|
||||
GAsyncResult, GBytes, GError, GMainContext, GObject, GSource, GSourceFunc, GSourceFuncs,
|
||||
GVariant, GumMemoryRange, gboolean, g_main_context_acquire, g_main_context_check,
|
||||
g_main_context_dispatch, g_main_context_prepare, g_main_context_query, g_main_context_release,
|
||||
g_main_context_wakeup,
|
||||
g_source_attach, g_source_new, g_source_unref,
|
||||
GAsyncResult, GBytes, GError, GMainContext, GObject, GVariant, GumMemoryRange,
|
||||
GumScript, GumScriptBackend, g_error_free, g_free, g_main_context_iteration,
|
||||
g_main_context_push_thread_default, g_memdup2, g_object_unref, g_variant_check_format_string,
|
||||
g_variant_get, g_variant_get_boolean, g_variant_get_child_value, g_variant_get_data,
|
||||
g_variant_get_size, g_variant_get_string, g_variant_get_strv,
|
||||
g_variant_get, g_variant_get_data, g_variant_get_size, g_variant_get_string,
|
||||
g_variant_get_uint32, 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_builder_add, g_variant_builder_add_value, g_variant_builder_close,
|
||||
g_variant_builder_end, g_variant_builder_new, g_variant_builder_open,
|
||||
g_variant_new_fixed_array, g_variant_get_fixed_array, g_bytes_new, g_bytes_get_data,
|
||||
g_bytes_unref, GVariantType,
|
||||
g_variant_unref, gchar, gpointer, gsize, gum_script_backend_create,
|
||||
@@ -47,12 +40,20 @@ use bindings::{
|
||||
gum_script_scheduler_get_js_context, gum_script_set_message_handler, gum_script_unload,
|
||||
gum_script_unload_finish, gum_stalker_exclude,
|
||||
};
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
use bindings::{
|
||||
GSource, GSourceFunc, GSourceFuncs, gboolean, g_main_context_wakeup, g_source_attach,
|
||||
g_source_new, g_source_unref, g_variant_builder_add, g_variant_builder_add_value,
|
||||
g_variant_builder_close, g_variant_builder_end, g_variant_builder_new, g_variant_builder_open,
|
||||
g_variant_get_boolean, g_variant_get_child_value,
|
||||
};
|
||||
|
||||
mod ffi;
|
||||
mod glib;
|
||||
mod gthread;
|
||||
mod gum;
|
||||
mod libc;
|
||||
#[cfg(any(feature = "win9x", feature = "winnt", feature = "linux-injected", feature = "xnu-core"))]
|
||||
mod ring;
|
||||
|
||||
pub mod kernel;
|
||||
@@ -143,25 +144,27 @@ mod bindings {
|
||||
#[repr(u8)]
|
||||
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
|
||||
pub enum FridaCommand {
|
||||
CreateScript = 1,
|
||||
LoadScript = 2,
|
||||
DestroyScript = 3,
|
||||
PostScriptMessage = 4,
|
||||
RemapWritablePages = 5,
|
||||
MemoryProtect = 6,
|
||||
PatchCode = 7,
|
||||
EnumerateProcesses = 8,
|
||||
InjectIntoProcess = 9,
|
||||
AllocateShared = 10,
|
||||
DetachFromProcess = 11,
|
||||
PlaceAgentInProcess = 12,
|
||||
StartAgentInProcess = 13,
|
||||
SpawnProcess = 14,
|
||||
ResumeProcess = 15,
|
||||
Stop = 16,
|
||||
GateSpawns = 17,
|
||||
EnumerateApplications = 18,
|
||||
EnumerateShortcuts = 19,
|
||||
EnumerateApplications = 1,
|
||||
EnumerateShortcuts = 2,
|
||||
EnumerateProcesses = 3,
|
||||
GateSpawns = 4,
|
||||
ArmNamedSpawn = 5,
|
||||
DisarmNamedSpawn = 6,
|
||||
SpawnProcess = 7,
|
||||
ResumeProcess = 8,
|
||||
Stop = 9,
|
||||
InjectIntoProcess = 10,
|
||||
PlaceAgentInProcess = 11,
|
||||
StartAgentInProcess = 12,
|
||||
AllocateShared = 13,
|
||||
RemapWritablePages = 14,
|
||||
MemoryProtect = 15,
|
||||
PatchCode = 16,
|
||||
DetachFromProcess = 17,
|
||||
CreateScript = 18,
|
||||
DestroyScript = 19,
|
||||
LoadScript = 20,
|
||||
PostScriptMessage = 21,
|
||||
|
||||
Reply = 128,
|
||||
ScriptMessage = 129,
|
||||
@@ -184,6 +187,8 @@ impl core::fmt::Display for FridaCommand {
|
||||
FridaCommand::RemapWritablePages => write!(f, "RemapWritablePages"),
|
||||
FridaCommand::MemoryProtect => write!(f, "MemoryProtect"),
|
||||
FridaCommand::PatchCode => write!(f, "PatchCode"),
|
||||
FridaCommand::ArmNamedSpawn => write!(f, "ArmNamedSpawn"),
|
||||
FridaCommand::DisarmNamedSpawn => write!(f, "DisarmNamedSpawn"),
|
||||
FridaCommand::EnumerateProcesses => write!(f, "EnumerateProcesses"),
|
||||
FridaCommand::InjectIntoProcess => write!(f, "InjectIntoProcess"),
|
||||
FridaCommand::AllocateShared => write!(f, "AllocateShared"),
|
||||
@@ -728,10 +733,6 @@ mod entrypoint_linux {
|
||||
STOP_REQUESTED.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn start_worker() {
|
||||
kernel::spawn_thread(worker, 12345usize as *mut c_void);
|
||||
}
|
||||
|
||||
unsafe extern "C" fn worker(_parameter: *mut c_void, _wait_result: i32) {
|
||||
unsafe {
|
||||
kernel::log("frida: worker entry\n\0");
|
||||
@@ -840,7 +841,7 @@ impl Transport {
|
||||
|
||||
// Configuration space is reached through I/O ports where there are any, and only a machine
|
||||
// without them is told where it is mapped instead.
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
|
||||
#[cfg(all(feature = "blob", any(target_arch = "aarch64", target_arch = "arm")))]
|
||||
unsafe fn where_configuration_space_is_mapped(transport: *mut GVariant) -> u64 {
|
||||
use crate::bindings::{g_variant_get_child_value, g_variant_get_uint64, g_variant_unref};
|
||||
|
||||
@@ -853,7 +854,7 @@ unsafe fn where_configuration_space_is_mapped(transport: *mut GVariant) -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
#[cfg(all(feature = "blob", any(target_arch = "x86", target_arch = "x86_64")))]
|
||||
unsafe fn where_configuration_space_is_mapped(_transport: *mut GVariant) -> u64 {
|
||||
0
|
||||
}
|
||||
@@ -883,6 +884,7 @@ fn transport_set(driver: Transport) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "blob")]
|
||||
fn tell_the_host_we_are_listening() {
|
||||
unsafe {
|
||||
let message = g_variant_new(
|
||||
@@ -939,7 +941,7 @@ static mut SCRIPTS: BTreeMap<u32, *mut GumScript> = BTreeMap::new();
|
||||
static NEXT_SCRIPT_ID: AtomicU32 = AtomicU32::new(1);
|
||||
// A copy of the agent runs the same code, but it cannot share what gets written to. Thus keep
|
||||
// the writable half as it is before anything writes to it.
|
||||
#[cfg(any(feature = "win9x", feature = "winnt", feature = "linux-injected", feature = "xnu-core"))]
|
||||
#[cfg(any(feature = "win9x", feature = "winnt", feature = "linux-injected", feature = "xnu"))]
|
||||
pub(crate) unsafe fn preserve_writable_half() {
|
||||
let size = writable_half_size();
|
||||
let pristine = kernel::alloc(size);
|
||||
@@ -1032,9 +1034,11 @@ fn writable_half_size() -> usize {
|
||||
|
||||
// A relocation names the slot first, and the rest of it says the same thing as the value that
|
||||
// the slot already holds.
|
||||
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
|
||||
#[cfg(all(any(feature = "win9x", feature = "winnt", feature = "linux-injected",
|
||||
feature = "xnu-core"), any(target_arch = "x86", target_arch = "arm")))]
|
||||
const RELOCATION_SIZE: usize = 8;
|
||||
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
|
||||
#[cfg(all(any(feature = "win9x", feature = "winnt", feature = "linux-injected",
|
||||
feature = "xnu-core"), any(target_arch = "x86_64", target_arch = "aarch64")))]
|
||||
const RELOCATION_SIZE: usize = 24;
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt", feature = "linux-injected", feature = "xnu-core"))]
|
||||
@@ -1067,6 +1071,7 @@ unsafe extern "C" {
|
||||
|
||||
// A copy runs at a base of its own, thus the half that placed it there says where. The
|
||||
// Stalker keeps out of this range: it must not instrument the runtime it runs on.
|
||||
#[cfg(any(feature = "win9x", feature = "winnt", feature = "xnu-core"))]
|
||||
pub(crate) unsafe fn set_own_range(base: u64, size: u64) {
|
||||
unsafe {
|
||||
OWN_RANGE = GumMemoryRange {
|
||||
@@ -1078,17 +1083,19 @@ pub(crate) unsafe fn set_own_range(base: u64, size: u64) {
|
||||
|
||||
#[cfg(feature = "winnt")]
|
||||
pub(crate) fn own_code() -> (usize, usize) {
|
||||
let start = entrypoint_blob::_start as usize;
|
||||
let start = entrypoint_blob::_start as *const () as usize;
|
||||
|
||||
(start, (&raw const _agent_private_start as usize) - start)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "linux-injected", feature = "xnu-core"))]
|
||||
pub(crate) fn own_range() -> (usize, usize) {
|
||||
let range = unsafe { ptr::addr_of!(OWN_RANGE).read() };
|
||||
|
||||
(range.base_address as usize, range.size as usize)
|
||||
}
|
||||
|
||||
#[cfg(feature = "win9x")]
|
||||
pub(crate) fn own_range_contains(address: u32) -> bool {
|
||||
let range = unsafe { ptr::addr_of!(OWN_RANGE).read() };
|
||||
let base = range.base_address as u32;
|
||||
@@ -1111,14 +1118,27 @@ unsafe fn init_gum() {
|
||||
|
||||
// The Exceptor installs fault handling for the full machine, which only the kernel half may
|
||||
// do. A copy in a process would take it from the half that uses it.
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
pub(crate) unsafe fn init_gum_without_exceptor() {
|
||||
unsafe { init_gum_with_exceptor(false) };
|
||||
unsafe {
|
||||
init_gum_with_exceptor(false);
|
||||
warm_async_io();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn warm_async_io() {
|
||||
unsafe {
|
||||
let task = bindings::g_task_new(core::ptr::null_mut(), core::ptr::null_mut(), None,
|
||||
core::ptr::null_mut());
|
||||
bindings::g_object_unref(task as bindings::gpointer);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn init_gum_with_exceptor(exceptor: bool) {
|
||||
unsafe {
|
||||
bindings::g_set_panic_handler(Some(signed_to_be_called_back(frida_panic_handler, 0)), ptr::null_mut());
|
||||
bindings::gum_init_embedded();
|
||||
bindings::glib_enable_io_features();
|
||||
if exceptor {
|
||||
bindings::gum_exceptor_obtain();
|
||||
}
|
||||
@@ -1186,6 +1206,7 @@ pub(crate) unsafe fn adopt_js_context() -> *mut GMainContext {
|
||||
|
||||
static mut JS_THREAD_ID: u64 = 0;
|
||||
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
pub(crate) fn on_js_thread() -> bool {
|
||||
let id = unsafe { JS_THREAD_ID };
|
||||
id != 0 && kernel::current_thread_id() == id
|
||||
@@ -1197,6 +1218,7 @@ pub(crate) static STOP_REQUESTED: core::sync::atomic::AtomicBool =
|
||||
#[unsafe(no_mangle)]
|
||||
pub static mut frida_agent_left: u32 = 0;
|
||||
|
||||
#[cfg(any(feature = "win9x", all(feature = "linux-injected", target_arch = "aarch64")))]
|
||||
pub(crate) fn note_unhandled_fault(vector: u64, pc: u64, address: u64) {
|
||||
unsafe {
|
||||
let fault = &raw mut frida_agent_fault;
|
||||
@@ -1299,7 +1321,14 @@ fn kernel_half_has_work() -> bool {
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
if kernel::a_copy_has_something_to_say() || kernel::a_spawn_is_held() {
|
||||
if kernel::a_copy_is_asking() {
|
||||
return true;
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
if kernel::a_copy_has_something_to_say() || kernel::a_spawn_is_held()
|
||||
|| kernel::a_pending_spawn_waits()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1318,13 +1347,16 @@ fn serve_the_kernel_half() {
|
||||
#[cfg(feature = "xnu-core")]
|
||||
relay_frames_from_targets();
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
kernel::drain_pending_spawn();
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
kernel::tell_of_held_spawns(&mut |id, program| {
|
||||
let said = alloc::ffi::CString::new(program).unwrap();
|
||||
tell_the_host_of_a_spawn(id, said.as_ptr() as *const u8);
|
||||
});
|
||||
|
||||
unsafe { transport_get_unchecked().process() };
|
||||
transport_get_unchecked().process();
|
||||
|
||||
#[cfg(feature = "win9x")]
|
||||
serve_deferred_work();
|
||||
@@ -1332,12 +1364,16 @@ fn serve_the_kernel_half() {
|
||||
#[cfg(all(feature = "linux-injected", target_arch = "aarch64"))]
|
||||
kernel::serve_executable_requests();
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
kernel::serve_register_requests();
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
kernel::report_what_the_copies_hit();
|
||||
|
||||
relay_frames_from_targets();
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
pub(crate) fn watch_for_work(main_context: *mut GMainContext, ready: fn() -> bool, serve: fn()) {
|
||||
unsafe {
|
||||
WORK_READY = Some(ready);
|
||||
@@ -1353,31 +1389,22 @@ pub(crate) fn watch_for_work(main_context: *mut GMainContext, ready: fn() -> boo
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
static mut WORK_SOURCE: *mut GSource = ptr::null_mut();
|
||||
|
||||
#[repr(C)]
|
||||
pub struct GPollFd {
|
||||
pub fd: i32,
|
||||
pub events: u16,
|
||||
pub revents: u16,
|
||||
pub user_data: *mut c_void,
|
||||
}
|
||||
#[cfg(any(feature = "win9x", feature = "winnt", feature = "linux-injected"))]
|
||||
static mut WAKEUP_POLLFD: bindings::GPollFD =
|
||||
bindings::GPollFD { fd: -1, events: 0, revents: 0, user_data: ptr::null_mut() };
|
||||
|
||||
pub type GPollFunc = unsafe extern "C" fn(*mut GPollFd, u32, i32) -> i32;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn g_source_add_poll(source: *mut GSource, fd: *mut GPollFd);
|
||||
fn g_main_context_set_poll_func(context: *mut GMainContext, func: GPollFunc);
|
||||
}
|
||||
|
||||
static mut WAKEUP_POLLFD: GPollFd = GPollFd { fd: -1, events: 0, revents: 0, user_data: ptr::null_mut() };
|
||||
|
||||
pub(crate) fn watch_a_descriptor(context: *mut GMainContext, fd: i32, poll: GPollFunc) {
|
||||
#[cfg(any(feature = "win9x", feature = "winnt", feature = "linux-injected"))]
|
||||
pub(crate) fn watch_a_descriptor(context: *mut GMainContext, fd: i32,
|
||||
poll: unsafe extern "C" fn(*mut bindings::GPollFD, u32, i32) -> i32) {
|
||||
const G_IO_IN: u16 = 1;
|
||||
unsafe {
|
||||
WAKEUP_POLLFD = GPollFd { fd, events: G_IO_IN, revents: 0, user_data: ptr::null_mut() };
|
||||
g_source_add_poll(WORK_SOURCE, ptr::addr_of_mut!(WAKEUP_POLLFD));
|
||||
g_main_context_set_poll_func(context, poll);
|
||||
WAKEUP_POLLFD =
|
||||
bindings::GPollFD { fd, events: G_IO_IN, revents: 0, user_data: ptr::null_mut() };
|
||||
bindings::g_source_add_poll(WORK_SOURCE, ptr::addr_of_mut!(WAKEUP_POLLFD));
|
||||
bindings::g_main_context_set_poll_func(context, Some(poll));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1404,9 +1431,12 @@ unsafe fn sign_what_the_loop_calls_back() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
static mut WORK_READY: Option<fn() -> bool> = None;
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
static mut WORK_SERVE: Option<fn()> = None;
|
||||
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
unsafe extern "C" fn work_prepare(source: *mut GSource, timeout: *mut i32) -> gboolean {
|
||||
unsafe {
|
||||
*timeout = -1;
|
||||
@@ -1415,6 +1445,7 @@ unsafe extern "C" fn work_prepare(source: *mut GSource, timeout: *mut i32) -> gb
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
unsafe extern "C" fn work_check(_source: *mut GSource) -> gboolean {
|
||||
let Some(ready) = (unsafe { ptr::addr_of!(WORK_READY).read() }) else {
|
||||
return 0;
|
||||
@@ -1423,6 +1454,7 @@ unsafe extern "C" fn work_check(_source: *mut GSource) -> gboolean {
|
||||
ready() as gboolean
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
unsafe extern "C" fn work_dispatch(_source: *mut GSource, _callback: GSourceFunc,
|
||||
_data: gpointer) -> gboolean {
|
||||
if let Some(serve) = unsafe { ptr::addr_of!(WORK_SERVE).read() } {
|
||||
@@ -1432,6 +1464,7 @@ unsafe extern "C" fn work_dispatch(_source: *mut GSource, _callback: GSourceFunc
|
||||
1
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
static mut WORK_FUNCS: GSourceFuncs = GSourceFuncs {
|
||||
prepare: Some(work_prepare),
|
||||
check: Some(work_check),
|
||||
@@ -1452,6 +1485,7 @@ pub(crate) unsafe fn dispatch_pending_work(main_context: *mut GMainContext) {
|
||||
static SERVICE_CONTEXT: core::sync::atomic::AtomicUsize =
|
||||
core::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
#[cfg(any(feature = "blob", feature = "xnu-core"))]
|
||||
pub(crate) fn nudge_the_loop(token: *const u8) {
|
||||
let context = SERVICE_CONTEXT.load(Ordering::Acquire) as *mut GMainContext;
|
||||
if !context.is_null() {
|
||||
@@ -1585,6 +1619,10 @@ fn process_incoming_message(variant: *mut GVariant) {
|
||||
FridaCommand::PostScriptMessage => Some(handle_post_script_message(payload_variant)),
|
||||
#[cfg(any(feature = "win9x", feature = "linux-injected", feature = "xnu-core"))]
|
||||
FridaCommand::GateSpawns => Some(handle_gate_spawns(payload_variant)),
|
||||
#[cfg(feature = "linux-injected")]
|
||||
FridaCommand::ArmNamedSpawn => Some(handle_arm_named_spawn(payload_variant)),
|
||||
#[cfg(feature = "linux-injected")]
|
||||
FridaCommand::DisarmNamedSpawn => Some(handle_disarm_named_spawn(payload_variant)),
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
FridaCommand::EnumerateApplications => Some(handle_enumerate_applications(payload_variant)),
|
||||
#[cfg(feature = "xnu-core")]
|
||||
@@ -1592,6 +1630,8 @@ fn process_incoming_message(variant: *mut GVariant) {
|
||||
kernel::list_applications_when_the_loop_can(request_id);
|
||||
None
|
||||
}
|
||||
#[cfg(feature = "linux-injected")]
|
||||
FridaCommand::EnumerateApplications => Some(handle_enumerate_no_applications()),
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
FridaCommand::EnumerateShortcuts => Some(handle_enumerate_shortcuts()),
|
||||
#[cfg(any(
|
||||
@@ -1862,6 +1902,16 @@ fn what_is_installed() -> HandlerResponse {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
fn handle_enumerate_no_applications() -> HandlerResponse {
|
||||
unsafe {
|
||||
let list_type = g_variant_type_new(c"a(sss)".as_ptr() as *const gchar);
|
||||
let list = g_variant_builder_end(g_variant_builder_new(list_type));
|
||||
g_variant_type_free(list_type);
|
||||
HandlerResponse::success(list)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
fn handle_enumerate_applications(payload: *mut GVariant) -> HandlerResponse {
|
||||
unsafe {
|
||||
@@ -1878,7 +1928,7 @@ fn handle_enumerate_applications(payload: *mut GVariant) -> HandlerResponse {
|
||||
let path = as_text(path, &mut path_text);
|
||||
|
||||
let identity = kernel::identify_image(path as *const u8);
|
||||
let named = if unsafe { identity.read() } != 0 { identity as *const gchar } else {
|
||||
let named = if identity.read() != 0 { identity as *const gchar } else {
|
||||
identifier
|
||||
};
|
||||
|
||||
@@ -1902,15 +1952,17 @@ fn handle_enumerate_applications(payload: *mut GVariant) -> HandlerResponse {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
struct SelectedIdentifiers {
|
||||
names: *mut *const gchar,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
impl SelectedIdentifiers {
|
||||
unsafe fn from(variant: *mut GVariant) -> Self {
|
||||
let mut count: gsize = 0;
|
||||
let names = unsafe { g_variant_get_strv(variant, &mut count) };
|
||||
let names = unsafe { bindings::g_variant_get_strv(variant, &mut count) };
|
||||
SelectedIdentifiers { names, count: count as usize }
|
||||
}
|
||||
|
||||
@@ -1923,12 +1975,14 @@ impl SelectedIdentifiers {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
impl Drop for SelectedIdentifiers {
|
||||
fn drop(&mut self) {
|
||||
unsafe { g_free(self.names as gpointer) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
unsafe fn c_string_equal(a: *const gchar, b: *const gchar) -> bool {
|
||||
unsafe {
|
||||
let mut offset = 0;
|
||||
@@ -1996,6 +2050,22 @@ fn handle_gate_spawns(payload: *mut GVariant) -> HandlerResponse {
|
||||
HandlerResponse::success(unsafe { g_variant_new_uint32(0) })
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
fn handle_arm_named_spawn(payload: *mut GVariant) -> HandlerResponse {
|
||||
let name = unsafe { core::ffi::CStr::from_ptr(g_variant_get_string(payload, ptr::null_mut())) };
|
||||
kernel::arm_named_spawn(name.to_bytes());
|
||||
|
||||
HandlerResponse::success(unsafe { g_variant_new_uint32(0) })
|
||||
}
|
||||
|
||||
#[cfg(feature = "linux-injected")]
|
||||
fn handle_disarm_named_spawn(payload: *mut GVariant) -> HandlerResponse {
|
||||
let name = unsafe { core::ffi::CStr::from_ptr(g_variant_get_string(payload, ptr::null_mut())) };
|
||||
kernel::disarm_named_spawn(name.to_bytes());
|
||||
|
||||
HandlerResponse::success(unsafe { g_variant_new_uint32(0) })
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "linux-injected", feature = "xnu-core"))]
|
||||
pub(crate) fn tell_the_host_of_a_spawn(pid: u32, command_line: *const u8) {
|
||||
unsafe {
|
||||
@@ -2030,8 +2100,8 @@ fn handle_enumerate_processes(payload: *mut GVariant) -> HandlerResponse {
|
||||
let selection = g_variant_get_child_value(payload, 1);
|
||||
let wanted = SelectedPids::from(selection);
|
||||
|
||||
let list_type = g_variant_type_new(c"a(usssaay)".as_ptr() as *const gchar);
|
||||
let process_type = g_variant_type_new(c"(usssaay)".as_ptr() as *const gchar);
|
||||
let list_type = g_variant_type_new(c"a(usssusuxaay)".as_ptr() as *const gchar);
|
||||
let process_type = g_variant_type_new(c"(usssusuxaay)".as_ptr() as *const gchar);
|
||||
let icons_type = g_variant_type_new(c"aay".as_ptr() as *const gchar);
|
||||
let byte_type = g_variant_type_new(c"y".as_ptr() as *const gchar);
|
||||
let builder = g_variant_builder_new(list_type);
|
||||
@@ -2042,6 +2112,10 @@ fn handle_enumerate_processes(payload: *mut GVariant) -> HandlerResponse {
|
||||
g_variant_builder_add(builder, c"s".as_ptr(), c"".as_ptr());
|
||||
g_variant_builder_add(builder, c"s".as_ptr(), c"".as_ptr());
|
||||
g_variant_builder_add(builder, c"s".as_ptr(), kernel_name());
|
||||
g_variant_builder_add(builder, c"u".as_ptr(), 0u32);
|
||||
g_variant_builder_add(builder, c"s".as_ptr(), c"".as_ptr());
|
||||
g_variant_builder_add(builder, c"u".as_ptr(), 0u32);
|
||||
g_variant_builder_add(builder, c"x".as_ptr(), 0i64);
|
||||
g_variant_builder_open(builder, icons_type);
|
||||
g_variant_builder_close(builder);
|
||||
g_variant_builder_close(builder);
|
||||
@@ -2063,6 +2137,10 @@ fn handle_enumerate_processes(payload: *mut GVariant) -> HandlerResponse {
|
||||
c"s".as_ptr(),
|
||||
text_or_empty(kernel::describe_process(&process)),
|
||||
);
|
||||
g_variant_builder_add(builder, c"u".as_ptr(), process.uid);
|
||||
g_variant_builder_add(builder, c"s".as_ptr(), text_or_empty(process.user));
|
||||
g_variant_builder_add(builder, c"u".as_ptr(), process.ppid);
|
||||
g_variant_builder_add(builder, c"x".as_ptr(), process.started);
|
||||
|
||||
g_variant_builder_open(builder, icons_type);
|
||||
if include_icons && !process.path.is_null() {
|
||||
@@ -2093,11 +2171,23 @@ fn handle_enumerate_processes(payload: *mut GVariant) -> HandlerResponse {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
feature = "win9x",
|
||||
feature = "winnt",
|
||||
feature = "linux-injected",
|
||||
feature = "xnu-core"
|
||||
))]
|
||||
struct SelectedPids {
|
||||
pids: *const u32,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
feature = "win9x",
|
||||
feature = "winnt",
|
||||
feature = "linux-injected",
|
||||
feature = "xnu-core"
|
||||
))]
|
||||
impl SelectedPids {
|
||||
unsafe fn from(variant: *mut GVariant) -> Self {
|
||||
let mut count: gsize = 0;
|
||||
@@ -2124,7 +2214,7 @@ fn kernel_name() -> *const gchar {
|
||||
c"ntoskrnl.exe".as_ptr() as *const gchar
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "linux", feature = "linux-injected"))]
|
||||
#[cfg(feature = "linux-injected")]
|
||||
fn kernel_name() -> *const gchar {
|
||||
c"kernel".as_ptr() as *const gchar
|
||||
}
|
||||
@@ -2134,6 +2224,12 @@ fn kernel_name() -> *const gchar {
|
||||
c"kernel".as_ptr() as *const gchar
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
feature = "win9x",
|
||||
feature = "winnt",
|
||||
feature = "linux-injected",
|
||||
feature = "xnu-core"
|
||||
))]
|
||||
const KERNEL_PID: u32 = 0;
|
||||
|
||||
#[cfg(any(
|
||||
@@ -2478,7 +2574,7 @@ unsafe extern "C" fn frida_message_handler(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "win9x", feature = "winnt"))]
|
||||
#[cfg(feature = "win9x")]
|
||||
pub(crate) fn routed_arena() -> u64 {
|
||||
unsafe { ROUTED_ARENA }
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use core::mem::size_of;
|
||||
use core::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
// What the kernel half and the copy leave for each other. Both reach it by its own address, so
|
||||
@@ -12,10 +13,6 @@ impl Arena {
|
||||
Arena { begins }
|
||||
}
|
||||
|
||||
pub fn at_offset(&self, offset: usize) -> usize {
|
||||
self.begins + offset
|
||||
}
|
||||
|
||||
// Until the frames flow, what the copy has to say is left here for the kernel half to read.
|
||||
pub fn say(&self, msg: &str) {
|
||||
let said = msg.as_bytes();
|
||||
@@ -28,14 +25,6 @@ impl Arena {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn said(&self) -> &str {
|
||||
let bytes =
|
||||
unsafe { core::slice::from_raw_parts((self.begins + SAID) as *const u8, SAID_SIZE) };
|
||||
let length = bytes.iter().position(|byte| *byte == 0).unwrap_or(SAID_SIZE);
|
||||
|
||||
core::str::from_utf8(&bytes[..length]).unwrap_or("")
|
||||
}
|
||||
|
||||
pub fn page_size(&self) -> u32 {
|
||||
self.word(PAGE_SIZE).load(Ordering::Acquire)
|
||||
}
|
||||
@@ -44,10 +33,6 @@ impl Arena {
|
||||
unsafe { ((self.begins + offset) as *mut u64).write_volatile(value) };
|
||||
}
|
||||
|
||||
pub fn progress(&self) -> u32 {
|
||||
self.word(PROGRESS).load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn note(&self, step: u32) {
|
||||
self.word(PROGRESS).store(step, Ordering::Release);
|
||||
}
|
||||
@@ -125,6 +110,7 @@ impl Arena {
|
||||
super::user::say_something();
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub fn request_executable(&self, address: u64, size: u64) -> u32 {
|
||||
self.leave(EXEC_ADDR, address);
|
||||
self.leave(EXEC_SIZE, size);
|
||||
@@ -133,10 +119,12 @@ impl Arena {
|
||||
seq
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub fn executable_settled(&self, seq: u32) -> bool {
|
||||
self.word(EXEC_ACK).load(Ordering::Acquire) == seq
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub fn executable_was_granted(&self) -> bool {
|
||||
self.word(EXEC_OK).load(Ordering::Acquire) != 0
|
||||
}
|
||||
@@ -149,12 +137,53 @@ impl Arena {
|
||||
Some((self.read_wide(EXEC_ADDR), self.read_wide(EXEC_SIZE)))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub fn grant_executable(&self, ok: bool) {
|
||||
self.word(EXEC_OK).store(ok as u32, Ordering::Release);
|
||||
let seq = self.word(EXEC_SEQ).load(Ordering::Acquire);
|
||||
self.word(EXEC_ACK).store(seq, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn request_registers(&self, thread: u32) -> u32 {
|
||||
self.word(REG_TID).store(thread, Ordering::Release);
|
||||
let seq = self.word(REG_SEQ).load(Ordering::Relaxed).wrapping_add(1).max(1);
|
||||
self.word(REG_SEQ).store(seq, Ordering::Release);
|
||||
seq
|
||||
}
|
||||
|
||||
pub fn registers_settled(&self, seq: u32) -> bool {
|
||||
self.word(REG_ACK).load(Ordering::Acquire) == seq
|
||||
}
|
||||
|
||||
pub fn registers_were_captured(&self) -> bool {
|
||||
self.word(REG_OK).load(Ordering::Acquire) != 0
|
||||
}
|
||||
|
||||
pub fn captured_registers(&self, into: &mut [u64]) {
|
||||
for (slot, word) in into.iter_mut().enumerate() {
|
||||
*word = self.read_wide(REG_STATE + slot * size_of::<u64>());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wants_registers(&self) -> Option<u32> {
|
||||
let seq = self.word(REG_SEQ).load(Ordering::Acquire);
|
||||
if seq == 0 || seq == self.word(REG_ACK).load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
Some(self.word(REG_TID).load(Ordering::Acquire))
|
||||
}
|
||||
|
||||
pub fn deliver_registers(&self, state: Option<&[u64]>) {
|
||||
if let Some(words) = state {
|
||||
for (slot, word) in words.iter().enumerate() {
|
||||
self.leave(REG_STATE + slot * size_of::<u64>(), *word);
|
||||
}
|
||||
}
|
||||
self.word(REG_OK).store(state.is_some() as u32, Ordering::Release);
|
||||
let seq = self.word(REG_SEQ).load(Ordering::Acquire);
|
||||
self.word(REG_ACK).store(seq, Ordering::Release);
|
||||
}
|
||||
|
||||
fn read_wide(&self, offset: usize) -> u64 {
|
||||
unsafe { ((self.begins + offset) as *const u64).read_volatile() }
|
||||
}
|
||||
@@ -190,4 +219,11 @@ const EXEC_SEQ: usize = 432;
|
||||
const EXEC_ACK: usize = 436;
|
||||
const EXEC_ADDR: usize = 440;
|
||||
const EXEC_SIZE: usize = 448;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const EXEC_OK: usize = 456;
|
||||
|
||||
const REG_SEQ: usize = 460;
|
||||
const REG_ACK: usize = 464;
|
||||
const REG_TID: usize = 468;
|
||||
const REG_OK: usize = 472;
|
||||
const REG_STATE: usize = 480;
|
||||
@@ -191,7 +191,8 @@ unsafe fn hook_data_ready(so: Socket) {
|
||||
let slot = (sk + dr_off) as *mut usize;
|
||||
ORIG_DATA_READY.store(unsafe { *slot }, Ordering::Release);
|
||||
|
||||
let thunk = super::native::kcfi_thunk(on_data_ready as usize, sock_def_readable_ref());
|
||||
let thunk =
|
||||
super::native::kcfi_thunk(on_data_ready as *const () as usize, sock_def_readable_ref());
|
||||
unsafe { *slot = thunk };
|
||||
}
|
||||
|
||||
@@ -257,11 +258,11 @@ unsafe fn send_all(so: Socket, bytes: &[u8]) {
|
||||
}
|
||||
|
||||
unsafe fn _init_net_addr() -> *mut c_void {
|
||||
unsafe { ptr::addr_of!(_init_net) as *mut c_void }
|
||||
ptr::addr_of!(_init_net) as *mut c_void
|
||||
}
|
||||
|
||||
unsafe fn _sock_def_readable_addr() -> usize {
|
||||
_sock_def_readable.map_or(0, |f| f as usize)
|
||||
unsafe { _sock_def_readable }.map_or(0, |f| f as usize)
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
|
||||
@@ -2,9 +2,16 @@ use core::ffi::{c_int, c_void};
|
||||
use core::ptr;
|
||||
|
||||
use alloc::collections::BTreeMap;
|
||||
use alloc::string::String;
|
||||
|
||||
use super::layout::{field_offset, struct_size};
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
use crate::bindings::{
|
||||
gum_interceptor_begin_transaction, gum_interceptor_end_transaction, gum_interceptor_obtain,
|
||||
gum_interceptor_replace_fast,
|
||||
};
|
||||
|
||||
use super::layout::field_offset;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
use super::layout::struct_size;
|
||||
use super::STACK_SPAN;
|
||||
use super::native;
|
||||
use super::processes::task_with_id;
|
||||
@@ -37,10 +44,8 @@ pub fn inject_into_process(id: u32) -> u32 {
|
||||
|
||||
let placed = Placement {
|
||||
task,
|
||||
copy_pid: home.copy_pid,
|
||||
base: home.base,
|
||||
arena: home.arena,
|
||||
seen_by_the_copy: home.seen_by_the_copy,
|
||||
stack: home.stack,
|
||||
says: ptr::null_mut(),
|
||||
hears: ptr::null_mut(),
|
||||
@@ -73,10 +78,8 @@ unsafe extern "C" fn carry_what_the_copy_says(argument: *mut c_void, _reason: i3
|
||||
|
||||
struct Placement {
|
||||
task: usize,
|
||||
copy_pid: u32,
|
||||
base: usize,
|
||||
arena: usize,
|
||||
seen_by_the_copy: usize,
|
||||
stack: usize,
|
||||
says: *mut c_void,
|
||||
hears: *mut c_void,
|
||||
@@ -89,10 +92,8 @@ fn pid_reported_by(placed: &Placement) -> u32 {
|
||||
// The copy is given a task of its own that shares the address space it was mapped into, so
|
||||
// nothing of the target is borrowed and a target that never runs is no obstacle.
|
||||
struct Home {
|
||||
copy_pid: u32,
|
||||
base: usize,
|
||||
arena: usize,
|
||||
seen_by_the_copy: usize,
|
||||
stack: usize,
|
||||
}
|
||||
|
||||
@@ -130,19 +131,14 @@ fn map_and_start(id: u32) -> Option<Home> {
|
||||
|
||||
let arena = view_of(where_the_copy_sees_it)?;
|
||||
|
||||
let copy_pid = start(base, where_the_copy_sees_it, stack);
|
||||
start(base, where_the_copy_sees_it, stack);
|
||||
|
||||
Some(Home {
|
||||
copy_pid,
|
||||
base,
|
||||
arena,
|
||||
seen_by_the_copy: where_the_copy_sees_it,
|
||||
stack,
|
||||
})
|
||||
Some(Home { base, arena, stack })
|
||||
}
|
||||
|
||||
// The kernel half reaches the same pages by an address of its own, so what the two leave for
|
||||
// each other needs neither the address space borrowed nor a copy made.
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn borrowed_memory() -> Option<usize> {
|
||||
let at = field_offset("task_struct", "mm")?;
|
||||
|
||||
@@ -207,6 +203,9 @@ fn map_a_copy() -> Option<usize> {
|
||||
return None;
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
keep_the_copy_in_small_pages(base, size + ARENA_SIZE)?;
|
||||
|
||||
give(base, own, shared)?;
|
||||
|
||||
let rebased = native::alloc(private);
|
||||
@@ -221,6 +220,13 @@ fn map_a_copy() -> Option<usize> {
|
||||
Some(base)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn keep_the_copy_in_small_pages(base: usize, size: usize) -> Option<()> {
|
||||
let memory = borrowed_memory()? as *mut c_void;
|
||||
unsafe { _do_madvise(memory, base, size, MADV_NOHUGEPAGE) };
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn make_the_code_executable(base: usize, size: usize) -> Option<()> {
|
||||
let memory = borrowed_memory()? as *mut c_void;
|
||||
@@ -330,7 +336,7 @@ unsafe fn open_user_access() -> usize {
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
unsafe fn close_user_access(_domains: usize) {}
|
||||
|
||||
fn start(base: usize, arena: usize, stack: usize) -> u32 {
|
||||
fn start(base: usize, arena: usize, stack: usize) {
|
||||
let entry = native::alloc(size_of::<Entry>()) as *mut Entry;
|
||||
unsafe {
|
||||
entry.write(Entry {
|
||||
@@ -339,7 +345,7 @@ fn start(base: usize, arena: usize, stack: usize) -> u32 {
|
||||
stack,
|
||||
});
|
||||
|
||||
_user_mode_thread(USER_ENTRY, entry as *mut c_void, CLONE_VM | CLONE_FS | CLONE_FILES) as u32
|
||||
_user_mode_thread(USER_ENTRY, entry as *mut c_void, CLONE_VM | CLONE_FS | CLONE_FILES);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,11 +388,13 @@ pub unsafe extern "C" fn frida_cb_user(argument: *mut c_void) -> c_int {
|
||||
// What a task starts with in userland is at the top of the kernel stack it was given.
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn registers_of_this_task(places: &Places) -> usize {
|
||||
let stack = unsafe {
|
||||
((native::current_task() as usize + places.stack_of_task) as *const usize).read()
|
||||
};
|
||||
registers_of_task(native::current_task() as usize, places)
|
||||
}
|
||||
|
||||
stack + STACK_SPAN - places.size
|
||||
fn registers_of_task(task: usize, places: &Places) -> usize {
|
||||
let stack = unsafe { ((task + places.stack_of_task) as *const usize).read() };
|
||||
|
||||
stack + STACK_SPAN - TOP_OF_STACK_PADDING - places.size
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
@@ -408,6 +416,273 @@ const TOP_OF_STACK_PADDING: usize = 8;
|
||||
#[cfg(not(any(target_arch = "x86", target_arch = "arm")))]
|
||||
const TOP_OF_STACK_PADDING: usize = 0;
|
||||
|
||||
pub fn thread_state(id: u32) -> Option<crate::bindings::GumThreadState> {
|
||||
use crate::bindings::{
|
||||
GumThreadState_GUM_THREAD_HALTED, GumThreadState_GUM_THREAD_RUNNING,
|
||||
GumThreadState_GUM_THREAD_STOPPED, GumThreadState_GUM_THREAD_UNINTERRUPTIBLE,
|
||||
GumThreadState_GUM_THREAD_WAITING,
|
||||
};
|
||||
|
||||
let task = native::task_for_thread(id) as usize;
|
||||
if task == 0 {
|
||||
return None;
|
||||
}
|
||||
let at = field_offset("task_struct", "__state")?;
|
||||
let running = unsafe { ((task + at) as *const u32).read() };
|
||||
|
||||
Some(if running == 0 {
|
||||
GumThreadState_GUM_THREAD_RUNNING
|
||||
} else if running & TASK_UNINTERRUPTIBLE != 0 {
|
||||
GumThreadState_GUM_THREAD_UNINTERRUPTIBLE
|
||||
} else if running & TASK_INTERRUPTIBLE != 0 {
|
||||
GumThreadState_GUM_THREAD_WAITING
|
||||
} else if running & (TASK_STOPPED | TASK_TRACED) != 0 {
|
||||
GumThreadState_GUM_THREAD_STOPPED
|
||||
} else {
|
||||
GumThreadState_GUM_THREAD_HALTED
|
||||
})
|
||||
}
|
||||
|
||||
const TASK_INTERRUPTIBLE: u32 = 0x0001;
|
||||
const TASK_UNINTERRUPTIBLE: u32 = 0x0002;
|
||||
const TASK_STOPPED: u32 = 0x0004;
|
||||
const TASK_TRACED: u32 = 0x0008;
|
||||
|
||||
fn registers_of_thread(id: u32) -> Option<usize> {
|
||||
let task = native::task_for_thread(id) as usize;
|
||||
if task == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut places = describe_registers()?;
|
||||
if places.stack_of_task == 0 {
|
||||
places.stack_of_task = field_offset("task_struct", "stack")?;
|
||||
}
|
||||
Some(registers_of_task(task, &places))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub fn capture_registers(id: u32) -> Option<crate::kernel::CpuState> {
|
||||
let regs = registers_of_thread(id)?;
|
||||
let general = regs as *const u64;
|
||||
|
||||
let mut x = [0u64; 29];
|
||||
for slot in 0..29 {
|
||||
x[slot] = unsafe { general.add(slot).read() };
|
||||
}
|
||||
|
||||
Some(crate::kernel::CpuState {
|
||||
x,
|
||||
fp: unsafe { general.add(29).read() },
|
||||
lr: unsafe { general.add(30).read() },
|
||||
sp: unsafe { general.add(31).read() },
|
||||
pc: unsafe { general.add(32).read() },
|
||||
nzcv: unsafe { general.add(33).read() },
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn capture_registers(id: u32) -> Option<crate::kernel::CpuState> {
|
||||
let regs = registers_of_thread(id)?;
|
||||
let at = |slot: usize| unsafe { ((regs + slot * 8) as *const u64).read() };
|
||||
|
||||
Some(crate::kernel::CpuState {
|
||||
r15: at(0),
|
||||
r14: at(1),
|
||||
r13: at(2),
|
||||
r12: at(3),
|
||||
rbp: at(4),
|
||||
rbx: at(5),
|
||||
r11: at(6),
|
||||
r10: at(7),
|
||||
r9: at(8),
|
||||
r8: at(9),
|
||||
rax: at(10),
|
||||
rcx: at(11),
|
||||
rdx: at(12),
|
||||
rsi: at(13),
|
||||
rdi: at(14),
|
||||
rip: at(16),
|
||||
rsp: at(19),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
pub fn capture_registers(id: u32) -> Option<crate::kernel::CpuState> {
|
||||
let regs = registers_of_thread(id)?;
|
||||
let at = |slot: usize| unsafe { ((regs + slot * 4) as *const u32).read() };
|
||||
|
||||
Some(crate::kernel::CpuState {
|
||||
ebx: at(0),
|
||||
ecx: at(1),
|
||||
edx: at(2),
|
||||
esi: at(3),
|
||||
edi: at(4),
|
||||
ebp: at(5),
|
||||
eax: at(6),
|
||||
eip: at(12),
|
||||
esp: at(15),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "arm")]
|
||||
pub fn capture_registers(id: u32) -> Option<crate::kernel::CpuState> {
|
||||
let regs = registers_of_thread(id)?;
|
||||
let at = |slot: usize| unsafe { ((regs + slot * 4) as *const u32).read() };
|
||||
|
||||
let mut r = [0u32; 8];
|
||||
for slot in 0..8 {
|
||||
r[slot] = at(slot);
|
||||
}
|
||||
|
||||
Some(crate::kernel::CpuState {
|
||||
pc: at(15),
|
||||
sp: at(13),
|
||||
cpsr: at(16),
|
||||
r,
|
||||
r8: at(8),
|
||||
r9: at(9),
|
||||
r10: at(10),
|
||||
r11: at(11),
|
||||
r12: at(12),
|
||||
lr: at(14),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub const REGISTER_WORDS: usize = 34;
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub const REGISTER_WORDS: usize = 17;
|
||||
#[cfg(target_arch = "x86")]
|
||||
pub const REGISTER_WORDS: usize = 9;
|
||||
#[cfg(target_arch = "arm")]
|
||||
pub const REGISTER_WORDS: usize = 17;
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub fn words_from_registers(state: &crate::kernel::CpuState) -> [u64; REGISTER_WORDS] {
|
||||
let mut words = [0u64; REGISTER_WORDS];
|
||||
words[..29].copy_from_slice(&state.x);
|
||||
words[29] = state.fp;
|
||||
words[30] = state.lr;
|
||||
words[31] = state.sp;
|
||||
words[32] = state.pc;
|
||||
words[33] = state.nzcv;
|
||||
words
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub fn registers_from_words(words: &[u64; REGISTER_WORDS]) -> crate::kernel::CpuState {
|
||||
let mut x = [0u64; 29];
|
||||
x.copy_from_slice(&words[..29]);
|
||||
crate::kernel::CpuState {
|
||||
x,
|
||||
fp: words[29],
|
||||
lr: words[30],
|
||||
sp: words[31],
|
||||
pc: words[32],
|
||||
nzcv: words[33],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn words_from_registers(state: &crate::kernel::CpuState) -> [u64; REGISTER_WORDS] {
|
||||
[
|
||||
state.rip, state.r15, state.r14, state.r13, state.r12, state.r11, state.r10, state.r9,
|
||||
state.r8, state.rdi, state.rsi, state.rbp, state.rsp, state.rbx, state.rdx, state.rcx,
|
||||
state.rax,
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn registers_from_words(words: &[u64; REGISTER_WORDS]) -> crate::kernel::CpuState {
|
||||
crate::kernel::CpuState {
|
||||
rip: words[0],
|
||||
r15: words[1],
|
||||
r14: words[2],
|
||||
r13: words[3],
|
||||
r12: words[4],
|
||||
r11: words[5],
|
||||
r10: words[6],
|
||||
r9: words[7],
|
||||
r8: words[8],
|
||||
rdi: words[9],
|
||||
rsi: words[10],
|
||||
rbp: words[11],
|
||||
rsp: words[12],
|
||||
rbx: words[13],
|
||||
rdx: words[14],
|
||||
rcx: words[15],
|
||||
rax: words[16],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
pub fn words_from_registers(state: &crate::kernel::CpuState) -> [u64; REGISTER_WORDS] {
|
||||
[
|
||||
state.eip as u64,
|
||||
state.edi as u64,
|
||||
state.esi as u64,
|
||||
state.ebp as u64,
|
||||
state.esp as u64,
|
||||
state.ebx as u64,
|
||||
state.edx as u64,
|
||||
state.ecx as u64,
|
||||
state.eax as u64,
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
pub fn registers_from_words(words: &[u64; REGISTER_WORDS]) -> crate::kernel::CpuState {
|
||||
crate::kernel::CpuState {
|
||||
eip: words[0] as u32,
|
||||
edi: words[1] as u32,
|
||||
esi: words[2] as u32,
|
||||
ebp: words[3] as u32,
|
||||
esp: words[4] as u32,
|
||||
ebx: words[5] as u32,
|
||||
edx: words[6] as u32,
|
||||
ecx: words[7] as u32,
|
||||
eax: words[8] as u32,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "arm")]
|
||||
pub fn words_from_registers(state: &crate::kernel::CpuState) -> [u64; REGISTER_WORDS] {
|
||||
let mut words = [0u64; REGISTER_WORDS];
|
||||
for slot in 0..8 {
|
||||
words[slot] = state.r[slot] as u64;
|
||||
}
|
||||
words[8] = state.r8 as u64;
|
||||
words[9] = state.r9 as u64;
|
||||
words[10] = state.r10 as u64;
|
||||
words[11] = state.r11 as u64;
|
||||
words[12] = state.r12 as u64;
|
||||
words[13] = state.sp as u64;
|
||||
words[14] = state.lr as u64;
|
||||
words[15] = state.pc as u64;
|
||||
words[16] = state.cpsr as u64;
|
||||
words
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "arm")]
|
||||
pub fn registers_from_words(words: &[u64; REGISTER_WORDS]) -> crate::kernel::CpuState {
|
||||
let mut r = [0u32; 8];
|
||||
for slot in 0..8 {
|
||||
r[slot] = words[slot] as u32;
|
||||
}
|
||||
crate::kernel::CpuState {
|
||||
pc: words[15] as u32,
|
||||
sp: words[13] as u32,
|
||||
cpsr: words[16] as u32,
|
||||
r,
|
||||
r8: words[8] as u32,
|
||||
r9: words[9] as u32,
|
||||
r10: words[10] as u32,
|
||||
r11: words[11] as u32,
|
||||
r12: words[12] as u32,
|
||||
lr: words[14] as u32,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
unsafe fn write_selectors(registers: usize, _places: &Places) {
|
||||
unsafe {
|
||||
@@ -561,33 +836,30 @@ fn make_a_range_executable(task: usize, base: usize, size: usize) -> bool {
|
||||
granted
|
||||
}
|
||||
|
||||
pub fn report_what_the_copies_hit() {
|
||||
pub fn a_copy_is_asking() -> bool {
|
||||
unsafe { placements() }.values().any(|placed| {
|
||||
let arena = Arena::at(placed.arena);
|
||||
arena.wants_registers().is_some() || arena.wants_executable().is_some()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn serve_register_requests() {
|
||||
for placed in unsafe { placements() }.values() {
|
||||
let Some(hit) = what_it_says(placed) else {
|
||||
let arena = Arena::at(placed.arena);
|
||||
let Some(thread) = arena.wants_registers() else {
|
||||
continue;
|
||||
};
|
||||
bump_to(placed.arena + super::arena::PROGRESS, NOTHING_MORE);
|
||||
let words = capture_registers(thread).map(|state| words_from_registers(&state));
|
||||
arena.deliver_registers(words.as_ref().map(|w| w.as_slice()));
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::at(placed.arena);
|
||||
let said = arena.said();
|
||||
if hit == super::user::SPOKE {
|
||||
native::log(&alloc::format!("copy in {}: {}\n", pid_reported_by(placed), said));
|
||||
} else if hit == super::user::PANICKED {
|
||||
native::log(&alloc::format!("copy in {} gave up: {}\n", pid_reported_by(placed), said));
|
||||
} else {
|
||||
let kind = read_address(placed.arena + super::arena::FAULT_KIND);
|
||||
native::log(&alloc::format!(
|
||||
"copy in {} died on signal {} ({}) at {:#x}, pc {}, lr {}, image at {:#x}, {}\n",
|
||||
pid_reported_by(placed),
|
||||
kind as u32,
|
||||
(kind >> 32) as u32,
|
||||
read_address(placed.arena + super::arena::FAULT_ADDRESS),
|
||||
relative_to_image(read_address(placed.arena + super::arena::FAULT_PC), placed),
|
||||
relative_to_image(read_address(placed.arena + super::arena::FAULT_LR), placed),
|
||||
placed.base,
|
||||
said
|
||||
));
|
||||
pub fn report_what_the_copies_hit() {
|
||||
for placed in unsafe { placements() }.values() {
|
||||
if what_it_says(placed).is_none() {
|
||||
continue;
|
||||
}
|
||||
bump_to(placed.arena + super::arena::PROGRESS, NOTHING_MORE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -605,16 +877,6 @@ fn bump_to(address: usize, value: u32) {
|
||||
unsafe { (address as *mut u32).write_volatile(value) };
|
||||
}
|
||||
|
||||
fn relative_to_image(address: u64, placed: &Placement) -> String {
|
||||
let base = placed.base as u64;
|
||||
let size = crate::own_range().1 as u64;
|
||||
if address >= base && address - base < size {
|
||||
alloc::format!("image+{:#x}", address - base)
|
||||
} else {
|
||||
alloc::format!("{:#x}", address)
|
||||
}
|
||||
}
|
||||
|
||||
const NOTHING_MORE: u32 = 0;
|
||||
|
||||
fn watch_the_threads() {
|
||||
@@ -667,6 +929,49 @@ pub unsafe extern "C" fn frida_cb_exec(_data: *mut c_void, task: *mut c_void, _w
|
||||
native::wake(task as *const u8);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
pub fn watch_for_named_spawns() {
|
||||
if RENAME_WATCHING.swap(true, core::sync::atomic::Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let interceptor = gum_interceptor_obtain();
|
||||
gum_interceptor_begin_transaction(interceptor);
|
||||
gum_interceptor_replace_fast(interceptor, ___set_task_comm as *mut c_void,
|
||||
frida_replaced_set_task_comm as *mut c_void, &raw mut ORIGINAL_SET_TASK_COMM,
|
||||
ptr::null());
|
||||
gum_interceptor_end_transaction(interceptor);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
pub fn watch_for_named_spawns() {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
static RENAME_WATCHING: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
static mut ORIGINAL_SET_TASK_COMM: *mut c_void = ptr::null_mut();
|
||||
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
unsafe extern "C" fn frida_replaced_set_task_comm(task: *mut c_void, buf: *const core::ffi::c_char,
|
||||
exec: c_int) {
|
||||
let name = unsafe { core::ffi::CStr::from_ptr(buf) };
|
||||
if super::spawn::claim_if_wanted(name.to_bytes()) {
|
||||
if let Some(id) = id_of(task as usize) {
|
||||
native::send_signal(STOP, task as usize);
|
||||
super::spawn::note_pending_spawn(id, name.to_bytes());
|
||||
native::wake(ptr::null());
|
||||
}
|
||||
}
|
||||
|
||||
let original: unsafe extern "C" fn(*mut c_void, *const core::ffi::c_char, c_int) =
|
||||
unsafe { core::mem::transmute(ORIGINAL_SET_TASK_COMM) };
|
||||
unsafe { original(task, buf, exec) };
|
||||
}
|
||||
|
||||
static HOLDING: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
const STOP: c_int = 19;
|
||||
@@ -715,7 +1020,7 @@ static COPY_TASK: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUs
|
||||
static WATCHING: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub fn detach_from_process(id: u32) -> bool {
|
||||
let Some(placed) = (unsafe { placements() }.remove(&id)) else {
|
||||
let Some(placed) = unsafe { placements() }.remove(&id) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -797,10 +1102,6 @@ fn wake_the_copy(placed: &Placement) {
|
||||
}
|
||||
}
|
||||
|
||||
fn read_address(address: usize) -> u64 {
|
||||
unsafe { (address as *const u64).read_volatile() }
|
||||
}
|
||||
|
||||
fn read_word(address: usize) -> u32 {
|
||||
unsafe { (address as *const u32).read_volatile() }
|
||||
}
|
||||
@@ -843,12 +1144,11 @@ const PROT_WRITE: usize = 2;
|
||||
const PROT_EXEC: usize = 4;
|
||||
const MAP_PRIVATE: usize = 2;
|
||||
const MAP_ANONYMOUS: usize = 0x20;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const MADV_NOHUGEPAGE: c_int = 15;
|
||||
const FIRST_ERROR_ADDRESS: usize = usize::MAX - 4095;
|
||||
const PAGE_SIZE: usize = 4096;
|
||||
const FOLL_WRITE: c_int = 1;
|
||||
const FUTEX_WAIT: c_int = 128;
|
||||
const FUTEX_WAKE: c_int = 129;
|
||||
const WAKE_EVERY_WAITER: u32 = i32::MAX as u32;
|
||||
|
||||
const CLONE_VM: usize = 0x100;
|
||||
const CLONE_FS: usize = 0x200;
|
||||
@@ -879,6 +1179,8 @@ unsafe extern "C" {
|
||||
static ___tracepoint_sched_process_exit: *mut c_void;
|
||||
static ___tracepoint_sched_process_exec: *mut c_void;
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
static ___set_task_comm: unsafe extern "C" fn(*mut c_void, *const core::ffi::c_char, c_int);
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
static _vunmap: unsafe extern "C" fn(*mut c_void);
|
||||
#[cfg(not(any(target_arch = "arm", target_arch = "x86", target_arch = "x86_64")))]
|
||||
static ___arch_copy_to_user: unsafe extern "C" fn(*mut c_void, *const c_void, usize) -> usize;
|
||||
@@ -921,6 +1223,8 @@ unsafe extern "C" {
|
||||
>;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
static _caches_clean_inval_pou: Option<unsafe extern "C" fn(usize, usize)>;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
static _do_madvise: unsafe extern "C" fn(*mut c_void, usize, usize, c_int) -> c_int;
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
@@ -980,6 +1284,7 @@ const EXEC_PROBE: unsafe extern "C" fn(*mut c_void, *mut c_void, c_int, *mut c_v
|
||||
const EXEC_PROBE: unsafe extern "C" fn(*mut c_void, *mut c_void, c_int, *mut c_void) =
|
||||
frida_cb_exec;
|
||||
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
const THREAD_APPEARED_PROBE: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
|
||||
frida_kcb_thread_appeared;
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use core::ffi::{c_int, c_long, c_void};
|
||||
use core::ffi::{c_int, c_void};
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
use core::ffi::c_long;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
use core::ptr;
|
||||
|
||||
use crate::bindings::{
|
||||
@@ -90,7 +93,7 @@ unsafe fn build_resume_stub() {
|
||||
stub.write(0xbf);
|
||||
(stub.add(1) as *mut u32).write((&raw mut RESUME_CONTEXT) as u32);
|
||||
stub.add(5).write(0xe9);
|
||||
let rel = (frida_i386_resume as usize).wrapping_sub(stub as usize + 10) as u32;
|
||||
let rel = (frida_i386_resume as *const () as usize).wrapping_sub(stub as usize + 10) as u32;
|
||||
(stub.add(6) as *mut u32).write(rel);
|
||||
RESUME_STUB = stub as usize;
|
||||
}
|
||||
@@ -316,7 +319,7 @@ pub fn install() {
|
||||
|
||||
unsafe {
|
||||
let addr = target as *mut u32;
|
||||
_patch_text(addr.add(1) as *mut c_void, frida_arm_fixup as usize as u32);
|
||||
_patch_text(addr.add(1) as *mut c_void, frida_arm_fixup as *const () as usize as u32);
|
||||
_patch_text(addr as *mut c_void, 0xe51ff004);
|
||||
}
|
||||
}
|
||||
@@ -449,7 +452,7 @@ pub fn install() {
|
||||
|
||||
unsafe { FRIDA_ARM64_ORIGINAL_CONT = target.add(4) as u64 };
|
||||
|
||||
let jump = detour_to(frida_arm64_fixup as usize);
|
||||
let jump = detour_to(frida_arm64_fixup as *const () as usize);
|
||||
unsafe {
|
||||
let addr = target as *mut u32;
|
||||
_aarch64_insn_patch_text_nosync(addr.add(2) as *mut c_void, jump[2]);
|
||||
@@ -526,7 +529,7 @@ unsafe fn recovered(regs: *mut c_void) -> bool {
|
||||
let esr: u64;
|
||||
unsafe { core::arch::asm!("mrs {}, esr_el1", out(reg) esr, options(nomem, nostack)) };
|
||||
crate::note_unhandled_fault(esr, faulted_at as u64, accessed as u64);
|
||||
context.pc = frida_arm64_park as usize as u64;
|
||||
context.pc = frida_arm64_park as *const () as usize as u64;
|
||||
unsafe { restore_context(regs, &context) };
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use alloc::string::String;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use core::ffi::c_void;
|
||||
use core::ffi::{CStr, c_void};
|
||||
use core::ptr;
|
||||
|
||||
use crate::bindings::{
|
||||
@@ -83,7 +83,7 @@ fn announce(image: &Image) {
|
||||
|
||||
let module = gum::gum_native_module_new(&image.path, "", &range);
|
||||
unsafe {
|
||||
gum_barebone_register_module(unsafe { REGISTRY }, module);
|
||||
gum_barebone_register_module(REGISTRY, module);
|
||||
g_object_unref(module as gpointer);
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,22 @@ pub fn enumerate_exports_in_range(from: u64, to: u64, found: &mut FoundExportCal
|
||||
}
|
||||
}
|
||||
|
||||
pub fn export_named(wanted: &str) -> u64 {
|
||||
let mut found: u64 = 0;
|
||||
for image in mapped_images() {
|
||||
enumerate_exports_in_range(image.base, image.base + image.size, &mut |name, address| {
|
||||
if !name.is_null() && unsafe { CStr::from_ptr(name as *const _) }.to_bytes() == wanted.as_bytes() {
|
||||
found = address;
|
||||
}
|
||||
found == 0
|
||||
});
|
||||
if found != 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
pub fn enumerate_symbols_in_range(from: u64, to: u64, found: &mut FoundSymbolCallback<'_>) {
|
||||
let Some(image) = mapped_images().into_iter().find(|image| image.base == from) else {
|
||||
return;
|
||||
|
||||
@@ -651,10 +651,6 @@ impl Regions {
|
||||
}
|
||||
}
|
||||
|
||||
fn reads_as_pointer(address: usize) -> bool {
|
||||
address >= LOWEST_MAPPING && address & (OFFSET_SIZE - 1) == 0
|
||||
}
|
||||
|
||||
fn try_read_word(address: usize) -> Option<usize> {
|
||||
Some(usize::from_ne_bytes(try_read(address)?))
|
||||
}
|
||||
@@ -767,7 +763,6 @@ const REGION_WINDOW: usize = 512;
|
||||
const MAX_REGIONS: usize = 16;
|
||||
const OFFSET_SIZE: usize = 4;
|
||||
const SYMBOL_SIZE: usize = if WORD == 8 { 24 } else { 16 };
|
||||
const LOWEST_MAPPING: usize = 1 << 20;
|
||||
const MAX_SYMBOLS: usize = 1 << 20;
|
||||
const MAX_EXPORTS: usize = 1 << 16;
|
||||
const EXPORTS_SAMPLED: usize = 64;
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
use core::ffi::{c_char, c_int, c_uint, c_void};
|
||||
use core::ptr;
|
||||
use core::ptr::read_volatile;
|
||||
use core::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
use core::sync::atomic::AtomicUsize;
|
||||
|
||||
use crate::kernel::ThreadEntry;
|
||||
|
||||
@@ -57,14 +59,14 @@ pub fn release_interrupt() {
|
||||
unsafe { _free_irq(interrupt.irq, interrupt.target) };
|
||||
}
|
||||
|
||||
pub fn take_the_file(descriptor: u32) -> *mut c_void {
|
||||
unsafe { _fget(descriptor) }
|
||||
}
|
||||
|
||||
pub fn take_the_file_of(task: *mut c_void, descriptor: u32) -> *mut c_void {
|
||||
unsafe { _fget_task(task, descriptor) }
|
||||
}
|
||||
|
||||
pub fn task_for_thread(id: u32) -> *mut c_void {
|
||||
unsafe { _find_task_by_vpid(id) }
|
||||
}
|
||||
|
||||
pub fn let_the_file_go(file: *mut c_void) {
|
||||
unsafe { super::processes::let_go_of(file) };
|
||||
}
|
||||
@@ -164,7 +166,10 @@ fn kcfi_thunk_cached(cache: &AtomicUsize, callback: usize, type_ref: Option<usiz
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn thread_entry() -> unsafe extern "C" fn(*mut c_void) -> c_int {
|
||||
let ref_fn = unsafe { _kthread_worker_fn.map(|f| f as usize) };
|
||||
unsafe { core::mem::transmute(kcfi_thunk_cached(&THREAD_THUNK, frida_cb_thread as usize, ref_fn)) }
|
||||
unsafe {
|
||||
core::mem::transmute(kcfi_thunk_cached(&THREAD_THUNK, frida_cb_thread as *const () as usize,
|
||||
ref_fn))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "aarch64"))]
|
||||
@@ -176,7 +181,8 @@ fn thread_entry() -> unsafe extern "C" fn(*mut c_void) -> c_int {
|
||||
fn interrupt_entry() -> unsafe extern "C" fn(c_int, *mut c_void) -> c_int {
|
||||
let ref_fn = unsafe { _vring_interrupt.map(|f| f as usize) };
|
||||
unsafe {
|
||||
core::mem::transmute(kcfi_thunk_cached(&INTERRUPT_THUNK, frida_cb_interrupt as usize, ref_fn))
|
||||
core::mem::transmute(kcfi_thunk_cached(&INTERRUPT_THUNK,
|
||||
frida_cb_interrupt as *const () as usize, ref_fn))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,14 +309,15 @@ pub fn patch_text(address: u64, data: *const u8, len: usize) -> bool {
|
||||
|
||||
let count = len / 4;
|
||||
|
||||
let mut addrs = alloc::vec::Vec::with_capacity(count);
|
||||
let mut insns = alloc::vec::Vec::with_capacity(count);
|
||||
for i in 0..count {
|
||||
addrs.push((address as usize + (i * 4)) as *mut c_void);
|
||||
insns.push(unsafe { (data as *const u32).add(i).read_unaligned() });
|
||||
let insn = unsafe { (data as *const u32).add(i).read_unaligned() };
|
||||
let at = (address as usize + (i * 4)) as *mut c_void;
|
||||
if unsafe { _aarch64_insn_patch_text_nosync(at, insn) } != 0 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe { _aarch64_insn_patch_text(addrs.as_mut_ptr(), insns.as_ptr(), count as c_int) == 0 }
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "arm")]
|
||||
@@ -368,7 +375,9 @@ pub fn set_protection(address: u64, size: usize, protection: u32) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
const GUM_PAGE_WRITE: u32 = 2;
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
const GUM_PAGE_EXECUTE: u32 = 4;
|
||||
|
||||
pub fn current_process_id() -> u32 {
|
||||
@@ -823,16 +832,25 @@ const WAIT_ENTRY_WAKE: usize = 2;
|
||||
const WAIT_ENTRY_QUEUED: usize = 3;
|
||||
const WAIT_QUEUE_WORDS: usize = 16;
|
||||
const LOCK_KEY_WORDS: usize = 8;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const DEVICE_MEMORY: u64 = 0x04;
|
||||
const ORDINARY_MEMORY: u64 = 0xff;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const ATTRIBUTES_KEPT: u64 = 8;
|
||||
const VM_MAP: u64 = 0x4;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const PTE_TYPE_PAGE: u64 = 0x3;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const PTE_SHARED: u64 = 3 << 8;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const PTE_AF: u64 = 1 << 10;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const PTE_WRITE: u64 = 1 << 51;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const PTE_DIRTY: u64 = 1 << 55;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const PTE_PXN: u64 = 1 << 53;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const PTE_UXN: u64 = 1 << 54;
|
||||
const IRQF_SHARED: usize = 0x80;
|
||||
const IRQ_NONE: c_int = 0;
|
||||
@@ -887,8 +905,7 @@ unsafe extern "C" {
|
||||
static _set_memory_x: Option<unsafe extern "C" fn(usize, c_int) -> c_int>;
|
||||
static _set_memory_nx: Option<unsafe extern "C" fn(usize, c_int) -> c_int>;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
static _aarch64_insn_patch_text:
|
||||
unsafe extern "C" fn(*mut *mut c_void, *const u32, c_int) -> c_int;
|
||||
static _aarch64_insn_patch_text_nosync: unsafe extern "C" fn(*mut c_void, u32) -> c_int;
|
||||
// Addresses of kernel functions of the same C signature as our kthread and IRQ
|
||||
// callbacks; the kCFI type-id the kernel checks sits in the word before each.
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
@@ -1051,10 +1068,10 @@ unsafe extern "C" {
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
const THREAD_ENTRY: unsafe extern "C" fn(*mut c_void) -> c_int = frida_kcb_thread;
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
#[cfg(not(any(target_arch = "x86", target_arch = "aarch64")))]
|
||||
const THREAD_ENTRY: unsafe extern "C" fn(*mut c_void) -> c_int = frida_cb_thread;
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
const INTERRUPT_ENTRY: unsafe extern "C" fn(c_int, *mut c_void) -> c_int = frida_kcb_interrupt;
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
#[cfg(not(any(target_arch = "x86", target_arch = "aarch64")))]
|
||||
const INTERRUPT_ENTRY: unsafe extern "C" fn(c_int, *mut c_void) -> c_int = frida_cb_interrupt;
|
||||
@@ -1,3 +1,5 @@
|
||||
use alloc::format;
|
||||
use alloc::string::String;
|
||||
use alloc::vec::Vec;
|
||||
use core::ffi::{c_char, c_int, c_long, c_void};
|
||||
use core::ptr;
|
||||
@@ -7,6 +9,10 @@ pub struct ProcessInfo {
|
||||
pub name: *const u8,
|
||||
pub path: *const u8,
|
||||
pub command_line: *const u8,
|
||||
pub uid: u32,
|
||||
pub user: *const u8,
|
||||
pub ppid: u32,
|
||||
pub started: i64,
|
||||
}
|
||||
|
||||
pub fn enumerate_processes(found: &mut dyn FnMut(ProcessInfo)) {
|
||||
@@ -16,14 +22,31 @@ pub fn enumerate_processes(found: &mut dyn FnMut(ProcessInfo)) {
|
||||
|
||||
let mut path = Vec::new();
|
||||
path.resize(PATH_MAX, 0u8);
|
||||
let mut cmdline = Vec::new();
|
||||
cmdline.resize(CMDLINE_MAX, 0u8);
|
||||
let mut label = Vec::new();
|
||||
label.resize(NAME_MAX, 0u8);
|
||||
let mut owner = Vec::new();
|
||||
owner.resize(NAME_MAX, 0u8);
|
||||
|
||||
let (now_boottime, now_realtime) = current_time();
|
||||
|
||||
for task in take_task_snapshot(layout) {
|
||||
found(ProcessInfo {
|
||||
id: task.id,
|
||||
name: task.name.as_ptr(),
|
||||
path: path_of(task.executable, &mut path),
|
||||
command_line: ptr::null(),
|
||||
});
|
||||
if !task.memory.is_null() {
|
||||
let (name, command_line) = describe(task.memory, &mut cmdline, &mut label)
|
||||
.unwrap_or((task.name.as_ptr(), ptr::null()));
|
||||
found(ProcessInfo {
|
||||
id: task.id,
|
||||
name,
|
||||
path: path_of(task.executable, &mut path),
|
||||
command_line,
|
||||
uid: task.uid,
|
||||
user: format_user(task.uid, &mut owner),
|
||||
ppid: task.ppid,
|
||||
started: wall_time(task.started, now_boottime, now_realtime),
|
||||
});
|
||||
unsafe { _mmput(task.memory) };
|
||||
}
|
||||
|
||||
if !task.executable.is_null() {
|
||||
unsafe { _fput(task.executable) };
|
||||
@@ -69,6 +92,10 @@ struct Task {
|
||||
id: u32,
|
||||
name: [u8; NAME_SIZE + 1],
|
||||
executable: *mut c_void,
|
||||
memory: *mut c_void,
|
||||
uid: u32,
|
||||
ppid: u32,
|
||||
started: u64,
|
||||
}
|
||||
|
||||
fn take_task_snapshot(layout: &Layout) -> Vec<Task> {
|
||||
@@ -94,14 +121,162 @@ fn read_task(task: usize, layout: &Layout) -> Task {
|
||||
id: read_id(task, layout),
|
||||
name,
|
||||
executable: unsafe { _get_task_exe_file(task as *mut c_void) },
|
||||
memory: unsafe { _get_task_mm(task as *mut c_void) },
|
||||
uid: read_uid(task, layout),
|
||||
ppid: read_ppid(task, layout),
|
||||
started: layout.started.and_then(|at| read_kernel_word(task + at)).unwrap_or(0) as u64,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_id(task: usize, layout: &Layout) -> u32 {
|
||||
let mut id = [0u8; 4];
|
||||
read_kernel(task + layout.id, &mut id);
|
||||
fn read_uid(task: usize, layout: &Layout) -> u32 {
|
||||
let (Some(credentials), Some(uid)) = (layout.credentials, layout.uid) else {
|
||||
return 0;
|
||||
};
|
||||
let Some(cred) = read_kernel_word(task + credentials) else {
|
||||
return 0;
|
||||
};
|
||||
read_kernel_u32(cred + uid)
|
||||
}
|
||||
|
||||
u32::from_ne_bytes(id)
|
||||
fn read_ppid(task: usize, layout: &Layout) -> u32 {
|
||||
let (Some(parent), Some(group)) = (layout.parent, layout.group) else {
|
||||
return 0;
|
||||
};
|
||||
let Some(task) = read_kernel_word(task + parent) else {
|
||||
return 0;
|
||||
};
|
||||
read_kernel_u32(task + group)
|
||||
}
|
||||
|
||||
fn read_id(task: usize, layout: &Layout) -> u32 {
|
||||
read_kernel_u32(task + layout.id)
|
||||
}
|
||||
|
||||
fn read_kernel_u32(address: usize) -> u32 {
|
||||
let mut bytes = [0u8; 4];
|
||||
if !read_kernel(address, &mut bytes) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
u32::from_ne_bytes(bytes)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn describe(memory: *mut c_void, cmdline: &mut [u8], label: &mut [u8]) -> Option<(*const u8, *const u8)> {
|
||||
let read = read_cmdline(memory, cmdline)?;
|
||||
let name = base_name(&cmdline[..read], label);
|
||||
let command_line = join_arguments(cmdline, read);
|
||||
Some((name, command_line))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "aarch64"))]
|
||||
fn describe(_memory: *mut c_void, _cmdline: &mut [u8], _label: &mut [u8]) -> Option<(*const u8, *const u8)> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn read_cmdline(memory: *mut c_void, buffer: &mut [u8]) -> Option<usize> {
|
||||
let start = read_kernel_word(memory as usize + super::layout::field_offset("mm_struct", "arg_start")?)?;
|
||||
if start == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let room = buffer.len() - 1;
|
||||
unsafe { _kthread_use_mm(memory) };
|
||||
let missed = unsafe {
|
||||
___arch_copy_from_user(buffer.as_mut_ptr() as *mut c_void, start as *const c_void, room)
|
||||
};
|
||||
unsafe { _kthread_unuse_mm(memory) };
|
||||
|
||||
let read = room - missed;
|
||||
(read != 0).then_some(read)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn base_name(arguments: &[u8], label: &mut [u8]) -> *const u8 {
|
||||
let first = &arguments[..arguments.iter().position(|byte| *byte == 0).unwrap_or(arguments.len())];
|
||||
let start = first.iter().rposition(|byte| *byte == b'/').map_or(0, |slash| slash + 1);
|
||||
let name = &first[start..];
|
||||
|
||||
let taken = name.len().min(label.len() - 1);
|
||||
label[..taken].copy_from_slice(&name[..taken]);
|
||||
label[taken] = 0;
|
||||
|
||||
label.as_ptr()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn join_arguments(cmdline: &mut [u8], read: usize) -> *const u8 {
|
||||
for byte in &mut cmdline[..read] {
|
||||
if *byte == 0 {
|
||||
*byte = b' ';
|
||||
}
|
||||
}
|
||||
cmdline[read] = 0;
|
||||
|
||||
cmdline.as_ptr()
|
||||
}
|
||||
|
||||
fn format_user(uid: u32, buffer: &mut [u8]) -> *const u8 {
|
||||
let text = user_label(uid);
|
||||
let bytes = text.as_bytes();
|
||||
|
||||
let taken = bytes.len().min(buffer.len() - 1);
|
||||
buffer[..taken].copy_from_slice(&bytes[..taken]);
|
||||
buffer[taken] = 0;
|
||||
|
||||
buffer.as_ptr()
|
||||
}
|
||||
|
||||
fn user_label(uid: u32) -> String {
|
||||
let user = uid / AID_USER_OFFSET;
|
||||
let app = uid % AID_USER_OFFSET;
|
||||
|
||||
if (AID_APP_START..AID_APP_END).contains(&app) {
|
||||
return format!("u{}_a{}", user, app - AID_APP_START);
|
||||
}
|
||||
|
||||
match app {
|
||||
0 => "root".into(),
|
||||
1000 => "system".into(),
|
||||
1001 => "radio".into(),
|
||||
2000 => "shell".into(),
|
||||
_ => format!("{}", uid),
|
||||
}
|
||||
}
|
||||
|
||||
fn wall_time(started: u64, now_boottime: u64, now_realtime: u64) -> i64 {
|
||||
if started == 0 || started > now_boottime {
|
||||
return 0;
|
||||
}
|
||||
let age = now_boottime - started;
|
||||
if age > now_realtime {
|
||||
return 0;
|
||||
}
|
||||
|
||||
((now_realtime - age) / 1_000_000_000) as i64
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
fn current_time() -> (u64, u64) {
|
||||
let mut wall = Timespec { seconds: 0, nanoseconds: 0 };
|
||||
unsafe { _ktime_get_real_ts64(&mut wall) };
|
||||
let wallclock = (wall.seconds as u64) * 1_000_000_000 + (wall.nanoseconds as u64);
|
||||
let uptime = unsafe { _ktime_get_mono_fast_ns() };
|
||||
|
||||
(uptime, wallclock)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
fn current_time() -> (u64, u64) {
|
||||
(0, 0)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
#[repr(C)]
|
||||
struct Timespec {
|
||||
seconds: i64,
|
||||
nanoseconds: i64,
|
||||
}
|
||||
|
||||
fn path_of(executable: *mut c_void, buffer: &mut [u8]) -> *const u8 {
|
||||
@@ -175,6 +350,11 @@ struct Layout {
|
||||
list: usize,
|
||||
name: usize,
|
||||
id: usize,
|
||||
credentials: Option<usize>,
|
||||
uid: Option<usize>,
|
||||
parent: Option<usize>,
|
||||
group: Option<usize>,
|
||||
started: Option<usize>,
|
||||
}
|
||||
|
||||
fn discover_layout() -> Option<Layout> {
|
||||
@@ -189,16 +369,32 @@ fn discover_layout() -> Option<Layout> {
|
||||
let name = find(&image, IDLE_TASK_NAME)?;
|
||||
let (list, id) = find_task_list(init, &image, name)?;
|
||||
|
||||
Some(Layout { init, list, name, id })
|
||||
Some(Layout {
|
||||
init,
|
||||
list,
|
||||
name,
|
||||
id,
|
||||
credentials: None,
|
||||
uid: None,
|
||||
parent: None,
|
||||
group: None,
|
||||
started: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn described_layout(init: usize) -> Option<Layout> {
|
||||
use super::layout::field_offset;
|
||||
|
||||
Some(Layout {
|
||||
init,
|
||||
list: super::layout::field_offset("task_struct", "tasks")?,
|
||||
name: super::layout::field_offset("task_struct", "comm")?,
|
||||
id: super::layout::field_offset("task_struct", "pid")?,
|
||||
list: field_offset("task_struct", "tasks")?,
|
||||
name: field_offset("task_struct", "comm")?,
|
||||
id: field_offset("task_struct", "pid")?,
|
||||
credentials: field_offset("task_struct", "real_cred"),
|
||||
uid: field_offset("cred", "uid"),
|
||||
parent: field_offset("task_struct", "real_parent"),
|
||||
group: field_offset("task_struct", "tgid"),
|
||||
started: field_offset("task_struct", "start_time"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -503,6 +699,11 @@ fn write_unlock_tasklist(flags: usize) {
|
||||
const IDLE_TASK_NAME: &[u8] = b"swapper";
|
||||
const NAME_SIZE: usize = 16;
|
||||
const PATH_MAX: usize = 4096;
|
||||
const CMDLINE_MAX: usize = 512;
|
||||
const NAME_MAX: usize = 256;
|
||||
const AID_USER_OFFSET: u32 = 100000;
|
||||
const AID_APP_START: u32 = 10000;
|
||||
const AID_APP_END: u32 = 20000;
|
||||
|
||||
const MAX_TASK_SIZE: usize = 16 * 1024;
|
||||
const READ_CHUNK: usize = 64;
|
||||
@@ -545,6 +746,21 @@ unsafe extern "C" {
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
static _copy_from_kernel_nofault:
|
||||
unsafe extern "C" fn(*mut c_void, *const c_void, usize) -> c_long;
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
static _get_task_mm: unsafe extern "C" fn(*mut c_void) -> *mut c_void;
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
static _mmput: unsafe extern "C" fn(*mut c_void);
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
static _kthread_use_mm: unsafe extern "C" fn(*mut c_void);
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
static _kthread_unuse_mm: unsafe extern "C" fn(*mut c_void);
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
static ___arch_copy_from_user:
|
||||
unsafe extern "C" fn(*mut c_void, *const c_void, usize) -> usize;
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
static _ktime_get_real_ts64: unsafe extern "C" fn(*mut Timespec);
|
||||
#[cfg(not(target_arch = "x86"))]
|
||||
static _ktime_get_mono_fast_ns: unsafe extern "C" fn() -> u64;
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
@@ -567,4 +783,8 @@ unsafe extern "C" {
|
||||
fn _file_path(a0: *mut c_void, a1: *mut c_char, a2: c_int) -> *const c_char;
|
||||
#[link_name = "frida_k_fput"]
|
||||
fn _fput(a0: *mut c_void);
|
||||
#[link_name = "frida_k_get_task_mm"]
|
||||
fn _get_task_mm(a0: *mut c_void) -> *mut c_void;
|
||||
#[link_name = "frida_k_mmput"]
|
||||
fn _mmput(a0: *mut c_void);
|
||||
}
|
||||
@@ -34,6 +34,15 @@ void * frida_k_fget_task (void * a0, unsigned int a1)
|
||||
return ((fn_t) _fget_task) (a0, a1);
|
||||
}
|
||||
|
||||
extern void * _find_task_by_vpid;
|
||||
|
||||
void * frida_k_find_task_by_vpid (unsigned int a0)
|
||||
{
|
||||
typedef void * (__attribute__((regparm(3))) * fn_t) (unsigned int);
|
||||
|
||||
return ((fn_t) _find_task_by_vpid) (a0);
|
||||
}
|
||||
|
||||
extern void * _kernel_read;
|
||||
|
||||
long frida_k_kernel_read (void * a0, void * a1, unsigned long a2, void * a3)
|
||||
|
||||
@@ -3,6 +3,7 @@ use alloc::vec::Vec;
|
||||
use core::ffi::{c_int, c_void};
|
||||
use core::mem::size_of;
|
||||
use core::ptr;
|
||||
use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
|
||||
|
||||
use super::layout::field_offset;
|
||||
use super::native;
|
||||
@@ -77,6 +78,65 @@ pub fn holds_this_one(task: usize) -> bool {
|
||||
held != 0 && held == id
|
||||
}
|
||||
|
||||
pub fn arm_named_spawn(name: &[u8]) {
|
||||
let end = name.iter().position(|byte| *byte == 0).unwrap_or(name.len());
|
||||
let name = &name[..end];
|
||||
let start = name.len().saturating_sub(COMM_LEN);
|
||||
let held = &name[start..];
|
||||
|
||||
unsafe { (&raw mut WANTED_COMM).as_mut().unwrap()[..held.len()].copy_from_slice(held) };
|
||||
WANTED_LEN.store(held.len(), Ordering::Release);
|
||||
|
||||
super::injection::watch_for_named_spawns();
|
||||
}
|
||||
|
||||
pub fn disarm_named_spawn(_name: &[u8]) {
|
||||
WANTED_LEN.store(0, Ordering::Release);
|
||||
}
|
||||
|
||||
// Runs in the rename tracepoint's atomic context: no allocation, no sleeping lock, no glib.
|
||||
pub fn claim_if_wanted(comm: &[u8]) -> bool {
|
||||
let len = WANTED_LEN.load(Ordering::Acquire);
|
||||
if len == 0 || comm.len() != len {
|
||||
return false;
|
||||
}
|
||||
let wanted = unsafe { core::slice::from_raw_parts((&raw const WANTED_COMM) as *const u8, len) };
|
||||
if comm != wanted {
|
||||
return false;
|
||||
}
|
||||
|
||||
WANTED_LEN.compare_exchange(len, 0, Ordering::AcqRel, Ordering::Acquire).is_ok()
|
||||
}
|
||||
|
||||
pub fn note_pending_spawn(id: u32, comm: &[u8]) {
|
||||
let len = comm.len().min(COMM_LEN);
|
||||
unsafe { (&raw mut PENDING_COMM).as_mut().unwrap()[..len].copy_from_slice(&comm[..len]) };
|
||||
PENDING_LEN.store(len, Ordering::Release);
|
||||
PENDING_HELD.store(id, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn a_pending_spawn_waits() -> bool {
|
||||
PENDING_HELD.load(Ordering::Acquire) != 0
|
||||
}
|
||||
|
||||
pub fn drain_pending_spawn() {
|
||||
let id = PENDING_HELD.swap(0, Ordering::AcqRel);
|
||||
if id == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let len = PENDING_LEN.load(Ordering::Acquire);
|
||||
let name = unsafe { core::slice::from_raw_parts((&raw const PENDING_COMM) as *const u8, len).to_vec() };
|
||||
unsafe { held_spawns() }.push((id, name));
|
||||
}
|
||||
|
||||
static mut WANTED_COMM: [u8; COMM_LEN] = [0; COMM_LEN];
|
||||
static WANTED_LEN: AtomicUsize = AtomicUsize::new(0);
|
||||
static mut PENDING_COMM: [u8; COMM_LEN] = [0; COMM_LEN];
|
||||
static PENDING_LEN: AtomicUsize = AtomicUsize::new(0);
|
||||
static PENDING_HELD: AtomicU32 = AtomicU32::new(0);
|
||||
const COMM_LEN: usize = 15;
|
||||
|
||||
// A spawn is held in the kernel's own exec path, where telling the host is not this thread's
|
||||
// to do; the loop says it once it is back where sending a frame belongs.
|
||||
pub fn note_a_held_spawn(id: u32, program: *const u8) {
|
||||
|
||||
@@ -2,20 +2,50 @@ use alloc::ffi::CString;
|
||||
use alloc::format;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use crate::bindings::{
|
||||
GumThreadState, GumThreadState_GUM_THREAD_HALTED, GumThreadState_GUM_THREAD_RUNNING,
|
||||
GumThreadState_GUM_THREAD_STOPPED, GumThreadState_GUM_THREAD_UNINTERRUPTIBLE,
|
||||
GumThreadState_GUM_THREAD_WAITING,
|
||||
};
|
||||
use crate::kernel::ThreadInfo;
|
||||
|
||||
use super::facade::{home_process_id, in_copy};
|
||||
use super::processes::running_task_ids;
|
||||
use super::user::names_in;
|
||||
use super::user::{contents_of, names_in};
|
||||
|
||||
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo)) {
|
||||
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
|
||||
let copy = in_copy();
|
||||
let ids = if copy { running_threads() } else { running_task_ids() };
|
||||
for id in ids {
|
||||
if copy && super::user::thread_is_ours(id) {
|
||||
continue;
|
||||
}
|
||||
found(ThreadInfo { id, cpu_state: None });
|
||||
let (state, cpu_state) = if !with_registers {
|
||||
(None, None)
|
||||
} else if copy {
|
||||
(state_from_proc(id), super::user::ask_the_kernel_half_for_registers(id))
|
||||
} else {
|
||||
(super::injection::thread_state(id), super::injection::capture_registers(id))
|
||||
};
|
||||
found(ThreadInfo { id, state, cpu_state });
|
||||
}
|
||||
}
|
||||
|
||||
fn state_from_proc(id: u32) -> Option<GumThreadState> {
|
||||
let path = CString::new(format!("/proc/{}/task/{}/stat", home_process_id(), id)).ok()?;
|
||||
let stat = contents_of(&path);
|
||||
let last_paren = stat.iter().rposition(|&byte| byte == b')')?;
|
||||
let state_letter = *stat.get(last_paren + 2)?;
|
||||
Some(gum_thread_state(state_letter))
|
||||
}
|
||||
|
||||
fn gum_thread_state(letter: u8) -> GumThreadState {
|
||||
match letter {
|
||||
b'R' => GumThreadState_GUM_THREAD_RUNNING,
|
||||
b'S' => GumThreadState_GUM_THREAD_WAITING,
|
||||
b'D' => GumThreadState_GUM_THREAD_UNINTERRUPTIBLE,
|
||||
b'T' | b't' => GumThreadState_GUM_THREAD_STOPPED,
|
||||
_ => GumThreadState_GUM_THREAD_HALTED,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ use super::arena::{Arena, FAULT_ADDRESS, FAULT_KIND, FAULT_LR, FAULT_PC, WOKEN};
|
||||
use super::facade::Primitives;
|
||||
|
||||
pub fn entry_offset() -> usize {
|
||||
(frida_linux_user_entry as usize) - crate::own_range().0
|
||||
(frida_linux_user_entry as *const () as usize) - crate::own_range().0
|
||||
}
|
||||
|
||||
// The copy's first word in the address space it was placed in: it says it is up, and from then
|
||||
@@ -97,10 +97,6 @@ pub fn thread_is_ours(id: u32) -> bool {
|
||||
id != 0 && unsafe { CLOAK_THREADS }.contains(&id)
|
||||
}
|
||||
|
||||
pub fn fd_is_ours(fd: u32) -> bool {
|
||||
fd != 0 && unsafe { CLOAK_FDS }.contains(&fd)
|
||||
}
|
||||
|
||||
fn serve_the_copy() {
|
||||
drain_loop_wakeup();
|
||||
let arena = Arena::at(unsafe { ARENA });
|
||||
@@ -230,6 +226,21 @@ fn ask_the_kernel_half_to_make_executable(address: u64, size: usize) -> bool {
|
||||
arena.executable_was_granted()
|
||||
}
|
||||
|
||||
pub fn ask_the_kernel_half_for_registers(id: u32) -> Option<crate::kernel::CpuState> {
|
||||
let arena = Arena::at(unsafe { ARENA });
|
||||
let seq = arena.request_registers(id);
|
||||
arena.tell_the_kernel_half();
|
||||
while !arena.registers_settled(seq) {
|
||||
yield_now();
|
||||
}
|
||||
if !arena.registers_were_captured() {
|
||||
return None;
|
||||
}
|
||||
let mut words = [0u64; super::injection::REGISTER_WORDS];
|
||||
arena.captured_registers(&mut words);
|
||||
Some(super::injection::registers_from_words(&words))
|
||||
}
|
||||
|
||||
pub fn map_writable(size: usize) -> *mut u8 {
|
||||
map(size, READABLE | WRITABLE)
|
||||
}
|
||||
@@ -314,6 +325,7 @@ fn stand_on_a_thread_pointer() {
|
||||
unsafe { core::arch::asm!("mov gs, {:e}", in(reg) selector, options(nomem, nostack)) };
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
#[repr(C)]
|
||||
struct UserDesc {
|
||||
entry_number: u32,
|
||||
@@ -449,7 +461,7 @@ unsafe extern "C" {
|
||||
unsafe fn start_thread(stack: usize, carried: usize) -> isize {
|
||||
let launch = stack - 8;
|
||||
unsafe {
|
||||
(launch as *mut usize).write(enter_thread as usize);
|
||||
(launch as *mut usize).write(enter_thread as *const () as usize);
|
||||
((launch + 4) as *mut usize).write(carried);
|
||||
|
||||
frida_start_thread(CLONE, THREAD_FLAGS, launch)
|
||||
@@ -583,7 +595,8 @@ struct TimeSpec {
|
||||
nanoseconds: i64,
|
||||
}
|
||||
|
||||
unsafe extern "C" fn frida_poll(ufds: *mut crate::GPollFd, nfds: u32, timeout: i32) -> i32 {
|
||||
pub(crate) unsafe extern "C" fn frida_poll(ufds: *mut crate::bindings::GPollFD, nfds: u32,
|
||||
timeout: i32) -> i32 {
|
||||
const MAX_FDS: usize = 16;
|
||||
let fds = unsafe { core::slice::from_raw_parts_mut(ufds, nfds as usize) };
|
||||
|
||||
@@ -712,7 +725,7 @@ fn current_thread_id() -> u64 {
|
||||
fn install_fault_reporter() {
|
||||
for signal in [ILLEGAL, ABORTED, BUS, SEGMENT, ARITHMETIC, TRAPPED, BAD_CALL] {
|
||||
let action = Action {
|
||||
handler: report_fault as usize,
|
||||
handler: report_fault as *const () as usize,
|
||||
flags: SIGINFO | RESTORER_FLAG,
|
||||
restorer: restorer(),
|
||||
blocked: 0,
|
||||
@@ -1086,7 +1099,7 @@ const RESTORER_FLAG: usize = 0;
|
||||
target_arch = "arm"
|
||||
))]
|
||||
fn restorer() -> usize {
|
||||
sigreturn_trampoline as usize
|
||||
sigreturn_trampoline as *const () as usize
|
||||
}
|
||||
#[cfg(not(any(
|
||||
target_arch = "aarch64",
|
||||
@@ -1191,6 +1204,18 @@ pub fn names_in(directory: &core::ffi::CStr) -> Vec<String> {
|
||||
names
|
||||
}
|
||||
|
||||
pub(crate) fn read(fd: i32, buffer: *mut u8, count: usize) -> isize {
|
||||
syscall(READ, fd as usize, buffer as usize, count, 0, 0, 0)
|
||||
}
|
||||
|
||||
pub(crate) fn write(fd: i32, buffer: *const u8, count: usize) -> isize {
|
||||
syscall(WRITE, fd as usize, buffer as usize, count, 0, 0, 0)
|
||||
}
|
||||
|
||||
pub(crate) fn close(fd: i32) -> isize {
|
||||
syscall(CLOSE, fd as usize, 0, 0, 0, 0, 0)
|
||||
}
|
||||
|
||||
pub fn contents_of(path: &core::ffi::CStr) -> Vec<u8> {
|
||||
let file = syscall(OPENAT, WORKING_DIRECTORY, path.as_ptr() as usize, READ_ONLY, 0, 0, 0);
|
||||
if file < 0 {
|
||||
@@ -1457,12 +1482,6 @@ const GETDENTS: usize = 220;
|
||||
const GETDENTS: usize = 217;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const GETDENTS: usize = 61;
|
||||
#[cfg(target_arch = "x86")]
|
||||
const POLL: usize = 168;
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const POLL: usize = 7;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const POLL: usize = 73;
|
||||
#[cfg(target_arch = "arm")]
|
||||
const READ: usize = 3;
|
||||
#[cfg(target_arch = "x86")]
|
||||
@@ -1568,7 +1587,6 @@ const MPROTECT: usize = 10;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const MPROTECT: usize = 226;
|
||||
|
||||
const STANDARD_ERROR: usize = 2;
|
||||
const WORKING_DIRECTORY: usize = -100isize as usize;
|
||||
const READ_ONLY: usize = 0;
|
||||
const POLL_IN: i32 = 1;
|
||||
|
||||
@@ -37,7 +37,7 @@ impl SymbolTable {
|
||||
self.symbol_count
|
||||
}
|
||||
|
||||
pub fn find_symbol_by_name(&self, name: &str) -> Option<SymbolRef> {
|
||||
pub fn find_symbol_by_name(&self, name: &str) -> Option<SymbolRef<'_>> {
|
||||
let (_, entry) = self.binary_search_by_name(name)?;
|
||||
Some(SymbolRef {
|
||||
symbol_table: self,
|
||||
@@ -46,7 +46,7 @@ impl SymbolTable {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn find_symbols_by_name(&self, name: &str) -> SymbolsByNameIterator {
|
||||
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),
|
||||
@@ -83,7 +83,7 @@ impl SymbolTable {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_symbols_matching_glob(&self, pattern: &str) -> SymbolsMatchingIterator {
|
||||
pub fn find_symbols_matching_glob(&self, pattern: &str) -> SymbolsMatchingIterator<'_> {
|
||||
if self.is_empty() {
|
||||
return SymbolsMatchingIterator::empty(self);
|
||||
}
|
||||
@@ -100,7 +100,7 @@ impl SymbolTable {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_symbol_by_address(&self, address: u64) -> Option<SymbolRef> {
|
||||
pub fn find_symbol_by_address(&self, address: u64) -> Option<SymbolRef<'_>> {
|
||||
let target_offset = address - get_kernel_base();
|
||||
let (_, entry) = self.binary_search_by_address(target_offset)?;
|
||||
Some(SymbolRef {
|
||||
@@ -119,7 +119,7 @@ impl SymbolTable {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_closest_symbol_by_address(&self, address: u64) -> Option<SymbolRef> {
|
||||
pub fn find_closest_symbol_by_address(&self, address: u64) -> Option<SymbolRef<'_>> {
|
||||
let kernel_base = get_kernel_base();
|
||||
let target_offset = address - kernel_base;
|
||||
let (_, entry) = self.binary_search_closest_by_address(target_offset)?;
|
||||
@@ -130,7 +130,9 @@ impl SymbolTable {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn iter_symbols_in_range(&self, start_address: u64, end_address: u64) -> SymbolsInRangeIterator {
|
||||
pub fn iter_symbols_in_range(&self, start_address: u64, end_address: u64)
|
||||
-> SymbolsInRangeIterator<'_>
|
||||
{
|
||||
if self.is_empty() {
|
||||
return SymbolsInRangeIterator {
|
||||
symbol_table: self,
|
||||
|
||||
+140
-55
@@ -192,7 +192,11 @@ fn block_until_signalled_or_timed_out(semaphore: u32, timeout_us: u64) {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn poke_loop_wakeup() {}
|
||||
pub fn poke_loop_wakeup() {
|
||||
if in_copy() {
|
||||
crate::win9x_user::poke_loop_wakeup();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wake(token: *const u8) {
|
||||
(primitives().wake)(token)
|
||||
@@ -220,7 +224,8 @@ pub fn inject_agent(pid: u32) -> u32 {
|
||||
0xff, 0x74, 0x24, 0x04,
|
||||
0xba, 0, 0, 0, 0,
|
||||
0xff, 0xd2,
|
||||
0xeb, 0xfe,
|
||||
0x59,
|
||||
0xc3,
|
||||
];
|
||||
payload[5..9].copy_from_slice(&entry.to_le_bytes());
|
||||
|
||||
@@ -244,6 +249,7 @@ pub fn inject_agent(pid: u32) -> u32 {
|
||||
unsafe {
|
||||
targets().insert(observed, Target {
|
||||
arena: injection.arena,
|
||||
thread: injection.thread,
|
||||
stack: injection.stack,
|
||||
image_base,
|
||||
})
|
||||
@@ -532,15 +538,15 @@ pub fn detach_from_process(pid: u32) -> bool {
|
||||
};
|
||||
let arena = target.arena;
|
||||
|
||||
unsafe { DEPARTING_THREAD = target.thread };
|
||||
unsafe { ((arena + STOP_REQUEST) as *mut u32).write_volatile(1) };
|
||||
if !await_flag(arena + WORKER_STOPPED) || !await_flag(arena + MAIN_STOPPED) {
|
||||
wake_copy(arena);
|
||||
if !await_flag(arena + WORKER_STOPPED) || !await_flag(arena + MAIN_STOPPED)
|
||||
|| !await_departure()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// A thread sets the flag before it leaves. Thus wait for the time it needs to run its last
|
||||
// instructions and return into KERNEL32.
|
||||
wait(core::ptr::addr_of!(TEARDOWN_TOKEN), Some(TEARDOWN_GRACE_US), &mut || false);
|
||||
|
||||
forget_hold(arena);
|
||||
|
||||
unsafe {
|
||||
@@ -556,13 +562,26 @@ pub fn detach_from_process(pid: u32) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn await_departure() -> bool {
|
||||
for _ in 0..INJECTION_ATTEMPTS {
|
||||
if unsafe { (&raw const DEPARTING_THREAD).read_volatile() } == 0 {
|
||||
return true;
|
||||
}
|
||||
wait(core::ptr::addr_of!(DEPARTURE_TOKEN), Some(INJECTION_POLL_US), &mut || false);
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
struct Target {
|
||||
arena: u32,
|
||||
thread: u32,
|
||||
stack: u32,
|
||||
image_base: u32,
|
||||
}
|
||||
|
||||
static mut TEARDOWN_TOKEN: u8 = 0;
|
||||
static mut DEPARTING_THREAD: u32 = 0;
|
||||
static mut DEPARTURE_TOKEN: u8 = 0;
|
||||
|
||||
pub fn arena_for_pid(pid: u32) -> Option<u64> {
|
||||
unsafe { targets().get(&pid).map(|t| t.arena as u64) }
|
||||
@@ -746,7 +765,7 @@ fn place_shared_agent() -> (u32, u32) {
|
||||
crate::install_writable_half(base as usize, (base + private_offset as u32) as usize);
|
||||
}
|
||||
|
||||
let entry = base + (crate::win9x_user::frida_win9x_user_main as usize
|
||||
let entry = base + (crate::win9x_user::frida_win9x_user_main as *const () as usize
|
||||
- own.base_address as usize) as u32;
|
||||
|
||||
(base, entry)
|
||||
@@ -784,12 +803,13 @@ pub fn inject(process: u32, payload: &[u8]) -> Injection {
|
||||
|
||||
let database = unsafe { ((arena + THREAD_DATABASE) as *const u32).read_volatile() };
|
||||
let thread = unsafe { (database as *const u32).byte_add(TDB_CONTROL_BLOCK).read() };
|
||||
redirect_to_trampoline(arena, thread);
|
||||
let start_stack = redirect_to_trampoline(arena, thread);
|
||||
|
||||
resume_thread(arena + RESUME_STUB_OFFSET, arena);
|
||||
if !await_flag(arena + RUNNING_FLAG) {
|
||||
return Injection { arena, thread: 0, stack };
|
||||
}
|
||||
free_shared(start_stack);
|
||||
unsafe {
|
||||
((arena + GATING) as *mut u32).write_volatile(spawns_are_gated() as u32);
|
||||
((arena + GO_FLAG) as *mut u32).write_volatile(1);
|
||||
@@ -1030,18 +1050,24 @@ fn write_trampoline(trampoline: u32, entry: u32, stack_top: u32) {
|
||||
0x50,
|
||||
0xba, 0, 0, 0, 0,
|
||||
0xff, 0xd2,
|
||||
0x64, 0xa1, 0x18, 0x00, 0x00, 0x00,
|
||||
0x89, 0x60, 0x58,
|
||||
0x89, 0x60, 0x04,
|
||||
0xc7, 0x40, 0x08, 0, 0, 0, 0,
|
||||
0x6a, 0x00,
|
||||
0xba, 0, 0, 0, 0,
|
||||
0xff, 0xd2,
|
||||
];
|
||||
let stack_bottom = stack_top + 0x40 - INJECTION_STACK_SIZE as u32;
|
||||
code[5..9].copy_from_slice(&stack_top.to_le_bytes());
|
||||
code[11..15].copy_from_slice(&entry.to_le_bytes());
|
||||
code[20..24].copy_from_slice(&kernel32_export(b"ExitThread").to_le_bytes());
|
||||
code[32..36].copy_from_slice(&stack_bottom.to_le_bytes());
|
||||
code[39..43].copy_from_slice(&kernel32_export(b"ExitThread").to_le_bytes());
|
||||
|
||||
unsafe { core::ptr::copy_nonoverlapping(code.as_ptr(), trampoline as *mut u8, code.len()) };
|
||||
}
|
||||
|
||||
fn redirect_to_trampoline(arena: u32, thread: u32) {
|
||||
fn redirect_to_trampoline(arena: u32, thread: u32) -> u32 {
|
||||
let mut context = [0u8; CONTEXT_SIZE];
|
||||
let base = context.as_mut_ptr();
|
||||
unsafe {
|
||||
@@ -1065,6 +1091,8 @@ fn redirect_to_trampoline(arena: u32, thread: u32) {
|
||||
base.add(CONTEXT_ESP).cast::<u32>().write_unaligned(top);
|
||||
__VWIN32_Set_Thread_Context(thread, base);
|
||||
}
|
||||
|
||||
stack
|
||||
}
|
||||
|
||||
fn await_flag(address: u32) -> bool {
|
||||
@@ -1128,6 +1156,26 @@ pub fn in_copy() -> bool {
|
||||
core::ptr::eq(primitives(), &crate::win9x_user::USER)
|
||||
}
|
||||
|
||||
pub fn thread_error() -> u32 {
|
||||
if in_copy() { crate::win9x_user::last_error() } else { 0 }
|
||||
}
|
||||
|
||||
pub fn set_thread_error(value: u32) {
|
||||
if in_copy() {
|
||||
crate::win9x_user::set_last_error(value);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file_api() -> &'static crate::gum_windows::FileApi {
|
||||
crate::win9x_user::file_api()
|
||||
}
|
||||
|
||||
pub fn text_api() -> Option<&'static crate::gum_windows::TextApi> {
|
||||
if in_copy() { Some(crate::win9x_user::text_api()) } else { None }
|
||||
}
|
||||
|
||||
pub(crate) use crate::win9x_user::poll_handles;
|
||||
|
||||
fn primitives() -> &'static Primitives {
|
||||
unsafe { ACTIVE }
|
||||
}
|
||||
@@ -1186,7 +1234,7 @@ mod kernel {
|
||||
vwin32_create_ring0_thread(
|
||||
THREAD_STACK_SIZE as u32,
|
||||
0,
|
||||
frida_win9x_thread_thunk as u32,
|
||||
frida_win9x_thread_thunk as *const () as u32,
|
||||
0,
|
||||
) as isize
|
||||
}
|
||||
@@ -1347,6 +1395,7 @@ mod kernel {
|
||||
|
||||
Some(ThreadInfo {
|
||||
id,
|
||||
state: None,
|
||||
cpu_state: with_registers.then(|| super::thread_cpu_state(thread)).flatten(),
|
||||
})
|
||||
}
|
||||
@@ -1461,6 +1510,48 @@ pub(crate) fn enumerate_exports(base: u32, found: &mut dyn FnMut(*const u8, u64)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn enumerate_imports(base: u32,
|
||||
found: &mut dyn FnMut(*const u8, *const u8, u64, u64) -> bool) {
|
||||
let headers = base + read_u32(base + DOS_HEADERS_OFFSET);
|
||||
let directory_rva = read_u32(headers + IMPORT_DIRECTORY_OFFSET);
|
||||
if directory_rva == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut descriptor = base + directory_rva;
|
||||
loop {
|
||||
let library_rva = read_u32(descriptor + IMPORT_NAME_OFFSET);
|
||||
if library_rva == 0 {
|
||||
return;
|
||||
}
|
||||
let library = (base + library_rva) as *const u8;
|
||||
let thunks = base + read_u32(descriptor + IMPORT_THUNKS_OFFSET);
|
||||
let lookups = match read_u32(descriptor + IMPORT_LOOKUPS_OFFSET) {
|
||||
0 => thunks,
|
||||
rva => base + rva,
|
||||
};
|
||||
|
||||
let mut index = 0;
|
||||
loop {
|
||||
let lookup = read_u32(lookups + index * 4);
|
||||
if lookup == 0 {
|
||||
break;
|
||||
}
|
||||
let slot = thunks + index * 4;
|
||||
let imported_by_name = lookup & IMPORT_BY_ORDINAL == 0;
|
||||
if imported_by_name {
|
||||
let name = (base + lookup + IMPORT_HINT_SIZE) as *const u8;
|
||||
if !found(library, name, slot as u64, read_u32(slot) as u64) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
|
||||
descriptor += IMPORT_DESCRIPTOR_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kernel32_export(wanted: &[u8]) -> u32 {
|
||||
let base = unsafe { core::ptr::addr_of!(_KERNEL32_Base).read() };
|
||||
let headers = base + read_u32(base + DOS_HEADERS_OFFSET);
|
||||
@@ -1511,17 +1602,20 @@ fn read_u8(address: u32) -> u8 {
|
||||
}
|
||||
|
||||
const EXPORT_DIRECTORY_OFFSET: u32 = 0x78;
|
||||
const IMPORT_DIRECTORY_OFFSET: u32 = 0x80;
|
||||
const IMPORT_DESCRIPTOR_SIZE: u32 = 20;
|
||||
const IMPORT_LOOKUPS_OFFSET: u32 = 0;
|
||||
const IMPORT_NAME_OFFSET: u32 = 12;
|
||||
const IMPORT_THUNKS_OFFSET: u32 = 16;
|
||||
const IMPORT_BY_ORDINAL: u32 = 0x8000_0000;
|
||||
const IMPORT_HINT_SIZE: u32 = 2;
|
||||
|
||||
pub(crate) const MEM_COMMIT: u32 = 0x0000_1000;
|
||||
pub(crate) const MEM_RESERVE: u32 = 0x0000_2000;
|
||||
pub(crate) const MEM_RELEASE: u32 = 0x0000_8000;
|
||||
pub(crate) const PAGE_EXECUTE_READ: u32 = 0x20;
|
||||
pub(crate) const PAGE_EXECUTE_READWRITE: u32 = 0x40;
|
||||
pub(crate) const INFINITE: u32 = 0xffff_ffff;
|
||||
pub(crate) const USER_THREAD_STACK_SIZE: u32 = 0x10000;
|
||||
|
||||
const INJECTION_ARENA_SIZE: usize = 0x1000;
|
||||
const HANDSHAKE_SIZE: usize = 0x40;
|
||||
pub(crate) const RUNNING_FLAG: u32 = 0x00;
|
||||
pub(crate) const GO_FLAG: u32 = 0x04;
|
||||
pub(crate) const OBSERVED_PID: u32 = 0x08;
|
||||
@@ -1556,9 +1650,7 @@ const PATCH_SIZE: usize = 2;
|
||||
const PE_SIGNATURE_OFFSET: usize = 0x3c;
|
||||
const PE_ENTRY_POINT_OFFSET: usize = 0x28;
|
||||
const FRAME_BUFFER_SIZE: usize = 0x4000;
|
||||
const TEARDOWN_GRACE_US: u64 = 500_000;
|
||||
const TDB_CONTROL_BLOCK: usize = 0x5c;
|
||||
const IDLE_SLEEP_MS: u32 = 1000;
|
||||
pub(crate) const PARKED_SLEEP_MS: u32 = 200;
|
||||
const STUB_OFFSET: u32 = 0x100;
|
||||
const PAYLOAD_OFFSET: u32 = 0x200;
|
||||
@@ -1731,6 +1823,7 @@ pub fn enumerate_threads_of(pid: u32, found: &mut dyn FnMut(ThreadInfo), with_re
|
||||
enumerate_thread_handles_of(pid, &mut |thread, id| {
|
||||
found(ThreadInfo {
|
||||
id,
|
||||
state: None,
|
||||
cpu_state: with_registers.then(|| thread_cpu_state(thread)).flatten(),
|
||||
});
|
||||
});
|
||||
@@ -1782,6 +1875,7 @@ fn enumerate_ring_zero_threads(found: &mut dyn FnMut(ThreadInfo), with_registers
|
||||
while thread != 0 {
|
||||
found(ThreadInfo {
|
||||
id: thread,
|
||||
state: None,
|
||||
cpu_state: with_registers.then(|| thread_cpu_state(thread)).flatten(),
|
||||
});
|
||||
|
||||
@@ -1823,7 +1917,7 @@ pub(crate) unsafe fn cpu_state_of(base: *const u8) -> CpuState {
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn write_cpu_state(base: *mut u8, state: &CpuState) {
|
||||
let mut field = |offset: usize, value: u32| unsafe {
|
||||
let field = |offset: usize, value: u32| unsafe {
|
||||
base.add(offset).cast::<u32>().write_unaligned(value)
|
||||
};
|
||||
|
||||
@@ -1859,6 +1953,10 @@ pub struct ProcessInfo {
|
||||
pub id: u32,
|
||||
pub path: *const u8,
|
||||
pub command_line: *const u8,
|
||||
pub uid: u32,
|
||||
pub user: *const u8,
|
||||
pub ppid: u32,
|
||||
pub started: i64,
|
||||
}
|
||||
|
||||
// Win32 threads carry the process they belong to in VWIN32's per-thread block, so the
|
||||
@@ -1883,6 +1981,10 @@ pub fn enumerate_processes(found: &mut dyn FnMut(ProcessInfo)) {
|
||||
id: process_id(pdb),
|
||||
path: image_path(pdb),
|
||||
command_line: command_line(pdb),
|
||||
uid: 0,
|
||||
user: core::ptr::null(),
|
||||
ppid: 0,
|
||||
started: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1892,11 +1994,6 @@ pub fn enumerate_processes(found: &mut dyn FnMut(ProcessInfo)) {
|
||||
}
|
||||
}
|
||||
|
||||
// KERNEL32 hands out its process database pointer XOR a per-boot value, and so must we.
|
||||
pub(crate) fn process_database(pid: u32) -> u32 {
|
||||
process_id(pid)
|
||||
}
|
||||
|
||||
fn process_id(pdb: u32) -> u32 {
|
||||
let slot = unsafe { core::ptr::addr_of!(_KERNEL32_ProcessIdObfuscator).read() };
|
||||
if slot == 0 {
|
||||
@@ -2247,7 +2344,7 @@ pub fn hear_from_vmm() {
|
||||
ddb[DDB_SDK_VERSION / 4] = SDK_VERSION;
|
||||
ddb[DDB_NAME / 4] = u32::from_le_bytes(*b"FRID");
|
||||
ddb[DDB_NAME / 4 + 1] = u32::from_le_bytes(*b"A ");
|
||||
ddb[DDB_CONTROL_PROC / 4] = frida_win9x_control_thunk as u32;
|
||||
ddb[DDB_CONTROL_PROC / 4] = frida_win9x_control_thunk as *const () as u32;
|
||||
|
||||
vmm_add_ddb(ddb.as_mut_ptr() as u32);
|
||||
}
|
||||
@@ -2290,6 +2387,10 @@ extern "C" fn frida_win9x_on_control(message: u32, thread: u32) {
|
||||
tell_the_copy_of_a_departure(thread);
|
||||
}
|
||||
|
||||
if message == DESTROY_THREAD && thread == unsafe { DEPARTING_THREAD } {
|
||||
unsafe { (&raw mut DEPARTING_THREAD).write_volatile(0) };
|
||||
}
|
||||
|
||||
let told = match message {
|
||||
THREAD_INIT => unsafe { THREAD_APPEARED },
|
||||
DESTROY_THREAD => unsafe { THREAD_VANISHED },
|
||||
@@ -2435,8 +2536,12 @@ extern "C" fn frida_win9x_on_fault(fault: u32, frame: *mut u32) -> u32 {
|
||||
)
|
||||
};
|
||||
if handled == 0 {
|
||||
if fault == PAGE_FAULT && page_is_absent(registers) {
|
||||
return unsafe { FAULT_CHAIN[fault as usize] };
|
||||
}
|
||||
|
||||
report_unhandled_fault(fault, cpu_context.eip);
|
||||
cpu_context.eip = frida_win9x_park as u32;
|
||||
cpu_context.eip = frida_win9x_park as *const () as u32;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
@@ -2471,6 +2576,12 @@ fn recovery_stack(frame: *mut u32) -> u32 {
|
||||
unsafe { frame.add(THUNK_FRAME_ESP).read() }
|
||||
}
|
||||
|
||||
fn page_is_absent(registers: *const u32) -> bool {
|
||||
let error_code = unsafe { registers.byte_add(FAULT_FRAME_ERROR_CODE).read() };
|
||||
|
||||
error_code & PAGE_FAULT_PRESENT == 0
|
||||
}
|
||||
|
||||
fn report_unhandled_fault(fault: u32, eip: u32) {
|
||||
let address = faulting_address();
|
||||
|
||||
@@ -2523,8 +2634,10 @@ const SIMD_FLOATING_POINT: u32 = 19;
|
||||
|
||||
const THUNK_FRAME_EBP: usize = 2;
|
||||
const THUNK_FRAME_ESP: usize = 3;
|
||||
const FAULT_FRAME_ERROR_CODE: usize = 0x20;
|
||||
const FAULT_FRAME_EIP: usize = 0x24;
|
||||
const FAULT_FRAME_CS: usize = 0x28;
|
||||
const PAGE_FAULT_PRESENT: u32 = 1 << 0;
|
||||
const PARK_SLICE_US: u64 = 1_000_000;
|
||||
|
||||
fn faulting_address() -> u32 {
|
||||
@@ -2635,29 +2748,6 @@ fn loop_semaphore() -> u32 {
|
||||
semaphore_in(slot_for_token(crate::glib::wakeup_token()))
|
||||
}
|
||||
|
||||
fn release_slot(slot: usize, token: *const u8) {
|
||||
if SLEEPERS[slot].fetch_sub(1, Ordering::AcqRel) != 1 {
|
||||
return;
|
||||
}
|
||||
if core::ptr::eq(token, crate::glib::wakeup_token()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let _ = OWNERS[slot].compare_exchange(token as usize, 0, Ordering::AcqRel, Ordering::Acquire);
|
||||
}
|
||||
|
||||
fn slot_owned_by(token: *const u8) -> Option<usize> {
|
||||
let start = (token as usize / core::mem::align_of::<usize>()) % NUM_SEMAPHORES;
|
||||
for step in 0..NUM_SEMAPHORES {
|
||||
let slot = (start + step) % NUM_SEMAPHORES;
|
||||
if OWNERS[slot].load(Ordering::Acquire) == token as usize {
|
||||
return Some(slot);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn semaphore_in(slot: usize) -> u32 {
|
||||
let existing = SEMAPHORES[slot].load(Ordering::Acquire);
|
||||
if existing != 0 {
|
||||
@@ -2703,13 +2793,10 @@ unsafe extern "C" {
|
||||
fn frida_win9x_fault_thunk_ud();
|
||||
fn frida_win9x_fault_thunk_gp();
|
||||
fn frida_win9x_fault_thunk_pf();
|
||||
fn frida_win9x_time_out_thunk();
|
||||
fn get_cur_vm_handle() -> u32;
|
||||
fn get_sys_vm_handle() -> u32;
|
||||
fn schedule_global_event(callback: unsafe extern "C" fn()) -> u32;
|
||||
fn frida_win9x_event_thunk();
|
||||
fn frida_win9x_wake_event_thunk();
|
||||
fn get_next_vm_handle(vm: u32) -> u32;
|
||||
fn get_initial_thread_handle(vm: u32) -> u32;
|
||||
fn get_next_thread_handle(thread: u32) -> u32;
|
||||
fn ifsmgr_ring0_file_io(function: u32, ebx: u32, ecx: u32, edx: u32, esi: u32, edi: u32) -> u32;
|
||||
@@ -2720,8 +2807,6 @@ unsafe extern "C" {
|
||||
|
||||
core::arch::global_asm!(
|
||||
r#"
|
||||
.intel_syntax noprefix
|
||||
|
||||
// A position-independent image cannot name its data in an instruction. Thus the code reads the
|
||||
// program counter, from which the offset to the data is known, and adds the offset. The frame
|
||||
// pointer holds the result, because no service reads that register.
|
||||
|
||||
@@ -8,6 +8,7 @@ use alloc::vec::Vec;
|
||||
use core::ffi::c_void;
|
||||
use core::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use crate::gum_windows::{FileApi, TextApi};
|
||||
use crate::kernel::{MemoryRegion, ThreadEntry};
|
||||
use crate::win9x::*;
|
||||
|
||||
@@ -48,9 +49,6 @@ pub extern "C" fn frida_win9x_user_main(arena: u32) {
|
||||
|
||||
stop_hearing_about_faults();
|
||||
unsafe { ((arena + MAIN_STOPPED) as *mut u32).write_volatile(1) };
|
||||
loop {
|
||||
unsafe { sleep(PARKED_SLEEP_MS) };
|
||||
}
|
||||
}
|
||||
|
||||
// The group that the user-mode half runs on. The order is the order in Primitives.
|
||||
@@ -105,7 +103,7 @@ fn hear_about_faults() {
|
||||
let install: unsafe extern "stdcall" fn(u32) -> u32 =
|
||||
unsafe { core::mem::transmute(user_api().set_unhandled_exception_filter as usize) };
|
||||
|
||||
unsafe { PREVIOUS_FILTER = install(on_fault as u32) };
|
||||
unsafe { PREVIOUS_FILTER = install(on_fault as *const () as u32) };
|
||||
}
|
||||
|
||||
fn stop_hearing_about_faults() {
|
||||
@@ -166,6 +164,97 @@ fn copy_has_work() -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
static LOOP_WAKE_EVENT: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
|
||||
|
||||
fn loop_wake_event() -> u32 {
|
||||
let existing = LOOP_WAKE_EVENT.load(Ordering::Acquire);
|
||||
if existing != 0 {
|
||||
return existing;
|
||||
}
|
||||
|
||||
let create_event: unsafe extern "stdcall" fn(u32, u32, u32, u32) -> u32 =
|
||||
unsafe { core::mem::transmute(user_api().create_event as usize) };
|
||||
let created = unsafe { create_event(0, 0, 0, 0) };
|
||||
|
||||
match LOOP_WAKE_EVENT.compare_exchange(0, created, Ordering::AcqRel, Ordering::Acquire) {
|
||||
Ok(_) => created,
|
||||
Err(raced) => {
|
||||
let close_handle: unsafe extern "stdcall" fn(u32) -> u32 =
|
||||
unsafe { core::mem::transmute(user_api().close_handle as usize) };
|
||||
unsafe { close_handle(created) };
|
||||
raced
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn poke_loop_wakeup() {
|
||||
let set_event: unsafe extern "stdcall" fn(u32) -> u32 =
|
||||
unsafe { core::mem::transmute(user_api().set_event as usize) };
|
||||
unsafe { set_event(loop_wake_event()) };
|
||||
}
|
||||
|
||||
pub(crate) unsafe extern "C" fn poll_handles(ufds: *mut crate::bindings::GPollFD, nfds: u32,
|
||||
timeout: i32) -> i32 {
|
||||
const MAX_HANDLES: usize = 16;
|
||||
let fds = unsafe { core::slice::from_raw_parts_mut(ufds, nfds as usize) };
|
||||
|
||||
let wake = loop_wake_event();
|
||||
|
||||
let mut handles = [0u32; MAX_HANDLES];
|
||||
let mut origin = [usize::MAX; MAX_HANDLES];
|
||||
handles[0] = wake;
|
||||
let mut count = 1usize;
|
||||
let mut ready = 0i32;
|
||||
|
||||
for (index, fd) in fds.iter_mut().enumerate() {
|
||||
fd.revents = 0;
|
||||
|
||||
if fd.fd == G_WAIT_WAKEUP_HANDLE {
|
||||
if !fd.user_data.is_null() {
|
||||
if unsafe { (fd.user_data as *const i32).read_volatile() } != 0 {
|
||||
fd.revents = POLL_IN;
|
||||
ready += 1;
|
||||
}
|
||||
let token = (fd.user_data as usize + GWAKEUP_TOKEN) as *mut *mut c_void;
|
||||
unsafe { token.write(fd.user_data) };
|
||||
}
|
||||
} else if fd.fd != -1 && fd.fd as u32 != wake && count < MAX_HANDLES {
|
||||
handles[count] = fd.fd as u32;
|
||||
origin[count] = index;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if ready == 0 {
|
||||
let wait_for_multiple_objects_ex: unsafe extern "stdcall" fn(u32, *const u32, u32, u32, u32) -> u32 =
|
||||
unsafe { core::mem::transmute(user_api().wait_for_multiple_objects_ex as usize) };
|
||||
let timeout_ms = if timeout < 0 { INFINITE } else { timeout as u32 };
|
||||
let status = unsafe {
|
||||
wait_for_multiple_objects_ex(count as u32, handles.as_ptr(), 0, timeout_ms, 1)
|
||||
};
|
||||
if (status as usize) < count {
|
||||
let slot = origin[status as usize];
|
||||
if slot != usize::MAX {
|
||||
fds[slot].revents = POLL_IN;
|
||||
ready += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for fd in fds.iter() {
|
||||
if fd.fd == G_WAIT_WAKEUP_HANDLE && !fd.user_data.is_null() {
|
||||
let token = (fd.user_data as usize + GWAKEUP_TOKEN) as *mut *mut c_void;
|
||||
unsafe { token.write(core::ptr::null_mut()) };
|
||||
}
|
||||
}
|
||||
|
||||
ready
|
||||
}
|
||||
|
||||
const G_WAIT_WAKEUP_HANDLE: i32 = -43;
|
||||
const GWAKEUP_TOKEN: usize = 4;
|
||||
const POLL_IN: u16 = 1;
|
||||
|
||||
fn serve_the_copy() {
|
||||
let arena = unsafe { ARENA };
|
||||
|
||||
@@ -224,6 +313,7 @@ unsafe extern "C" fn user_worker(parameter: *mut c_void, _wait_result: i32) {
|
||||
crate::gum_windows::watch_the_loader();
|
||||
crate::glib::own_the_loop();
|
||||
crate::watch_for_work(context, copy_has_work, serve_the_copy);
|
||||
crate::watch_a_descriptor(context, loop_wake_event() as i32, poll_handles);
|
||||
|
||||
while unsafe { ((arena + STOP_REQUEST) as *const u32).read_volatile() } == 0 {
|
||||
unsafe { crate::dispatch_pending_work(context) };
|
||||
@@ -271,6 +361,7 @@ fn find_thread(id: u32, with_registers: bool) -> Option<crate::kernel::ThreadInf
|
||||
|
||||
Some(crate::kernel::ThreadInfo {
|
||||
id,
|
||||
state: None,
|
||||
cpu_state: with_registers.then(|| crate::win9x::thread_cpu_state(thread)).flatten(),
|
||||
})
|
||||
}
|
||||
@@ -330,19 +421,11 @@ const GUM_PAGE_WRITE: u32 = 0x2;
|
||||
const GUM_PAGE_EXECUTE: u32 = 0x4;
|
||||
|
||||
pub unsafe extern "stdcall" fn on_module_load(name: *const u8) -> u32 {
|
||||
unsafe {
|
||||
let n = (ARENA + 0xb0) as *mut u32;
|
||||
n.write_volatile(n.read_volatile() + 1);
|
||||
}
|
||||
let original: extern "stdcall" fn(*const u8) -> u32 =
|
||||
unsafe { core::mem::transmute(crate::gum_windows::loader_load()) };
|
||||
|
||||
let handle = original(name);
|
||||
note_module(handle, name);
|
||||
unsafe {
|
||||
let n = (ARENA + 0xb4) as *mut u32;
|
||||
n.write_volatile(n.read_volatile() + 1);
|
||||
}
|
||||
|
||||
handle
|
||||
}
|
||||
@@ -512,16 +595,21 @@ fn resolve_user_api() {
|
||||
resume_thread: kernel32_export(b"ResumeThread"),
|
||||
create_event: kernel32_export(b"CreateEventA"),
|
||||
set_event: kernel32_export(b"SetEvent"),
|
||||
wait_for_single_object: kernel32_export(b"WaitForSingleObject"),
|
||||
wait_for_single_object_ex: kernel32_export(b"WaitForSingleObjectEx"),
|
||||
exit_thread: kernel32_export(b"ExitThread"),
|
||||
wait_for_multiple_objects_ex: kernel32_export(b"WaitForMultipleObjectsEx"),
|
||||
close_handle: kernel32_export(b"CloseHandle"),
|
||||
set_file_pointer: kernel32_export(b"SetFilePointer"),
|
||||
create_file: kernel32_export(b"CreateFileA"),
|
||||
read_file: kernel32_export(b"ReadFile"),
|
||||
write_file: kernel32_export(b"WriteFile"),
|
||||
find_first_file: kernel32_export(b"FindFirstFileA"),
|
||||
find_next_file: kernel32_export(b"FindNextFileA"),
|
||||
find_close: kernel32_export(b"FindClose"),
|
||||
get_last_error: kernel32_export(b"GetLastError"),
|
||||
set_last_error: kernel32_export(b"SetLastError"),
|
||||
format_message: kernel32_export(b"FormatMessageA"),
|
||||
multi_byte_to_wide_char: kernel32_export(b"MultiByteToWideChar"),
|
||||
wide_char_to_multi_byte: kernel32_export(b"WideCharToMultiByte"),
|
||||
set_unhandled_exception_filter: kernel32_export(b"SetUnhandledExceptionFilter"),
|
||||
tls_alloc: kernel32_export(b"TlsAlloc"),
|
||||
tls_get_value: kernel32_export(b"TlsGetValue"),
|
||||
@@ -534,6 +622,50 @@ fn user_api() -> &'static UserApi {
|
||||
unsafe { &*core::ptr::addr_of!(USER_API) }
|
||||
}
|
||||
|
||||
pub fn last_error() -> u32 {
|
||||
let get_last_error: unsafe extern "stdcall" fn() -> u32 =
|
||||
unsafe { core::mem::transmute(user_api().get_last_error as usize) };
|
||||
unsafe { get_last_error() }
|
||||
}
|
||||
|
||||
pub fn set_last_error(value: u32) {
|
||||
let set_last_error: unsafe extern "stdcall" fn(u32) =
|
||||
unsafe { core::mem::transmute(user_api().set_last_error as usize) };
|
||||
unsafe { set_last_error(value) }
|
||||
}
|
||||
|
||||
pub fn file_api() -> &'static FileApi {
|
||||
unsafe {
|
||||
if (*core::ptr::addr_of!(FILE_API)).is_none() {
|
||||
let api = user_api();
|
||||
FILE_API = Some(FileApi {
|
||||
read_file: core::mem::transmute(api.read_file as usize),
|
||||
write_file: core::mem::transmute(api.write_file as usize),
|
||||
close_handle: core::mem::transmute(api.close_handle as usize),
|
||||
format_message: core::mem::transmute(api.format_message as usize),
|
||||
});
|
||||
}
|
||||
(*core::ptr::addr_of!(FILE_API)).as_ref().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
static mut FILE_API: Option<FileApi> = None;
|
||||
|
||||
pub fn text_api() -> &'static TextApi {
|
||||
unsafe {
|
||||
if (*core::ptr::addr_of!(TEXT_API)).is_none() {
|
||||
let api = user_api();
|
||||
TEXT_API = Some(TextApi {
|
||||
multi_byte_to_wide_char: core::mem::transmute(api.multi_byte_to_wide_char as usize),
|
||||
wide_char_to_multi_byte: core::mem::transmute(api.wide_char_to_multi_byte as usize),
|
||||
});
|
||||
}
|
||||
(*core::ptr::addr_of!(TEXT_API)).as_ref().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
static mut TEXT_API: Option<TextApi> = None;
|
||||
|
||||
struct UserApi {
|
||||
sleep: u32,
|
||||
get_tick_count: u32,
|
||||
@@ -553,16 +685,21 @@ struct UserApi {
|
||||
resume_thread: u32,
|
||||
create_event: u32,
|
||||
set_event: u32,
|
||||
wait_for_single_object: u32,
|
||||
wait_for_single_object_ex: u32,
|
||||
exit_thread: u32,
|
||||
wait_for_multiple_objects_ex: u32,
|
||||
close_handle: u32,
|
||||
set_file_pointer: u32,
|
||||
create_file: u32,
|
||||
read_file: u32,
|
||||
write_file: u32,
|
||||
find_first_file: u32,
|
||||
find_next_file: u32,
|
||||
find_close: u32,
|
||||
get_last_error: u32,
|
||||
set_last_error: u32,
|
||||
format_message: u32,
|
||||
multi_byte_to_wide_char: u32,
|
||||
wide_char_to_multi_byte: u32,
|
||||
set_unhandled_exception_filter: u32,
|
||||
tls_alloc: u32,
|
||||
tls_get_value: u32,
|
||||
@@ -588,16 +725,21 @@ static mut USER_API: UserApi = UserApi {
|
||||
resume_thread: 0,
|
||||
create_event: 0,
|
||||
set_event: 0,
|
||||
wait_for_single_object: 0,
|
||||
wait_for_single_object_ex: 0,
|
||||
exit_thread: 0,
|
||||
wait_for_multiple_objects_ex: 0,
|
||||
close_handle: 0,
|
||||
set_file_pointer: 0,
|
||||
create_file: 0,
|
||||
read_file: 0,
|
||||
write_file: 0,
|
||||
find_first_file: 0,
|
||||
find_next_file: 0,
|
||||
find_close: 0,
|
||||
get_last_error: 0,
|
||||
set_last_error: 0,
|
||||
format_message: 0,
|
||||
multi_byte_to_wide_char: 0,
|
||||
wide_char_to_multi_byte: 0,
|
||||
set_unhandled_exception_filter: 0,
|
||||
tls_alloc: 0,
|
||||
tls_get_value: 0,
|
||||
@@ -722,7 +864,7 @@ pub fn spawn_process(command_line: &str) -> u32 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
unsafe { held().insert(pid, HeldProcess { process, thread }) };
|
||||
held().insert(pid, HeldProcess { process, thread });
|
||||
|
||||
pid
|
||||
}
|
||||
@@ -772,7 +914,7 @@ unsafe extern "stdcall" fn on_create_process(application: u32, command_line: *co
|
||||
let arena = crate::routed_arena() as u32;
|
||||
((arena + HOLD_RESULT) as *mut u32).write_volatile(if held_ok { 1 } else { 2 });
|
||||
}
|
||||
unsafe { held().insert(pid, HeldProcess { process, thread }) };
|
||||
held().insert(pid, HeldProcess { process, thread });
|
||||
|
||||
crate::tell_the_host_of_a_spawn(pid, command_line);
|
||||
|
||||
@@ -888,8 +1030,6 @@ fn in_shared_library(address: u32) -> bool {
|
||||
}
|
||||
|
||||
fn ask_for_a_guard(address: u32, bytes: &[u8]) {
|
||||
let sleep: unsafe extern "stdcall" fn(u32) =
|
||||
unsafe { core::mem::transmute(user_api().sleep as usize) };
|
||||
let arena = crate::routed_arena() as u32;
|
||||
|
||||
if bytes.len() > PATCH_CODE_MAX {
|
||||
@@ -944,8 +1084,6 @@ fn give_the_slot_back() {
|
||||
static ASKING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
fn patch(pid: u32, address: u32, code: u32) -> Option<(u32, u32)> {
|
||||
let sleep: unsafe extern "stdcall" fn(u32) =
|
||||
unsafe { core::mem::transmute(user_api().sleep as usize) };
|
||||
let arena = crate::routed_arena() as u32;
|
||||
|
||||
take_the_slot();
|
||||
@@ -1012,7 +1150,7 @@ fn resume_thread(thread: u32) {
|
||||
}
|
||||
|
||||
pub fn resume_process(pid: u32) -> bool {
|
||||
let Some(held) = (unsafe { held().remove(&pid) }) else {
|
||||
let Some(held) = held().remove(&pid) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -1042,12 +1180,9 @@ static mut HELD_PROCESSES: BTreeMap<u32, HeldProcess> = BTreeMap::new();
|
||||
const CREATE_SUSPENDED: u32 = 0x4;
|
||||
const CONTEXT_WORDS: usize = 179;
|
||||
const CONTEXT_CONTROL: u32 = 0x0001_0001;
|
||||
const CONTEXT_INTEGER: u32 = 0x0001_0002;
|
||||
const CONTEXT_EAX: usize = 0xb0;
|
||||
const CONTEXT_EIP: usize = 0xb8;
|
||||
const CONTEXT_ESP: usize = 0xc4;
|
||||
const HOLD_INSTRUCTION: u32 = 0xfeeb;
|
||||
const PATCH_ATTEMPTS: u32 = 5000;
|
||||
const HOLD_ATTEMPTS: u32 = 5000;
|
||||
const HOLD_SLICE_MS: u32 = 1;
|
||||
const STARTUP_INFO_WORDS: usize = 17;
|
||||
@@ -1094,8 +1229,9 @@ pub fn spawn_thread(entry: ThreadEntry, parameter: *mut c_void) -> isize {
|
||||
unsafe { start.write(UserThreadStart { entry, parameter }) };
|
||||
|
||||
let thread = unsafe {
|
||||
create_thread(0, USER_THREAD_STACK_SIZE, frida_win9x_user_thread as usize as u32,
|
||||
start as *mut c_void, 0, core::ptr::null_mut())
|
||||
create_thread(0, USER_THREAD_STACK_SIZE,
|
||||
frida_win9x_user_thread as *const () as usize as u32, start as *mut c_void, 0,
|
||||
core::ptr::null_mut())
|
||||
};
|
||||
|
||||
let close_handle: unsafe extern "stdcall" fn(u32) -> u32 =
|
||||
|
||||
+126
-139
@@ -21,7 +21,6 @@ pub use crate::winnt_user::{
|
||||
ThreadEntryPoints,
|
||||
};
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
#[cfg(target_arch = "x86")]
|
||||
type ThreadChangeRoutine = unsafe extern "stdcall" fn(usize, usize, u8);
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
@@ -29,30 +28,7 @@ type ThreadChangeRoutine = unsafe extern "win64" fn(usize, usize, u8);
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
type ThreadChangeRoutine = unsafe extern "C" fn(usize, usize, u8);
|
||||
|
||||
macro_rules! windows_fn {
|
||||
($($argument:ty),* $(,)?) => { unsafe extern "stdcall" fn($($argument),*) };
|
||||
($($argument:ty),* $(,)? => $result:ty) => {
|
||||
unsafe extern "stdcall" fn($($argument),*) -> $result
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
macro_rules! windows_fn {
|
||||
($($argument:ty),* $(,)?) => { unsafe extern "win64" fn($($argument),*) };
|
||||
($($argument:ty),* $(,)? => $result:ty) => {
|
||||
unsafe extern "win64" fn($($argument),*) -> $result
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
macro_rules! windows_fn {
|
||||
($($argument:ty),* $(,)?) => { unsafe extern "C" fn($($argument),*) };
|
||||
($($argument:ty),* $(,)? => $result:ty) => {
|
||||
unsafe extern "C" fn($($argument),*) -> $result
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use windows_fn;
|
||||
pub(crate) use crate::gum_windows::windows_fn;
|
||||
|
||||
pub const MODULE_DIRECTORY: &str = "/WINDOWS/system32/";
|
||||
|
||||
@@ -94,7 +70,6 @@ pub fn panic(msg: &str) -> ! {
|
||||
unsafe {
|
||||
(_KeBugCheckEx)(MANUALLY_INITIATED_CRASH, msg.as_ptr() as usize, 0, 0, 0);
|
||||
}
|
||||
loop {}
|
||||
}
|
||||
|
||||
const MANUALLY_INITIATED_CRASH: u32 = 0xe2;
|
||||
@@ -304,10 +279,6 @@ static mut SHAREABLE_WAKE_EVENT: *mut c_void = core::ptr::null_mut();
|
||||
static mut SHAREABLE_TOKEN: *const u8 = core::ptr::null();
|
||||
|
||||
// The kernel has no futex. Thus each token uses an event, which the code makes on first use.
|
||||
fn event_for(token: *const u8) -> *mut c_void {
|
||||
event_in(slot_for_token(token))
|
||||
}
|
||||
|
||||
fn event_in(slot: usize) -> *mut c_void {
|
||||
loop {
|
||||
let existing = EVENTS[slot].load(Ordering::Acquire);
|
||||
@@ -1046,7 +1017,7 @@ pub fn install_fault_reporter() {
|
||||
let (base, size) = crate::own_code();
|
||||
let entry = (shadow + SYNCHRONOUS_ENTRY_OFFSET) as *mut u8;
|
||||
FAULT_CONTROL = FaultControl {
|
||||
thunk: frida_winnt_fault_thunk as usize as u64,
|
||||
thunk: frida_winnt_fault_thunk as *const () as usize as u64,
|
||||
chain: entry.byte_add(chain_offset()) as u64,
|
||||
base: base as u64,
|
||||
size: size as u64,
|
||||
@@ -1198,9 +1169,9 @@ fn pool_anchor() -> Option<usize> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const POOL_WINDOW: usize = 1 << 32;
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const POOL_REACH: usize = 1 << 29;
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
||||
const POOL_GRANULARITY: usize = 16;
|
||||
@@ -1388,21 +1359,6 @@ const BRANCH_LINK_MASK: u32 = 0xfc00_0000;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const BRANCH_LINK: u32 = 0x9400_0000;
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const SET_VBAR: u32 = 0xd518_c000;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const SET_VBAR_MASK: u32 = 0xffff_ffe0;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const ADRP_MASK: u32 = 0x9f00_001f;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const ADRP: u32 = 0x9000_0000;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const ADD_MASK: u32 = 0xffc0_03ff;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const ADD: u32 = 0x9100_0000;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const LOAD: u32 = 0xf940_0000;
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn vectors_in_use() -> *mut u64 {
|
||||
let Some(image) = image_containing(current_vectors()) else {
|
||||
@@ -1444,7 +1400,7 @@ fn image_size(image: usize) -> Option<usize> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn image_containing(address: usize) -> Option<usize> {
|
||||
unsafe {
|
||||
(*core::ptr::addr_of!(crate::MODULE_INFO))
|
||||
@@ -1581,8 +1537,6 @@ struct FaultControl {
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
static mut FAULT_CONTROL: FaultControl =
|
||||
FaultControl { thunk: 0, chain: 0, base: 0, size: 0 };
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
static mut ORIGINAL_ENTRY: u32 = 0;
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
unsafe extern "C" {
|
||||
@@ -1661,8 +1615,6 @@ macro_rules! read_exception_register {
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
use read_exception_register;
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const FRAME_BYTES: usize = 288;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const RESUME_STACK_SLOT: usize = 31;
|
||||
|
||||
@@ -1695,6 +1647,7 @@ const SYNDROME_BREAKPOINT: u32 = 0x30;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const SYNDROME_SOFTWARE_STEP: u32 = 0x32;
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
fn descriptor_table_base() -> usize {
|
||||
let mut descriptor = [0u8; DESCRIPTOR_SIZE];
|
||||
unsafe {
|
||||
@@ -1709,6 +1662,7 @@ const GATE_SIZE: usize = 8;
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const GATE_SIZE: usize = 16;
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const DESCRIPTOR_SIZE: usize = 2 + core::mem::size_of::<usize>();
|
||||
|
||||
// Report only the faults from our own code. Send the other faults, primarily the paging
|
||||
@@ -1717,6 +1671,7 @@ const DESCRIPTOR_SIZE: usize = 2 + core::mem::size_of::<usize>();
|
||||
// A long-mode frame always contains the stack pointer. Thus write the values from Gum into
|
||||
// the frame.
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
fn handle(fault: u32, pc: u64, cpu_context: &mut crate::bindings::GumCpuContext) -> bool {
|
||||
handle_with(fault, pc, faulting_address(), cpu_context)
|
||||
}
|
||||
@@ -1735,11 +1690,6 @@ fn handle_with(fault: u32, pc: u64, accessed: usize,
|
||||
handled != 0
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
const PUSHED_REGISTERS: usize = 8;
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const PUSHED_REGISTERS: usize = 16;
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
fn exception_type_for(fault: u32) -> crate::bindings::GumExceptionType {
|
||||
use crate::bindings::*;
|
||||
@@ -1751,17 +1701,10 @@ fn exception_type_for(fault: u32) -> crate::bindings::GumExceptionType {
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
fn faulting_address() -> usize {
|
||||
let address: usize;
|
||||
unsafe {
|
||||
core::arch::asm!("mov {0}, cr2", out(reg) address,
|
||||
options(nomem, nostack, preserves_flags));
|
||||
}
|
||||
address
|
||||
}
|
||||
|
||||
const INVALID_OPCODE: u32 = 6;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const GENERAL_PROTECTION: u32 = 13;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PAGE_FAULT: u32 = 14;
|
||||
|
||||
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
|
||||
@@ -1778,7 +1721,7 @@ pub fn modify_thread(id: u32, change: &mut dyn FnMut(&mut CpuState)) -> bool {
|
||||
|
||||
fn enumerate_ring_zero_threads(found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
|
||||
let Some(layout) = thread_layout() else {
|
||||
found(ThreadInfo { id: current_thread_id() as u32, cpu_state: None });
|
||||
found(ThreadInfo { id: current_thread_id() as u32, state: None, cpu_state: None });
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -1787,6 +1730,7 @@ fn enumerate_ring_zero_threads(found: &mut dyn FnMut(ThreadInfo), with_registers
|
||||
walk_threads_of(ours, &mut |thread| unsafe {
|
||||
found(ThreadInfo {
|
||||
id: (_PsGetThreadId)(thread),
|
||||
state: None,
|
||||
cpu_state: with_registers.then(|| capture(thread)).flatten(),
|
||||
});
|
||||
});
|
||||
@@ -2022,7 +1966,7 @@ pub(crate) unsafe fn cpu_state_of(base: *const u8) -> CpuState {
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
pub(crate) unsafe fn write_cpu_state(base: *mut u8, state: &CpuState) {
|
||||
let mut field = |offset: usize, value: u32| unsafe {
|
||||
let field = |offset: usize, value: u32| unsafe {
|
||||
base.add(offset).cast::<u32>().write_unaligned(value)
|
||||
};
|
||||
|
||||
@@ -2064,7 +2008,7 @@ pub(crate) unsafe fn cpu_state_of(base: *const u8) -> CpuState {
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub(crate) unsafe fn write_cpu_state(base: *mut u8, state: &CpuState) {
|
||||
let mut field = |offset: usize, value: u64| unsafe {
|
||||
let field = |offset: usize, value: u64| unsafe {
|
||||
base.add(offset).cast::<u64>().write_unaligned(value)
|
||||
};
|
||||
|
||||
@@ -2108,7 +2052,7 @@ pub(crate) unsafe fn cpu_state_of(base: *const u8) -> CpuState {
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub(crate) unsafe fn write_cpu_state(base: *mut u8, state: &CpuState) {
|
||||
let mut field = |offset: usize, value: u64| unsafe {
|
||||
let field = |offset: usize, value: u64| unsafe {
|
||||
base.add(offset).cast::<u64>().write_unaligned(value)
|
||||
};
|
||||
|
||||
@@ -2162,6 +2106,10 @@ pub struct ProcessInfo {
|
||||
pub path: *const u8,
|
||||
pub command_line: *const u8,
|
||||
pub handle: *mut c_void,
|
||||
pub uid: u32,
|
||||
pub user: *const u8,
|
||||
pub ppid: u32,
|
||||
pub started: i64,
|
||||
}
|
||||
|
||||
// Find only the head of the list. Read the other data with the accessors that the kernel
|
||||
@@ -2189,6 +2137,10 @@ pub fn enumerate_processes(found: &mut dyn FnMut(ProcessInfo)) {
|
||||
path,
|
||||
command_line,
|
||||
handle: process,
|
||||
uid: 0,
|
||||
user: core::ptr::null(),
|
||||
ppid: 0,
|
||||
started: 0,
|
||||
});
|
||||
}
|
||||
entry = unsafe { (entry as *const usize).read_volatile() };
|
||||
@@ -2359,33 +2311,6 @@ unsafe fn read_string_from(process: *mut c_void, address: usize, out: &mut [u8])
|
||||
|
||||
static mut WIDE: [u8; MAX_COMMAND_LINE_SIZE] = [0; MAX_COMMAND_LINE_SIZE];
|
||||
|
||||
// This read can cause a fault if the page is not in memory. At PASSIVE_LEVEL the pager gets
|
||||
// the page again.
|
||||
|
||||
unsafe fn read_user_string(address: usize, out: &mut [u8]) {
|
||||
unsafe {
|
||||
let Some(length) = try_read_pointer(address).map(|word| word as u16 as usize) else {
|
||||
return;
|
||||
};
|
||||
let Some(buffer) = try_read_pointer(address + UNICODE_STRING_BUFFER_OFFSET) else {
|
||||
return;
|
||||
};
|
||||
if buffer == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let limit = out.len() - 1;
|
||||
let mut written = 0;
|
||||
for i in 0..length.min(limit) / 2 {
|
||||
let Some(word) = try_read_pointer(buffer + i * 2) else {
|
||||
break;
|
||||
};
|
||||
written += encode_utf8(word as u16, &mut out[written..limit]);
|
||||
}
|
||||
out[written] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_utf8(c: u16, out: &mut [u8]) -> usize {
|
||||
if c < 0x80 && !out.is_empty() {
|
||||
out[0] = c as u8;
|
||||
@@ -2528,7 +2453,6 @@ pub fn place_agent_in_process(pid: u32) -> bool {
|
||||
wake,
|
||||
started: false,
|
||||
text: placed.seen_by_process,
|
||||
size: own.size as u64,
|
||||
stack: 0,
|
||||
step: 0,
|
||||
carrier: core::ptr::null_mut(),
|
||||
@@ -2548,7 +2472,6 @@ pub struct Placement {
|
||||
pub arena_mdl: *mut c_void,
|
||||
}
|
||||
|
||||
const MAX_PLACEMENT_TRIES: usize = 8;
|
||||
const USER_MODE: u8 = 1;
|
||||
const MM_CACHED: u32 = 1;
|
||||
const NORMAL_PAGE_PRIORITY: u32 = 16;
|
||||
@@ -2664,17 +2587,16 @@ pub fn stop_copies() {
|
||||
|
||||
static mut TEARDOWN_TOKEN: u8 = 0;
|
||||
|
||||
const TEARDOWN_GRACE_US: u64 = 500_000;
|
||||
|
||||
pub fn start_agent_in_process(pid: u32) -> u32 {
|
||||
let Some(target) = (unsafe { targets().get(&pid) }) else {
|
||||
return 0;
|
||||
};
|
||||
let (arena, seen) = (target.arena, target.seen);
|
||||
let own = unsafe { core::ptr::addr_of!(crate::OWN_RANGE).read() }.base_address as usize;
|
||||
let bootstrap = target.text + (crate::winnt_user::frida_winnt_user_bootstrap as usize
|
||||
- own) as u64;
|
||||
let entry = target.text + (crate::winnt_user::frida_winnt_user_main as usize - own) as u64;
|
||||
let bootstrap = target.text
|
||||
+ (crate::winnt_user::frida_winnt_user_bootstrap as *const () as usize - own) as u64;
|
||||
let entry = target.text
|
||||
+ (crate::winnt_user::frida_winnt_user_main as *const () as usize - own) as u64;
|
||||
|
||||
if !target.started {
|
||||
let mut process: *mut c_void = core::ptr::null_mut();
|
||||
@@ -2761,16 +2683,6 @@ fn carry_image_across(process: *mut c_void, whole: u64, private_offset: usize, s
|
||||
}
|
||||
}
|
||||
|
||||
fn put_a_copy_in_the_session_server(pid: u32) {
|
||||
let server = session_server_pid();
|
||||
if server == 0 || server == pid || arena_for_pid(server).is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
place_agent_in_process(server);
|
||||
start_agent_in_process(server);
|
||||
}
|
||||
|
||||
fn introduce_to_session_server(pid: u32) {
|
||||
if unsafe { targets().get(&pid).map(|t| t.introduced) } != Some(false) {
|
||||
return;
|
||||
@@ -2975,7 +2887,7 @@ fn synthesize_zw_stub(index: u32) -> usize {
|
||||
// The image is further from pool memory than a relative jump can reach here, thus the jump to
|
||||
// the dispatcher is an indirect one.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
unsafe fn emit_zw_stub(template: *const u8, stub: *mut u8, index: u32,
|
||||
unsafe fn emit_zw_stub(template: *const u8, _stub: *mut u8, index: u32,
|
||||
put: &mut dyn FnMut(&[u8])) {
|
||||
unsafe {
|
||||
let linkage = template.add(ZW_STUB_LEA_NEXT) as u64
|
||||
@@ -3474,9 +3386,9 @@ fn allocate_in_process(process_handle: *mut c_void, size: usize, protection: u32
|
||||
// This is a system thread, but it uses the address space of the target. The code after the
|
||||
// descent runs in ring 3.
|
||||
const STACK_SIZE: usize = 256 * 1024;
|
||||
const BLOCK_SIZE: usize = 4096;
|
||||
const PROCESS_ALL_ACCESS: u32 = 0x1f_0fff;
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const INITIAL_EFLAGS: u64 = 0x200;
|
||||
|
||||
// The primitives that differ between the two halves. The kernel half runs on KERNEL, and the
|
||||
@@ -3511,6 +3423,26 @@ pub fn in_copy() -> bool {
|
||||
core::ptr::eq(primitives(), &crate::winnt_user::USER)
|
||||
}
|
||||
|
||||
pub fn thread_error() -> u32 {
|
||||
if in_copy() { crate::winnt_user::last_error() } else { 0 }
|
||||
}
|
||||
|
||||
pub fn set_thread_error(value: u32) {
|
||||
if in_copy() {
|
||||
crate::winnt_user::set_last_error(value);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file_api() -> &'static crate::gum_windows::FileApi {
|
||||
crate::winnt_user::file_api()
|
||||
}
|
||||
|
||||
pub fn text_api() -> Option<&'static crate::gum_windows::TextApi> {
|
||||
if in_copy() { Some(crate::winnt_user::text_api()) } else { None }
|
||||
}
|
||||
|
||||
pub(crate) use crate::winnt_user::poll_handles;
|
||||
|
||||
fn primitives() -> &'static Primitives {
|
||||
unsafe { ACTIVE }
|
||||
}
|
||||
@@ -3589,6 +3521,7 @@ mod kernel {
|
||||
|
||||
Some(ThreadInfo {
|
||||
id,
|
||||
state: None,
|
||||
cpu_state: with_registers.then(|| unsafe { super::capture(thread) }).flatten(),
|
||||
})
|
||||
}
|
||||
@@ -3812,19 +3745,83 @@ pub(crate) fn enumerate_exports(base: usize, found: &mut dyn FnMut(*const u8, u6
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn enumerate_imports(base: usize,
|
||||
found: &mut dyn FnMut(*const u8, *const u8, u64, u64) -> bool) {
|
||||
unsafe {
|
||||
let directories = data_directories(base);
|
||||
let directory_rva = read_u32(directories + IMPORT_DIRECTORY_INDEX * 8) as usize;
|
||||
if directory_rva == 0 {
|
||||
return;
|
||||
}
|
||||
let wide = is_pe32_plus(base);
|
||||
let thunk_size = if wide { 8 } else { 4 };
|
||||
let by_ordinal: u64 = if wide { 1 << 63 } else { 1 << 31 };
|
||||
|
||||
let mut descriptor = base + directory_rva;
|
||||
loop {
|
||||
let library_rva = read_u32(descriptor + IMPORT_NAME_OFFSET) as usize;
|
||||
if library_rva == 0 {
|
||||
return;
|
||||
}
|
||||
let library = (base + library_rva) as *const u8;
|
||||
let thunks = base + read_u32(descriptor + IMPORT_THUNKS_OFFSET) as usize;
|
||||
let lookups = match read_u32(descriptor + IMPORT_LOOKUPS_OFFSET) as usize {
|
||||
0 => thunks,
|
||||
rva => base + rva,
|
||||
};
|
||||
|
||||
let mut index = 0;
|
||||
loop {
|
||||
let lookup = read_thunk(lookups + index * thunk_size, wide);
|
||||
if lookup == 0 {
|
||||
break;
|
||||
}
|
||||
let slot = thunks + index * thunk_size;
|
||||
if lookup & by_ordinal == 0 {
|
||||
let name = (base + lookup as usize + IMPORT_HINT_SIZE) as *const u8;
|
||||
if !found(library, name, slot as u64, read_thunk(slot, wide)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
|
||||
descriptor += IMPORT_DESCRIPTOR_SIZE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn read_thunk(address: usize, wide: bool) -> u64 {
|
||||
unsafe {
|
||||
if wide {
|
||||
(address as *const u64).read()
|
||||
} else {
|
||||
read_u32(address) as u64
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn export_directory(base: usize) -> usize {
|
||||
unsafe { base + read_u32(data_directories(base)) as usize }
|
||||
}
|
||||
|
||||
unsafe fn is_pe32_plus(base: usize) -> bool {
|
||||
unsafe {
|
||||
let headers = base + read_u32(base + PE_HEADERS_OFFSET) as usize;
|
||||
let magic = (headers + OPTIONAL_HEADER_OFFSET) as *const u16;
|
||||
let directories = headers
|
||||
((headers + OPTIONAL_HEADER_OFFSET) as *const u16).read() == PE32_PLUS_MAGIC
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn data_directories(base: usize) -> usize {
|
||||
unsafe {
|
||||
let headers = base + read_u32(base + PE_HEADERS_OFFSET) as usize;
|
||||
headers
|
||||
+ OPTIONAL_HEADER_OFFSET
|
||||
+ if magic.read() == PE32_PLUS_MAGIC {
|
||||
+ if is_pe32_plus(base) {
|
||||
DATA_DIRECTORIES_OFFSET_64
|
||||
} else {
|
||||
DATA_DIRECTORIES_OFFSET_32
|
||||
};
|
||||
|
||||
base + read_u32(directories) as usize
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3903,6 +3900,12 @@ const PE32_PLUS_MAGIC: u16 = 0x20b;
|
||||
const DATA_DIRECTORIES_OFFSET_32: usize = 0x60;
|
||||
const DATA_DIRECTORIES_OFFSET_64: usize = 0x70;
|
||||
const EXPORT_NAME_COUNT_OFFSET: usize = 0x18;
|
||||
const IMPORT_DIRECTORY_INDEX: usize = 1;
|
||||
const IMPORT_DESCRIPTOR_SIZE: usize = 20;
|
||||
const IMPORT_LOOKUPS_OFFSET: usize = 0;
|
||||
const IMPORT_NAME_OFFSET: usize = 12;
|
||||
const IMPORT_THUNKS_OFFSET: usize = 16;
|
||||
const IMPORT_HINT_SIZE: usize = 2;
|
||||
const EXPORT_FUNCTIONS_OFFSET: usize = 0x1c;
|
||||
const EXPORT_NAMES_OFFSET: usize = 0x20;
|
||||
const EXPORT_ORDINALS_OFFSET: usize = 0x24;
|
||||
@@ -4114,19 +4117,12 @@ struct Target {
|
||||
started: bool,
|
||||
introduced: bool,
|
||||
text: u64,
|
||||
size: u64,
|
||||
stack: u64,
|
||||
step: u64,
|
||||
carrier: *mut c_void,
|
||||
arena_mdl: *mut c_void,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
fn private_offset(&self) -> u64 {
|
||||
crate::writable_half_start() as u64
|
||||
- unsafe { core::ptr::addr_of!(crate::OWN_RANGE).read() }.base_address
|
||||
}
|
||||
}
|
||||
|
||||
pub const ARENA_SIZE: usize = 0x1000 + 2 * FRAME_BUFFER_SIZE;
|
||||
const FRAME_BUFFER_SIZE: usize = 0x4000;
|
||||
@@ -4672,18 +4668,11 @@ pub fn set_kernel_base(base: u64) {
|
||||
|
||||
static KERNEL_BASE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
unsafe extern "C" {
|
||||
fn frida_winnt_run_on_stack(stack_top: *mut u8, entry: unsafe extern "C" fn(*mut c_void),
|
||||
context: *mut c_void);
|
||||
}
|
||||
|
||||
// To give a fault back to the kernel, remove only the vector from the frame. Thus the error
|
||||
// code stays where the previous handler reads it.
|
||||
#[cfg(target_arch = "x86")]
|
||||
core::arch::global_asm!(
|
||||
r#"
|
||||
.intel_syntax noprefix
|
||||
|
||||
.global frida_winnt_run_on_stack
|
||||
frida_winnt_run_on_stack:
|
||||
push ebp
|
||||
@@ -4709,8 +4698,6 @@ frida_winnt_run_on_stack:
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
core::arch::global_asm!(
|
||||
r#"
|
||||
.intel_syntax noprefix
|
||||
|
||||
.global frida_winnt_run_on_stack
|
||||
frida_winnt_run_on_stack:
|
||||
push rbp
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
// that you calculate from the page, and no kernel export is necessary. The two word sizes
|
||||
// differ only in the address of the self-map and the number of levels.
|
||||
|
||||
use core::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use crate::kernel::MemoryRegion;
|
||||
|
||||
pub fn protect(address: u64, size: usize, gum_prot: u32) -> bool {
|
||||
@@ -206,6 +204,7 @@ mod arch {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
mod arch {
|
||||
use super::*;
|
||||
use core::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
pub fn mapping_at(address: usize) -> Option<(u32, usize)> {
|
||||
for level in TOP_LEVEL..TABLE_LEVEL {
|
||||
@@ -331,7 +330,7 @@ mod arch {
|
||||
}
|
||||
|
||||
fn discover_self_map() -> Option<usize> {
|
||||
let probe = discover_self_map as usize;
|
||||
let probe = discover_self_map as *const () as usize;
|
||||
let expected = crate::winnt::virt_to_phys(probe as u64) & ADDRESS_MASK;
|
||||
if expected == 0 {
|
||||
return None;
|
||||
@@ -370,12 +369,6 @@ mod arch {
|
||||
|
||||
const LEVEL_SHIFTS: [usize; 4] = [39, 30, 21, 12];
|
||||
const LEVEL_INDEX_MASKS: [usize; 4] = [0x1ff, 0x3_ffff, 0x7ff_ffff, 0xf_ffff_ffff];
|
||||
const LEVEL_BASES: [usize; 4] = [
|
||||
0xffff_f6fb_7dbe_d000,
|
||||
0xffff_f6fb_7da0_0000,
|
||||
0xffff_f6fb_4000_0000,
|
||||
0xffff_f680_0000_0000,
|
||||
];
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
@@ -582,6 +575,7 @@ pub use arch::present_span;
|
||||
|
||||
use arch::{mapping_at, reprotect, walk_kernel_space};
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
fn protection_of(entry: u64, no_execute: u64) -> u32 {
|
||||
let mut prot = GUM_PAGE_READ;
|
||||
if (entry & PAGE_WRITEABLE as u64) != 0 {
|
||||
@@ -593,6 +587,7 @@ fn protection_of(entry: u64, no_execute: u64) -> u32 {
|
||||
prot
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
fn apply_protection(entry: u64, gum_prot: u64, writeable: u64, no_execute: u64) -> u64 {
|
||||
let mut value = entry;
|
||||
|
||||
@@ -634,9 +629,13 @@ fn invalidate_page(address: usize) {
|
||||
}
|
||||
|
||||
const PAGE_SIZE: usize = 4096;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PAGE_PRESENT: u32 = 0x1;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PAGE_WRITEABLE: u32 = 0x2;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PAGE_LARGE: u32 = 0x80;
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
const PAGE_NO_EXECUTE: u64 = 1 << 63;
|
||||
|
||||
pub(crate) const GUM_PAGE_READ: u32 = 0x1;
|
||||
|
||||
@@ -8,6 +8,7 @@ use alloc::vec::Vec;
|
||||
use core::ffi::c_void;
|
||||
use core::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use crate::gum_windows::{FileApi, TextApi};
|
||||
use crate::kernel::MemoryRegion;
|
||||
use crate::winnt::{
|
||||
BLOCK_PROCESS_ID, BLOCK_THREAD_ID, CURRENT_PROCESS, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE,
|
||||
@@ -18,7 +19,6 @@ use crate::winnt::{
|
||||
USER_SHARED_DATA, AGENT_WAKE_HANDLE,
|
||||
LDR_IN_LOAD_ORDER_OFFSET, LOADER_LIBRARY, PEB_LDR_OFFSET,
|
||||
CONTEXT_ALIGNMENT, CONTEXT_CONTROL, CONTEXT_FLAGS, CONTEXT_FULL, CONTEXT_PC, CONTEXT_SIZE,
|
||||
PEB_PARAMETERS_OFFSET,
|
||||
POINTER_SIZE, export, module_base, read_pointer, read_u32,
|
||||
select_user, take_frame_from_host, windows_fn,
|
||||
};
|
||||
@@ -139,6 +139,7 @@ pub static USER: Primitives = Primitives {
|
||||
shared_data,
|
||||
};
|
||||
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
pub(crate) fn flush_code(start: *const u8, end: *const u8) -> bool {
|
||||
let Some(api) = (unsafe { (*core::ptr::addr_of!(USER_API)).as_ref() }) else {
|
||||
return false;
|
||||
@@ -149,10 +150,6 @@ pub(crate) fn flush_code(start: *const u8, end: *const u8) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn yield_entry_point() -> usize {
|
||||
unsafe { user_api().yield_execution as usize }
|
||||
}
|
||||
|
||||
fn resolve_user_api() {
|
||||
let ntdll = loader_library();
|
||||
|
||||
@@ -172,6 +169,7 @@ fn resolve_user_api() {
|
||||
create_event: core::mem::transmute(export(ntdll, b"NtCreateEvent")),
|
||||
close: core::mem::transmute(export(ntdll, b"NtClose")),
|
||||
exit_thread: core::mem::transmute(export(ntdll, b"RtlExitUserThread")),
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
flush_code: core::mem::transmute(export(ntdll, b"NtFlushInstructionCache")),
|
||||
create_heap: core::mem::transmute(export(ntdll, b"RtlCreateHeap")),
|
||||
add_fault_handler: core::mem::transmute(
|
||||
@@ -418,6 +416,7 @@ fn thread_starter() -> Option<usize> {
|
||||
Some((jump as isize + 5 + displacement as isize) as usize)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
const THREAD_THUNK: [u8; 7] = [0x33, 0xed, 0x53, 0x50, 0x6a, 0x00, 0xe9];
|
||||
|
||||
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
|
||||
@@ -425,6 +424,7 @@ fn thread_starter() -> Option<usize> {
|
||||
Some(export(module_base(peb(), b"kernel32.dll"), b"BaseThreadStart"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
fn image_size(base: usize) -> usize {
|
||||
unsafe {
|
||||
let headers = base + ((base + PE_SIGNATURE_OFFSET) as *const u32).read() as usize;
|
||||
@@ -432,6 +432,7 @@ fn image_size(base: usize) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
const PE_IMAGE_SIZE_OFFSET: usize = 0x50;
|
||||
|
||||
pub struct LoaderEntryPoints {
|
||||
@@ -529,12 +530,10 @@ pub fn spawn_process(command_line: &str) -> u32 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
unsafe {
|
||||
held().insert(made.pid, HeldProcess {
|
||||
process: made.process,
|
||||
thread: made.thread,
|
||||
})
|
||||
};
|
||||
held().insert(made.pid, HeldProcess {
|
||||
process: made.process,
|
||||
thread: made.thread,
|
||||
});
|
||||
|
||||
made.pid
|
||||
}
|
||||
@@ -681,7 +680,6 @@ fn make_process(command_line: &str) -> Option<MadeProcess> {
|
||||
process: read_handle(&information, PROCESS_INFORMATION_PROCESS),
|
||||
thread: read_handle(&information, PROCESS_INFORMATION_THREAD),
|
||||
pid: unsafe { read_u32(information.as_ptr() as usize + PROCESS_INFORMATION_PID) },
|
||||
tid: unsafe { read_u32(information.as_ptr() as usize + PROCESS_INFORMATION_TID) },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -689,11 +687,10 @@ struct MadeProcess {
|
||||
process: *mut c_void,
|
||||
thread: *mut c_void,
|
||||
pid: u32,
|
||||
tid: u32,
|
||||
}
|
||||
|
||||
pub fn resume_process(pid: u32) -> bool {
|
||||
let Some(held) = (unsafe { held().remove(&pid) }) else {
|
||||
let Some(held) = held().remove(&pid) else {
|
||||
return false;
|
||||
};
|
||||
let api = spawn_api();
|
||||
@@ -762,10 +759,6 @@ const PROCESS_BASIC_INFORMATION_PEB: usize = 0x08;
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
const PEB_IMAGE_BASE_OFFSET: usize = 0x10;
|
||||
|
||||
#[cfg(target_arch = "x86")]
|
||||
const UNICODE_STRING_SIZE: usize = 8;
|
||||
#[cfg(target_arch = "x86")]
|
||||
const PARAMETERS_DESKTOP_OFFSET: usize = 0x78;
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
const PROCESS_INFORMATION_SIZE: usize = 128;
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
@@ -775,14 +768,8 @@ const PROCESS_INFORMATION_THREAD: usize = 0x04;
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
const PROCESS_INFORMATION_PID: usize = 0x08;
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
const PROCESS_INFORMATION_TID: usize = 0x0c;
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
const STARTUP_INFO_SIZE: usize = 0x44;
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const UNICODE_STRING_SIZE: usize = 16;
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const PARAMETERS_DESKTOP_OFFSET: usize = 0xc0;
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
const PROCESS_INFORMATION_SIZE: usize = 192;
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
@@ -793,8 +780,6 @@ const PROCESS_INFORMATION_THREAD: usize = 0x08;
|
||||
const PROCESS_INFORMATION_PID: usize = 0x10;
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
const STARTUP_INFO_SIZE: usize = 0x68;
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
const PROCESS_INFORMATION_TID: usize = 0x20;
|
||||
|
||||
fn spawn_api() -> &'static SpawnApi {
|
||||
unsafe { (*core::ptr::addr_of!(SPAWN_API)).as_ref().unwrap() }
|
||||
@@ -804,6 +789,68 @@ fn user_api() -> &'static UserApi {
|
||||
unsafe { (*core::ptr::addr_of!(USER_API)).as_ref().unwrap() }
|
||||
}
|
||||
|
||||
pub fn last_error() -> u32 {
|
||||
unsafe { (error_api().get_last_error)() }
|
||||
}
|
||||
|
||||
pub fn set_last_error(value: u32) {
|
||||
unsafe { (error_api().set_last_error)(value) }
|
||||
}
|
||||
|
||||
fn error_api() -> &'static ErrorApi {
|
||||
unsafe {
|
||||
if (*core::ptr::addr_of!(ERROR_API)).is_none() {
|
||||
let library = module_base(peb(), b"kernel32.dll");
|
||||
ERROR_API = Some(ErrorApi {
|
||||
get_last_error: core::mem::transmute(export(library, b"GetLastError")),
|
||||
set_last_error: core::mem::transmute(export(library, b"SetLastError")),
|
||||
});
|
||||
}
|
||||
(*core::ptr::addr_of!(ERROR_API)).as_ref().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
struct ErrorApi {
|
||||
get_last_error: windows_fn!(=> u32),
|
||||
set_last_error: windows_fn!(u32),
|
||||
}
|
||||
|
||||
static mut ERROR_API: Option<ErrorApi> = None;
|
||||
|
||||
pub fn file_api() -> &'static FileApi {
|
||||
unsafe {
|
||||
if (*core::ptr::addr_of!(FILE_API)).is_none() {
|
||||
let library = module_base(peb(), b"kernel32.dll");
|
||||
FILE_API = Some(FileApi {
|
||||
read_file: core::mem::transmute(export(library, b"ReadFile")),
|
||||
write_file: core::mem::transmute(export(library, b"WriteFile")),
|
||||
close_handle: core::mem::transmute(export(library, b"CloseHandle")),
|
||||
format_message: core::mem::transmute(export(library, b"FormatMessageA")),
|
||||
});
|
||||
}
|
||||
(*core::ptr::addr_of!(FILE_API)).as_ref().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
static mut FILE_API: Option<FileApi> = None;
|
||||
|
||||
pub fn text_api() -> &'static TextApi {
|
||||
unsafe {
|
||||
if (*core::ptr::addr_of!(TEXT_API)).is_none() {
|
||||
let library = module_base(peb(), b"kernel32.dll");
|
||||
TEXT_API = Some(TextApi {
|
||||
multi_byte_to_wide_char: core::mem::transmute(
|
||||
export(library, b"MultiByteToWideChar")),
|
||||
wide_char_to_multi_byte: core::mem::transmute(
|
||||
export(library, b"WideCharToMultiByte")),
|
||||
});
|
||||
}
|
||||
(*core::ptr::addr_of!(TEXT_API)).as_ref().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
static mut TEXT_API: Option<TextApi> = None;
|
||||
|
||||
struct UserApi {
|
||||
allocate_heap: windows_fn!(usize, u32, usize => *mut u8),
|
||||
free_heap: windows_fn!(usize, u32, *mut u8 => u8),
|
||||
@@ -814,6 +861,7 @@ struct UserApi {
|
||||
yield_execution: windows_fn!( => i32),
|
||||
wait_for_object: windows_fn!(*mut c_void, u8, *const i64 => i32),
|
||||
wait_for_objects: windows_fn!(u32, *const *mut c_void, u32, u8, *const i64 => i32),
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
flush_code: windows_fn!(*mut c_void, *mut u8, usize => i32),
|
||||
set_event: windows_fn!(*mut c_void, *mut u32 => i32),
|
||||
reset_event: windows_fn!(*mut c_void, *mut u32 => i32),
|
||||
@@ -984,7 +1032,8 @@ fn serve_the_copy() {
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn poll_handles(ufds: *mut crate::GPollFd, nfds: u32, timeout: i32) -> i32 {
|
||||
pub(crate) unsafe extern "C" fn poll_handles(ufds: *mut crate::bindings::GPollFD, nfds: u32,
|
||||
timeout: i32) -> i32 {
|
||||
const MAX_HANDLES: usize = 16;
|
||||
let fds = unsafe { core::slice::from_raw_parts_mut(ufds, nfds as usize) };
|
||||
|
||||
@@ -1237,6 +1286,7 @@ fn enumerate_threads(found: &mut dyn FnMut(crate::kernel::ThreadInfo), with_regi
|
||||
for_each_thread(&mut |id| {
|
||||
found(crate::kernel::ThreadInfo {
|
||||
id,
|
||||
state: None,
|
||||
cpu_state: with_registers.then(|| registers_of(id)).flatten(),
|
||||
});
|
||||
true
|
||||
@@ -1254,6 +1304,7 @@ fn find_thread(id: u32, with_registers: bool) -> Option<crate::kernel::ThreadInf
|
||||
|
||||
found.then(|| crate::kernel::ThreadInfo {
|
||||
id,
|
||||
state: None,
|
||||
cpu_state: with_registers.then(|| registers_of(id)).flatten(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub struct Primitives {
|
||||
pub page_size: fn() -> usize,
|
||||
pub cache_shape: fn() -> u64,
|
||||
pub enumerate_ranges: fn(&mut dyn FnMut(u64, usize, u32)),
|
||||
pub enumerate_threads: fn(&mut dyn FnMut(crate::kernel::ThreadInfo)),
|
||||
pub enumerate_threads: fn(&mut dyn FnMut(crate::kernel::ThreadInfo), bool),
|
||||
pub find_thread: fn(u32) -> Option<crate::kernel::ThreadInfo>,
|
||||
pub modify_thread: fn(u32, &mut dyn FnMut(&mut crate::kernel::CpuState)) -> bool,
|
||||
}
|
||||
@@ -121,8 +121,8 @@ pub fn enumerate_ranges(found: &mut dyn FnMut(u64, usize, u32)) {
|
||||
(primitives().enumerate_ranges)(found);
|
||||
}
|
||||
|
||||
pub fn enumerate_threads(found: &mut dyn FnMut(crate::kernel::ThreadInfo)) {
|
||||
(primitives().enumerate_threads)(found);
|
||||
pub fn enumerate_threads(found: &mut dyn FnMut(crate::kernel::ThreadInfo), with_registers: bool) {
|
||||
(primitives().enumerate_threads)(found, with_registers);
|
||||
}
|
||||
|
||||
pub fn find_thread(id: u32) -> Option<crate::kernel::ThreadInfo> {
|
||||
@@ -141,7 +141,7 @@ fn kernel_protect(_address: u64, _size: usize, _may: u32) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn kernel_enumerate_threads(_found: &mut dyn FnMut(crate::kernel::ThreadInfo)) {}
|
||||
fn kernel_enumerate_threads(_found: &mut dyn FnMut(crate::kernel::ThreadInfo), _with_registers: bool) {}
|
||||
|
||||
fn kernel_find_thread(_id: u32) -> Option<crate::kernel::ThreadInfo> {
|
||||
None
|
||||
@@ -883,30 +883,6 @@ pub fn write_through_a_writable_alias(address: u64, data: *const u8, len: usize)
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(feature = "xnu-kext")]
|
||||
fn alias_of(physical: u64, page: usize) -> *mut c_void {
|
||||
let held = unsafe { aliases() };
|
||||
if let Some(known) = held.get(&physical) {
|
||||
return *known as *mut c_void;
|
||||
}
|
||||
|
||||
let made = map_io(physical, page as u64);
|
||||
if !made.is_null() {
|
||||
held.insert(physical, made as u64);
|
||||
}
|
||||
|
||||
made
|
||||
}
|
||||
|
||||
#[cfg(feature = "xnu-kext")]
|
||||
unsafe fn aliases() -> &'static mut alloc::collections::BTreeMap<u64, u64> {
|
||||
unsafe { (&raw mut ALIASES).as_mut().unwrap() }
|
||||
}
|
||||
|
||||
#[cfg(feature = "xnu-kext")]
|
||||
static mut ALIASES: alloc::collections::BTreeMap<u64, u64> =
|
||||
alloc::collections::BTreeMap::new();
|
||||
|
||||
#[cfg(feature = "xnu-kext")]
|
||||
fn hold_the_books() {
|
||||
while BOOKS
|
||||
@@ -953,20 +929,6 @@ fn copy_the_words_that_differ(from: *const u8, have: *const u8, to: *mut u8, len
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(feature = "xnu-kext")]
|
||||
fn copy_as_words(from: *const u8, to: *mut u8, len: usize) -> bool {
|
||||
if (to as usize) % 4 != 0 || len % 4 != 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
for step in (0..len).step_by(4) {
|
||||
let word = unsafe { (from.add(step) as *const u32).read_unaligned() };
|
||||
unsafe { (to.add(step) as *mut u32).write_volatile(word) };
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub fn virt_to_phys(vaddr: u64) -> u64 {
|
||||
unsafe {
|
||||
if let Some(ask) = _ml_vtophys {
|
||||
|
||||
@@ -489,7 +489,7 @@ pub fn one_of_ours(number: u64) {
|
||||
}
|
||||
|
||||
pub fn forget_the_threads_of(arena: u64) {
|
||||
let said = unsafe { ((arena + crate::xnu_relay::OUR_THREADS) as *const u64) };
|
||||
let said = (arena + crate::xnu_relay::OUR_THREADS) as *const u64;
|
||||
for step in 0..MOST_OF_OURS_IN_ONE {
|
||||
let number = unsafe { said.add(step).read_volatile() };
|
||||
for kept in ours().iter_mut().filter(|kept| **kept == number && number != 0) {
|
||||
@@ -499,7 +499,7 @@ pub fn forget_the_threads_of(arena: u64) {
|
||||
}
|
||||
|
||||
pub fn take_note_of_what_a_copy_says(arena: u64) {
|
||||
let said = unsafe { ((arena + crate::xnu_relay::OUR_THREADS) as *const u64) };
|
||||
let said = (arena + crate::xnu_relay::OUR_THREADS) as *const u64;
|
||||
for step in 0..MOST_OF_OURS_IN_ONE {
|
||||
one_of_ours(unsafe { said.add(step).read_volatile() });
|
||||
}
|
||||
|
||||
@@ -163,9 +163,7 @@ fn where_a_copy_has_been(id: u32, map: *mut c_void) -> Option<u64> {
|
||||
(kept.map == map).then_some(kept.code)
|
||||
}
|
||||
|
||||
fn what_an_agent_before_this_one_left(map: *mut c_void, shared: usize, size: usize)
|
||||
-> Option<u64>
|
||||
{
|
||||
fn what_an_agent_before_this_one_left(map: *mut c_void, shared: usize) -> Option<u64> {
|
||||
let ask = unsafe { _mach_vm_region }?;
|
||||
let mut at = 0u64;
|
||||
for _ in 0..MOST_RANGES_TO_LOOK_THROUGH {
|
||||
@@ -501,7 +499,7 @@ fn give_the_copy_a_home(id: u32, map: *mut c_void) -> Option<Home> {
|
||||
let shared = crate::writable_half_start() - base;
|
||||
|
||||
let (code, seen_from_here, seen_size) = match where_a_copy_has_been(id, map)
|
||||
.or_else(|| what_an_agent_before_this_one_left(map, shared, size))
|
||||
.or_else(|| what_an_agent_before_this_one_left(map, shared))
|
||||
{
|
||||
Some(code) => {
|
||||
let private = (size - shared) as u64;
|
||||
|
||||
@@ -3,7 +3,7 @@ use alloc::string::{String, ToString};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use crate::bindings::{
|
||||
GumDarwinExportDetails, GumDarwinModule, GumMemoryRange, GumModuleRegistry, GumAddress,
|
||||
GumMachoExportDetails, GumMachoModule, GumMemoryRange, GumModuleRegistry, GumAddress,
|
||||
gboolean, g_object_unref, gpointer, gsize,
|
||||
};
|
||||
use crate::gum;
|
||||
@@ -33,7 +33,7 @@ pub fn enumerate_exports_in_range(from: u64, to: u64,
|
||||
|
||||
let mut asking = Asking { found, base: image.base };
|
||||
unsafe {
|
||||
crate::bindings::gum_darwin_module_enumerate_exports(module,
|
||||
crate::bindings::gum_macho_module_enumerate_exports(module,
|
||||
Some(crate::signed_to_be_called_back(note_an_export, 0)),
|
||||
&mut asking as *mut Asking<'_, '_> as gpointer);
|
||||
g_object_unref(module as gpointer);
|
||||
@@ -45,7 +45,7 @@ struct Asking<'a, 'b> {
|
||||
base: u64,
|
||||
}
|
||||
|
||||
unsafe extern "C" fn note_an_export(details: *const GumDarwinExportDetails, asking: gpointer)
|
||||
unsafe extern "C" fn note_an_export(details: *const GumMachoExportDetails, asking: gpointer)
|
||||
-> gboolean
|
||||
{
|
||||
let asking = unsafe { &mut *(asking as *mut Asking<'_, '_>) };
|
||||
@@ -58,6 +58,7 @@ unsafe extern "C" fn note_an_export(details: *const GumDarwinExportDetails, aski
|
||||
1
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
pub fn export_named(wanted: &str) -> u64 {
|
||||
let Some(ask_the_loader) = crate::xnu_libsystem::function_named(b"/libdyld.dylib", b"_dlsym")
|
||||
else {
|
||||
@@ -76,6 +77,7 @@ pub fn export_named(wanted: &str) -> u64 {
|
||||
unsafe { crate::pac::ptrauth_strip_data(signed as *const u8) as u64 }
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
const WHEREVER_IT_IS: *const core::ffi::c_void = -2isize as *const core::ffi::c_void;
|
||||
|
||||
struct Image {
|
||||
@@ -144,10 +146,10 @@ fn where_the_loader_keeps_its_list() -> Option<u64> {
|
||||
(list != 0).then_some(list)
|
||||
}
|
||||
|
||||
fn read_the_image(base: u64, name: &str) -> Option<*mut GumDarwinModule> {
|
||||
fn read_the_image(base: u64, name: &str) -> Option<*mut GumMachoModule> {
|
||||
let named = alloc::ffi::CString::new(name).ok()?;
|
||||
let module = unsafe {
|
||||
crate::bindings::gum_darwin_module_new_from_memory(named.as_ptr(), NO_TASK_TO_ASK,
|
||||
crate::bindings::gum_macho_module_new_from_memory(named.as_ptr(), NO_TASK_TO_ASK,
|
||||
base as GumAddress, 0, core::ptr::null_mut())
|
||||
};
|
||||
|
||||
@@ -161,7 +163,7 @@ fn how_much_of_it_there_is(base: u64, name: &str) -> u64 {
|
||||
|
||||
let mut size = 0;
|
||||
for step in 0.. {
|
||||
let segment = unsafe { crate::bindings::gum_darwin_module_get_nth_segment(module, step) };
|
||||
let segment = unsafe { crate::bindings::gum_macho_module_get_nth_segment(module, step) };
|
||||
if segment.is_null() {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ pub struct ProcessInfo {
|
||||
pub name: *const u8,
|
||||
pub path: *const u8,
|
||||
pub command_line: *const u8,
|
||||
pub uid: u32,
|
||||
pub user: *const u8,
|
||||
pub ppid: u32,
|
||||
pub started: i64,
|
||||
}
|
||||
|
||||
// The kernel walks its own list, and where a process keeps its number and its name is what the
|
||||
@@ -33,6 +37,10 @@ pub fn enumerate_processes(found: &mut dyn FnMut(ProcessInfo)) {
|
||||
name: name.as_ptr(),
|
||||
path: name.as_ptr(),
|
||||
command_line: core::ptr::null(),
|
||||
uid: 0,
|
||||
user: core::ptr::null(),
|
||||
ppid: 0,
|
||||
started: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
|
||||
pub fn entry_offset() -> usize {
|
||||
(frida_xnu_user_entry as usize) - crate::own_range().0
|
||||
(frida_xnu_user_entry as *const () as usize) - crate::own_range().0
|
||||
}
|
||||
|
||||
pub extern "C" fn frida_xnu_user_entry(arena: usize) -> ! {
|
||||
|
||||
@@ -257,7 +257,7 @@ struct Region {
|
||||
size: u64,
|
||||
}
|
||||
|
||||
fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo)) {
|
||||
fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo), _with_registers: bool) {
|
||||
let Some(asking) = crate::xnu_libsystem::asking_about_threads() else {
|
||||
return;
|
||||
};
|
||||
@@ -273,7 +273,7 @@ fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo)) {
|
||||
|
||||
for step in 0..counted as usize {
|
||||
let thread = unsafe { threads.add(step).read() };
|
||||
found(ThreadInfo { id: thread, cpu_state: state_of(thread) });
|
||||
found(ThreadInfo { id: thread, state: None, cpu_state: state_of(thread) });
|
||||
}
|
||||
|
||||
unsafe { (asking.give_back)(task, threads as u64, (counted as u64) * 4) };
|
||||
@@ -285,7 +285,7 @@ fn find_thread(id: u32) -> Option<ThreadInfo> {
|
||||
if thread.id == id {
|
||||
found = Some(thread);
|
||||
}
|
||||
});
|
||||
}, true);
|
||||
|
||||
found
|
||||
}
|
||||
@@ -404,10 +404,6 @@ unsafe extern "C" fn say_which_one_first(errand: *mut c_void) -> *mut c_void {
|
||||
core::ptr::null_mut()
|
||||
}
|
||||
|
||||
const STACK: usize = 1024 * 1024;
|
||||
const STACK_HEADROOM: u64 = 0x100;
|
||||
const PLAIN_ADDRESSES: u32 = 1;
|
||||
|
||||
pub fn process_id() -> u32 {
|
||||
unsafe { ask(GET_PID, [0; 4]) as u32 }
|
||||
}
|
||||
@@ -439,6 +435,7 @@ pub fn where_the_shared_code_is() -> Option<u64> {
|
||||
|
||||
const WHERE_IS_THE_SHARED_CODE: i64 = 294;
|
||||
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
pub fn code_memory_near(wanted: u64, size: usize) -> *mut u8 {
|
||||
let mut address = wanted;
|
||||
let told = unsafe {
|
||||
@@ -453,6 +450,7 @@ pub fn code_memory_near(wanted: u64, size: usize) -> *mut u8 {
|
||||
take_memory(size).unwrap_or(0) as *mut u8
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
fn own_task_map() -> u64 {
|
||||
own_task() as u64
|
||||
}
|
||||
@@ -556,10 +554,6 @@ pub fn give_memory_back(address: u64, size: usize) {
|
||||
unsafe { trap(MACH_VM_DEALLOCATE, [task(), address, size as u64, 0]) };
|
||||
}
|
||||
|
||||
fn set_protection(address: u64, size: usize, may: u64) -> bool {
|
||||
unsafe { trap(MACH_VM_PROTECT, [task(), address, size as u64, may]) == KERN_SUCCESS }
|
||||
}
|
||||
|
||||
unsafe fn task() -> u64 {
|
||||
unsafe { trap(TASK_SELF, [0; 4]) as u64 }
|
||||
}
|
||||
@@ -604,14 +598,11 @@ pub(crate) unsafe fn ask7(number: i64, args: [u64; 7]) -> (i64, bool) {
|
||||
(answer, went_wrong != 0)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "xnu-kext"))]
|
||||
pub(crate) fn own_task() -> u32 {
|
||||
unsafe { trap(TASK_SELF, [0; 4]) as u32 }
|
||||
}
|
||||
|
||||
pub fn own_thread() -> u32 {
|
||||
unsafe { trap(THREAD_SELF, [0; 4]) as u32 }
|
||||
}
|
||||
|
||||
pub(crate) fn a_port_to_answer_on() -> u32 {
|
||||
unsafe { trap(REPLY_PORT, [0; 4]) as u32 }
|
||||
}
|
||||
@@ -640,11 +631,8 @@ const ANYWHERE: u64 = 1;
|
||||
|
||||
const MACH_VM_ALLOCATE: i64 = -10;
|
||||
const MACH_VM_DEALLOCATE: i64 = -12;
|
||||
const MACH_VM_PROTECT: i64 = -14;
|
||||
const TASK_SELF: i64 = -28;
|
||||
const REPLY_PORT: i64 = -26;
|
||||
const THREAD_SELF: i64 = -27;
|
||||
pub(crate) const MACH_MSG: i64 = -31;
|
||||
|
||||
const COMPARE_AND_WAIT: u64 = 1;
|
||||
const WAKE_ALL: u64 = 0x100;
|
||||
|
||||
+13
-13
@@ -8,7 +8,7 @@ namespace Frida.Barebone {
|
||||
public abstract Gum.PageProtection granted_protection ();
|
||||
|
||||
public abstract async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable)
|
||||
throws Error, IOError;
|
||||
throws Efni.Error, IOError;
|
||||
}
|
||||
|
||||
public interface Allocation : Object {
|
||||
@@ -20,11 +20,11 @@ namespace Frida.Barebone {
|
||||
get;
|
||||
}
|
||||
|
||||
public abstract async void deallocate (Cancellable? cancellable) throws Error, IOError;
|
||||
public abstract async void deallocate (Cancellable? cancellable) throws Efni.Error, IOError;
|
||||
}
|
||||
|
||||
internal async void protect_unless_already (Machine machine, Allocator allocator, uint64 address, size_t size,
|
||||
Gum.PageProtection prot, Cancellable? cancellable) throws Error, IOError {
|
||||
Gum.PageProtection prot, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if ((allocator.granted_protection () & prot) == prot)
|
||||
return;
|
||||
|
||||
@@ -55,9 +55,9 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
if (size > _size)
|
||||
throw new Error.NOT_SUPPORTED ("Reserved region is too small");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Reserved region is too small");
|
||||
|
||||
return new FixedAllocation (address, size);
|
||||
}
|
||||
@@ -84,7 +84,7 @@ namespace Frida.Barebone {
|
||||
this._size = size;
|
||||
}
|
||||
|
||||
public async void deallocate (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void deallocate (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,8 +105,8 @@ namespace Frida.Barebone {
|
||||
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 async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("To enable this feature, specify an allocator in your FRIDA_BAREBONE_CONFIG");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ namespace Frida.Barebone {
|
||||
this.cursor = config.physical_base.address;
|
||||
}
|
||||
|
||||
public async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable) throws Error, IOError {
|
||||
public async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
uint64 address_pa = cursor;
|
||||
|
||||
size_t vm_size = round_size_up (size, _page_size);
|
||||
@@ -168,7 +168,7 @@ namespace Frida.Barebone {
|
||||
page_allocation = allocation;
|
||||
}
|
||||
|
||||
public async void deallocate (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void deallocate (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
// TODO: Add to freelist.
|
||||
yield page_allocation.deallocate (cancellable);
|
||||
}
|
||||
@@ -208,14 +208,14 @@ namespace Frida.Barebone {
|
||||
// A kernel allocator gives blocks with an alignment of less than a page, and the caller can
|
||||
// change the protection and write whole pages. Thus allocate enough for every page the
|
||||
// result spans, give out full pages, and keep the start of the block for the release.
|
||||
public async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable) throws Error, IOError {
|
||||
public async Allocation allocate (size_t size, size_t alignment, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
size_t aligned_size = (size + alignment - 1) & ~(alignment - 1);
|
||||
size_t padded_size = aligned_size + alignment - 1;
|
||||
|
||||
uint64 block = yield machine.invoke (alloc_function,
|
||||
resolve_arguments (alloc_arguments, padded_size, 0), cancellable);
|
||||
if (block == 0)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to allocate %zu bytes in the target", padded_size);
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unable to allocate %zu bytes in the target", padded_size);
|
||||
|
||||
uint64 address = (block + alignment - 1) & ~((uint64) alignment - 1);
|
||||
|
||||
@@ -274,7 +274,7 @@ namespace Frida.Barebone {
|
||||
this.free_arguments = free_arguments;
|
||||
}
|
||||
|
||||
public async void deallocate (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void deallocate (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
yield machine.invoke (free_function,
|
||||
resolve_arguments (free_arguments, block_size, block), cancellable);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using Efni;
|
||||
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public sealed class AndroidEmulatorStubClient : GDB.Client {
|
||||
private AndroidEmulatorStubClient (IOStream stream) {
|
||||
Object (stream: stream);
|
||||
}
|
||||
|
||||
public static new async AndroidEmulatorStubClient open (IOStream stream, Cancellable? cancellable = null)
|
||||
throws Efni.Error, IOError {
|
||||
var client = new AndroidEmulatorStubClient (stream);
|
||||
|
||||
try {
|
||||
yield client.init_async (Priority.DEFAULT, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
Efni.throw_api_error (e);
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
protected override async void detect_corellium (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public sealed class ArmMachine : Object, Machine {
|
||||
@@ -84,14 +86,14 @@ namespace Frida.Barebone {
|
||||
Object (debugger: debugger);
|
||||
}
|
||||
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Error, IOError {
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
return 4096;
|
||||
}
|
||||
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
DebuggerException? exception = debugger.exception;
|
||||
if (exception == null)
|
||||
throw new Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
throw new Efni.Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
DebuggerThread thread = exception.thread;
|
||||
|
||||
var cpsr = yield thread.read_register ("cpsr", cancellable);
|
||||
@@ -100,7 +102,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async void enumerate_ranges (Gum.PageProtection prot, FoundRangeFunc func, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
Gee.List<RangeDetails> ranges = yield collect_ranges_using_mmu (cancellable);
|
||||
foreach (RangeDetails r in coalesce_ranges (ranges)) {
|
||||
if ((r.protection & prot) != prot)
|
||||
@@ -110,7 +112,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
|
||||
private async Gee.List<RangeDetails> collect_ranges_using_mmu (Cancellable? cancellable) throws Error, IOError {
|
||||
private async Gee.List<RangeDetails> collect_ranges_using_mmu (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var result = new Gee.ArrayList<RangeDetails> ();
|
||||
|
||||
MMUParameters p = yield MMUParameters.load (debugger, cancellable);
|
||||
@@ -132,7 +134,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void collect_ranges_in_l1 (uint64 table_address, uint first_index, uint end_index, MMUParameters p,
|
||||
Gee.List<RangeDetails> ranges, Cancellable? cancellable) throws Error, IOError {
|
||||
Gee.List<RangeDetails> ranges, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
Buffer entries = yield read_physical_buffer (table_address + (first_index * L1_ENTRY_SIZE),
|
||||
(end_index - first_index) * L1_ENTRY_SIZE, cancellable);
|
||||
|
||||
@@ -158,7 +160,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void collect_ranges_in_l2 (uint64 table_address, uint64 base_va, MMUParameters p,
|
||||
Gee.List<RangeDetails> ranges, Cancellable? cancellable) throws Error, IOError {
|
||||
Gee.List<RangeDetails> ranges, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
Buffer entries = yield read_physical_buffer (table_address, L2_NUM_ENTRIES * L2_ENTRY_SIZE, cancellable);
|
||||
|
||||
for (uint i = 0; i != L2_NUM_ENTRIES; i++) {
|
||||
@@ -202,7 +204,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public override async void write_virtual (uint64 va, uint8[] data, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
if (kernel_page_table == 0) {
|
||||
yield debugger.write_byte_array (va, new Bytes (data), cancellable);
|
||||
return;
|
||||
@@ -229,7 +231,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async bool write_through_kernel_table (uint64 va, uint8[] data, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
size_t offset = 0;
|
||||
while (offset < data.length) {
|
||||
uint64 cur_va = va + offset;
|
||||
@@ -247,7 +249,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void locate_kernel_page_table (MMUParameters p, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
if (kernel_page_table == 0 || kernel_page_table_pa != 0)
|
||||
return;
|
||||
|
||||
@@ -257,7 +259,7 @@ namespace Frida.Barebone {
|
||||
kernel_page_table_pa = table;
|
||||
}
|
||||
|
||||
public override async uint64 translate_address (uint64 va, Cancellable? cancellable) throws Error, IOError {
|
||||
public override async uint64 translate_address (uint64 va, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
MMUParameters p = yield MMUParameters.load (debugger, cancellable);
|
||||
|
||||
bool was_running = yield enter_physical_addressing (debugger, cancellable);
|
||||
@@ -274,13 +276,13 @@ namespace Frida.Barebone {
|
||||
throw_if_failed (failure);
|
||||
|
||||
if (pa == null)
|
||||
throw new Error.INVALID_ARGUMENT ("Address 0x%x is not mapped", (uint) va);
|
||||
throw new Efni.Error.INVALID_ARGUMENT ("Address 0x%x is not mapped", (uint) va);
|
||||
|
||||
return pa;
|
||||
}
|
||||
|
||||
private async uint64 table_describing (uint64 va, MMUParameters p, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
if (kernel_page_table_pa != 0) {
|
||||
uint64 slot = kernel_page_table_pa + (((va >> L1_SHIFT) & (L1_NUM_ENTRIES - 1)) * L1_ENTRY_SIZE);
|
||||
uint32 entry = (yield read_physical_buffer (slot, L1_ENTRY_SIZE, cancellable)).read_uint32 (0);
|
||||
@@ -292,7 +294,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async uint64? translate_in_table (uint64 table_pa, uint64 va, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
uint64 l1_slot = table_pa + (((va >> L1_SHIFT) & (L1_NUM_ENTRIES - 1)) * L1_ENTRY_SIZE);
|
||||
uint32 l1 = (yield read_physical_buffer (l1_slot, L1_ENTRY_SIZE, cancellable)).read_uint32 (0);
|
||||
|
||||
@@ -317,7 +319,7 @@ namespace Frida.Barebone {
|
||||
return (l2 & SMALL_PAGE_MASK) | (va & 0xfff);
|
||||
}
|
||||
|
||||
private async Buffer read_physical_buffer (uint64 pa, size_t size, Cancellable? cancellable) throws Error, IOError {
|
||||
private async Buffer read_physical_buffer (uint64 pa, size_t size, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
return yield debugger.read_buffer (pa, size, cancellable);
|
||||
}
|
||||
|
||||
@@ -327,15 +329,15 @@ namespace Frida.Barebone {
|
||||
public uint n;
|
||||
public bool afe;
|
||||
|
||||
public static async MMUParameters load (Debugger debugger, Cancellable? cancellable) throws Error, IOError {
|
||||
public static async MMUParameters load (Debugger debugger, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
DebuggerException? exception = debugger.exception;
|
||||
if (exception == null)
|
||||
throw new Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
throw new Efni.Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
DebuggerThread thread = exception.thread;
|
||||
|
||||
uint64 ttbcr = yield thread.read_register ("ttbcr", cancellable);
|
||||
if ((ttbcr & TTBCR_EAE) != 0)
|
||||
throw new Error.NOT_SUPPORTED ("LPAE translation tables are not supported; please open a PR");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("LPAE translation tables are not supported; please open a PR");
|
||||
|
||||
uint64 sctlr;
|
||||
try {
|
||||
@@ -344,7 +346,7 @@ namespace Frida.Barebone {
|
||||
sctlr = yield thread.read_register ("sctlr_el1", cancellable);
|
||||
}
|
||||
if ((sctlr & SCTLR_M) == 0)
|
||||
throw new Error.NOT_SUPPORTED ("The MMU is off");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("The MMU is off");
|
||||
|
||||
var p = new MMUParameters ();
|
||||
p.n = (uint) (ttbcr & TTBCR_N_MASK);
|
||||
@@ -367,7 +369,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async Allocation allocate_pages (Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
MMUParameters p = yield MMUParameters.load (debugger, cancellable);
|
||||
|
||||
uint num_pages = physical_addresses.size;
|
||||
@@ -387,12 +389,12 @@ namespace Frida.Barebone {
|
||||
throw_if_failed (failure);
|
||||
|
||||
if (allocation == null)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to find a free run of page table entries");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unable to find a free run of page table entries");
|
||||
|
||||
return allocation;
|
||||
}
|
||||
|
||||
private async bool scan_for_run (Run run, MMUParameters p, Cancellable? cancellable) throws Error, IOError {
|
||||
private async bool scan_for_run (Run run, MMUParameters p, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
uint boundary = p.split_index;
|
||||
|
||||
if (boundary != L1_NUM_ENTRIES) {
|
||||
@@ -410,7 +412,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async bool scan_for_run_in_l1 (Run run, uint64 table_address, uint first_index, uint end_index,
|
||||
MMUParameters p, Cancellable? cancellable) throws Error, IOError {
|
||||
MMUParameters p, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
Buffer l1 = yield read_physical_buffer (table_address + (first_index * L1_ENTRY_SIZE),
|
||||
(end_index - first_index) * L1_ENTRY_SIZE, cancellable);
|
||||
|
||||
@@ -441,7 +443,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async Allocation occupy (Run run, Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var displaced = new Gee.ArrayList<DisplacedEntries> ();
|
||||
|
||||
uint next_page = 0;
|
||||
@@ -463,7 +465,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async void protect_pages (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
MMUParameters p = yield MMUParameters.load (debugger, cancellable);
|
||||
|
||||
uint64 start_va = page_start (virtual_address, SMALL_PAGE_SIZE);
|
||||
@@ -517,9 +519,9 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async uint64 skip_section (uint64 page_va, uint64 end_va, uint32 l1_entry, Gum.PageProtection prot,
|
||||
MMUParameters p, Cancellable? cancellable) throws Error, IOError {
|
||||
MMUParameters p, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if ((l1_entry & L1_KIND_MASK) != L1_KIND_SECTION) {
|
||||
throw new Error.NOT_SUPPORTED ("Unable to change protection of the unmapped page at 0x%"
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unable to change protection of the unmapped page at 0x%"
|
||||
+ uint64.FORMAT_MODIFIER + "x", page_va);
|
||||
}
|
||||
|
||||
@@ -527,7 +529,7 @@ namespace Frida.Barebone {
|
||||
| (((l1_entry >> SECTION_APX_SHIFT) & 1) << AP_HIGH_SHIFT);
|
||||
Gum.PageProtection current = protection_from_ap (ap, (l1_entry & SECTION_XN) != 0, p.afe);
|
||||
if ((current & prot) != prot) {
|
||||
throw new Error.NOT_SUPPORTED ("Unable to change protection of the section mapping at 0x%"
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unable to change protection of the section mapping at 0x%"
|
||||
+ uint64.FORMAT_MODIFIER + "x", page_va);
|
||||
}
|
||||
|
||||
@@ -561,7 +563,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void write_physical_buffer (uint64 pa, Bytes data, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
yield debugger.write_byte_array (pa, data, cancellable);
|
||||
}
|
||||
|
||||
@@ -649,7 +651,7 @@ namespace Frida.Barebone {
|
||||
this.machine = machine;
|
||||
}
|
||||
|
||||
public async void deallocate (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void deallocate (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
bool was_running = yield enter_physical_addressing (machine.debugger, cancellable);
|
||||
GLib.Error? failure = null;
|
||||
try {
|
||||
@@ -664,11 +666,11 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
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 ();
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Not yet supported");
|
||||
}
|
||||
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Error {
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Efni.Error {
|
||||
Gum.ElfArmRelocation type = (Gum.ElfArmRelocation) r.type;
|
||||
size_t offset = (size_t) r.address;
|
||||
switch (type) {
|
||||
@@ -682,14 +684,14 @@ namespace Frida.Barebone {
|
||||
relocated.write_int32 (offset, (int32) diff);
|
||||
break;
|
||||
default:
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported relocation type: %s",
|
||||
Marshal.enum_to_nick<Gum.ElfArmRelocation> (type));
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unsupported relocation type: %s",
|
||||
Efni.Marshal.enum_to_nick<Gum.ElfArmRelocation> (type));
|
||||
}
|
||||
}
|
||||
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (args.length > NUM_ARGS_IN_REGS)
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported number of arguments; please open a PR");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unsupported number of arguments; please open a PR");
|
||||
|
||||
bool was_running = debugger.state != STOPPED;
|
||||
if (was_running)
|
||||
@@ -718,7 +720,7 @@ namespace Frida.Barebone {
|
||||
int64 deadline = get_monotonic_time () + LANDING_TIMEOUT_USEC;
|
||||
do {
|
||||
if (get_monotonic_time () >= deadline)
|
||||
throw new Error.TIMED_OUT ("Timed out waiting for the call to return");
|
||||
throw new Efni.Error.TIMED_OUT ("Timed out waiting for the call to return");
|
||||
|
||||
ex = yield debugger.continue_until_exception (cancellable);
|
||||
} while (ex.breakpoint != bp);
|
||||
@@ -741,7 +743,7 @@ namespace Frida.Barebone {
|
||||
return cpsr & ~CPSR_THUMB_BIT;
|
||||
}
|
||||
|
||||
public async CallFrame load_call_frame (DebuggerThread thread, uint arity, Cancellable? cancellable) throws Error, IOError {
|
||||
public async CallFrame load_call_frame (DebuggerThread thread, uint arity, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var regs = yield thread.read_registers (cancellable);
|
||||
|
||||
Buffer? stack = null;
|
||||
@@ -844,7 +846,7 @@ namespace Frida.Barebone {
|
||||
stack_state = MODIFIED;
|
||||
}
|
||||
|
||||
public async void commit (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void commit (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (regs.get_data<bool> ("dirty"))
|
||||
yield thread.write_registers (regs, cancellable);
|
||||
|
||||
@@ -876,7 +878,7 @@ namespace Frida.Barebone {
|
||||
this.debugger = debugger;
|
||||
}
|
||||
|
||||
public async void destroy (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void destroy (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (state == DESTROYED)
|
||||
return;
|
||||
|
||||
@@ -892,16 +894,16 @@ namespace Frida.Barebone {
|
||||
yield debugger.resume (cancellable);
|
||||
}
|
||||
|
||||
public async void enable (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void enable (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (state == ENABLED)
|
||||
return;
|
||||
if (state != DISABLED)
|
||||
throw new Error.INVALID_OPERATION ("Invalid operation");
|
||||
throw new Efni.Error.INVALID_OPERATION ("Invalid operation");
|
||||
yield debugger.write_byte_array (target, new_target_code, cancellable);
|
||||
state = ENABLED;
|
||||
}
|
||||
|
||||
public async void disable (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void disable (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (state != ENABLED)
|
||||
return;
|
||||
yield debugger.write_byte_array (target, old_target_code, cancellable);
|
||||
@@ -918,7 +920,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async InlineHook create_inline_hook (uint64 target, uint64 handler, Allocator allocator,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
uint64 target_address = address_from_funcptr (target);
|
||||
bool target_is_thumb = (target & THUMB_BIT) != 0;
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public sealed class Arm64Machine : Object, Machine {
|
||||
@@ -74,7 +76,7 @@ namespace Frida.Barebone {
|
||||
Object (debugger: debugger);
|
||||
}
|
||||
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Error, IOError {
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if ("parallels" in debugger.features)
|
||||
return SMALLEST_GRANULE;
|
||||
|
||||
@@ -86,10 +88,10 @@ namespace Frida.Barebone {
|
||||
return p.granule;
|
||||
}
|
||||
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
DebuggerException? exception = debugger.exception;
|
||||
if (exception == null)
|
||||
throw new Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
throw new Efni.Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
DebuggerThread thread = exception.thread;
|
||||
|
||||
var cpsr = yield thread.read_register ("cpsr", cancellable);
|
||||
@@ -98,7 +100,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async void enumerate_ranges (Gum.PageProtection prot, FoundRangeFunc func, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
Gee.List<RangeDetails> ranges = ("corellium" in debugger.features)
|
||||
? yield collect_ranges_using_corellium (cancellable)
|
||||
: yield collect_ranges_using_mmu (cancellable);
|
||||
@@ -110,7 +112,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
|
||||
private async Gee.List<RangeDetails> collect_ranges_using_mmu (Cancellable? cancellable) throws Error, IOError {
|
||||
private async Gee.List<RangeDetails> collect_ranges_using_mmu (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var result = new Gee.ArrayList<RangeDetails> ();
|
||||
|
||||
MMUParameters p = yield load_mmu_parameters (cancellable);
|
||||
@@ -129,7 +131,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
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 {
|
||||
Gee.List<RangeDetails> ranges, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
uint max_entries = compute_max_entries (level, p);
|
||||
Buffer entries = yield read_physical_buffer (table_address, max_entries * Descriptor.SIZE, cancellable);
|
||||
uint shift = address_shift_at_level (level, p.granule);
|
||||
@@ -155,7 +157,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
|
||||
private async Gee.List<RangeDetails> collect_ranges_using_corellium (Cancellable? cancellable) throws Error, IOError {
|
||||
private async Gee.List<RangeDetails> collect_ranges_using_corellium (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var result = new Gee.ArrayList<RangeDetails> ();
|
||||
|
||||
string pt = yield debugger.run_remote_command ("pt", cancellable);
|
||||
@@ -168,7 +170,7 @@ namespace Frida.Barebone {
|
||||
|
||||
string[] range_tokens = range.split ("-");
|
||||
if (range_tokens.length != 2)
|
||||
throw new Error.PROTOCOL ("Unexpected Corellium response; please file a bug");
|
||||
throw new Efni.Error.PROTOCOL ("Unexpected Corellium response; please file a bug");
|
||||
|
||||
uint64 base_va = uint64.parse (range_tokens[0], 16);
|
||||
uint64 end_va = uint64.parse (range_tokens[1], 16) + 1;
|
||||
@@ -184,7 +186,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async Allocation allocate_pages (Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
MMUParameters p = yield load_mmu_parameters (cancellable);
|
||||
|
||||
bool was_running = yield begin_physical_addressing (cancellable);
|
||||
@@ -200,14 +202,14 @@ namespace Frida.Barebone {
|
||||
throw_if_failed (failure);
|
||||
|
||||
if (allocation == null)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to insert page table mapping; please file a bug");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unable to insert page table mapping; please file a bug");
|
||||
|
||||
return allocation;
|
||||
}
|
||||
|
||||
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 {
|
||||
throws Efni.Error, IOError {
|
||||
uint max_entries = compute_max_entries (level, p);
|
||||
uint shift = address_shift_at_level (level, p.granule);
|
||||
|
||||
@@ -286,7 +288,7 @@ namespace Frida.Barebone {
|
||||
// A kernel using permission indirection reads an index out of those bits instead, leaving
|
||||
// AP to say nothing at all, so both kinds of page are granted by sampling one the kernel
|
||||
// already made that way and replaying its exact attribute encoding.
|
||||
public async void learn_permission_templates (uint64 code_va, Cancellable? cancellable) throws Error, IOError {
|
||||
public async void learn_permission_templates (uint64 code_va, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
code_template_descriptor = yield read_level3_descriptor (code_va, cancellable);
|
||||
code_template_known = true;
|
||||
|
||||
@@ -295,7 +297,7 @@ namespace Frida.Barebone {
|
||||
data_template_known = true;
|
||||
}
|
||||
|
||||
public override async uint64 translate_address (uint64 va, Cancellable? cancellable) throws Error, IOError {
|
||||
public override async uint64 translate_address (uint64 va, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
MMUParameters p = yield load_mmu_parameters (cancellable);
|
||||
uint64 descriptor = yield read_level3_descriptor (va, cancellable);
|
||||
uint64 page_mask = (1ULL << inpage_bits_for_granule (p.granule)) - 1;
|
||||
@@ -303,7 +305,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public override async Bytes read_virtual (uint64 va, size_t size, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
if (physical_memory == null)
|
||||
return yield debugger.read_byte_array (va, size, cancellable);
|
||||
|
||||
@@ -314,7 +316,7 @@ namespace Frida.Barebone {
|
||||
uint64 cur_va = va + offset;
|
||||
uint64 pa = yield translate_address (cur_va, cancellable);
|
||||
if (!physical_memory.contains (pa))
|
||||
throw new Error.NOT_SUPPORTED ("Address 0x%" + uint64.FORMAT_MODIFIER + "x is a device, not memory", cur_va);
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Address 0x%" + uint64.FORMAT_MODIFIER + "x is a device, not memory", cur_va);
|
||||
size_t chunk = size_t.min ((size_t) (p.granule - (cur_va & (p.granule - 1))), size - offset);
|
||||
taken.append (physical_memory.read (pa, chunk));
|
||||
offset += chunk;
|
||||
@@ -323,7 +325,7 @@ namespace Frida.Barebone {
|
||||
return ByteArray.free_to_bytes ((owned) taken);
|
||||
}
|
||||
|
||||
public override async void write_virtual (uint64 va, uint8[] data, Cancellable? cancellable) throws Error, IOError {
|
||||
public override async void write_virtual (uint64 va, uint8[] data, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (physical_memory == null) {
|
||||
yield debugger.write_byte_array (va, new Bytes (data), cancellable);
|
||||
return;
|
||||
@@ -340,13 +342,13 @@ namespace Frida.Barebone {
|
||||
}
|
||||
}
|
||||
|
||||
private async Buffer read_physical_buffer (uint64 pa, size_t size, Cancellable? cancellable) throws Error, IOError {
|
||||
private async Buffer read_physical_buffer (uint64 pa, size_t size, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (physical_memory != null && physical_memory.contains (pa))
|
||||
return debugger.make_buffer (new Bytes (physical_memory.read (pa, size)));
|
||||
return yield debugger.read_buffer (pa, size, cancellable);
|
||||
}
|
||||
|
||||
private async void write_physical_buffer (uint64 pa, Bytes data, Cancellable? cancellable) throws Error, IOError {
|
||||
private async void write_physical_buffer (uint64 pa, Bytes data, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (physical_memory != null && physical_memory.contains (pa)) {
|
||||
physical_memory.write (pa, data.get_data ());
|
||||
return;
|
||||
@@ -354,13 +356,13 @@ namespace Frida.Barebone {
|
||||
yield debugger.write_byte_array (pa, data, cancellable);
|
||||
}
|
||||
|
||||
public async uint8[] read_physical (uint64 pa, size_t size, Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint8[] read_physical (uint64 pa, size_t size, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (physical_memory != null && physical_memory.contains (pa))
|
||||
return physical_memory.read (pa, size);
|
||||
return yield read_physical_via_stub (pa, size, cancellable);
|
||||
}
|
||||
|
||||
public async void write_physical (uint64 pa, uint8[] data, Cancellable? cancellable) throws Error, IOError {
|
||||
public async void write_physical (uint64 pa, uint8[] data, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (physical_memory != null && physical_memory.contains (pa)) {
|
||||
physical_memory.write (pa, data);
|
||||
return;
|
||||
@@ -376,7 +378,7 @@ namespace Frida.Barebone {
|
||||
throw_if_failed (failure);
|
||||
}
|
||||
|
||||
public async uint8[] read_physical_via_stub (uint64 pa, size_t size, Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint8[] read_physical_via_stub (uint64 pa, size_t size, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
bool was_running = yield enter_physical_addressing (debugger, cancellable);
|
||||
uint8[]? data = null;
|
||||
GLib.Error? failure = null;
|
||||
@@ -391,7 +393,7 @@ namespace Frida.Barebone {
|
||||
return data;
|
||||
}
|
||||
|
||||
public async uint64 read_level3_descriptor (uint64 va, Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint64 read_level3_descriptor (uint64 va, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
MMUParameters p = yield load_mmu_parameters (cancellable);
|
||||
bool was_running = yield begin_physical_addressing (cancellable);
|
||||
uint64 descriptor = 0;
|
||||
@@ -416,12 +418,12 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public override async void protect_pages_leaving_the_flush (uint64 virtual_address, size_t size,
|
||||
Gum.PageProtection prot, Cancellable? cancellable) throws Error, IOError {
|
||||
Gum.PageProtection prot, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
yield write_page_protection (virtual_address, size, prot, cancellable);
|
||||
}
|
||||
|
||||
public async void protect_pages (uint64 virtual_address, size_t size, Gum.PageProtection prot, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
if (!mmu_registers_available) {
|
||||
yield set_pages_protection (virtual_address, size, prot, cancellable);
|
||||
return;
|
||||
@@ -436,7 +438,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void ensure_level3_coverage (uint64 virtual_address, size_t size, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
if (code_allocator == null)
|
||||
return;
|
||||
|
||||
@@ -469,7 +471,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async Gee.List<BlockMapping> locate_blocks (uint64 start_va, uint64 end_va, MMUParameters p,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var blocks = new Gee.ArrayList<BlockMapping> ();
|
||||
|
||||
bool was_running = yield begin_physical_addressing (cancellable);
|
||||
@@ -496,7 +498,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async BlockMapping? locate_block (uint64 va, MMUParameters p, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
uint64 table_pa = p.tt1;
|
||||
uint level = p.first_level;
|
||||
while (true) {
|
||||
@@ -522,7 +524,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void split_block (BlockMapping block, uint64 table_pa, MMUParameters p, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
uint sub_level = block.level + 1;
|
||||
uint64 sub_size = (sub_level == 3)
|
||||
? (uint64) 1 << inpage_bits_for_granule (p.granule)
|
||||
@@ -545,7 +547,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async uint64 resolve_physical_address (uint64 va, MMUParameters p, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
uint64 table_pa = p.tt1;
|
||||
uint level = p.first_level;
|
||||
while (true) {
|
||||
@@ -565,7 +567,7 @@ namespace Frida.Barebone {
|
||||
return (raw & INT48_MASK & ~(span - 1)) | (va & (span - 1));
|
||||
}
|
||||
if (desc.kind != TABLE)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to resolve physical address for 0x%" + uint64.FORMAT_MODIFIER + "x", va);
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unable to resolve physical address for 0x%" + uint64.FORMAT_MODIFIER + "x", va);
|
||||
|
||||
table_pa = desc.target_address;
|
||||
level++;
|
||||
@@ -576,9 +578,9 @@ namespace Frida.Barebone {
|
||||
// clearing write before adding execute; the helpers take a page-aligned base and a page
|
||||
// count, and handle the TLB and cache maintenance themselves.
|
||||
private async void set_pages_protection (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (set_memory_x == 0)
|
||||
throw new Error.NOT_SUPPORTED ("Kernel set_memory_* helpers are unavailable");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Kernel set_memory_* helpers are unavailable");
|
||||
|
||||
uint64 aligned = virtual_address & ~(uint64) 0xfff;
|
||||
uint num_pages = (uint) (((virtual_address + size + 0xfff) & ~(uint64) 0xfff) - aligned) / 4096;
|
||||
@@ -594,7 +596,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void write_page_protection (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
MMUParameters p = yield load_mmu_parameters (cancellable);
|
||||
|
||||
bool was_running = yield begin_physical_addressing (cancellable);
|
||||
@@ -613,7 +615,7 @@ namespace Frida.Barebone {
|
||||
throw_if_failed (failure);
|
||||
}
|
||||
|
||||
private async void flush_translations (Cancellable? cancellable) throws Error, IOError {
|
||||
private async void flush_translations (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (flush_stub == null) {
|
||||
flush_stub = yield code_allocator.allocate (code_allocator.page_size, code_allocator.page_size,
|
||||
cancellable);
|
||||
@@ -631,7 +633,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void grant_execution (uint64 virtual_address, size_t size, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
yield ensure_level3_coverage (virtual_address, size, cancellable);
|
||||
|
||||
MMUParameters p = yield load_mmu_parameters (cancellable);
|
||||
@@ -654,7 +656,7 @@ namespace Frida.Barebone {
|
||||
|
||||
// The bridge reads and writes guest physical memory directly, so the stub's
|
||||
// physical-addressing mode, which requires a halted target, is unnecessary.
|
||||
private async bool begin_physical_addressing (Cancellable? cancellable) throws Error, IOError {
|
||||
private async bool begin_physical_addressing (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (physical_memory != null)
|
||||
return false;
|
||||
|
||||
@@ -662,21 +664,21 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void end_physical_addressing (bool was_running, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
if (physical_memory != null)
|
||||
return;
|
||||
|
||||
yield leave_physical_addressing (debugger, was_running, cancellable);
|
||||
}
|
||||
|
||||
private async MMUParameters load_mmu_parameters (Cancellable? cancellable) throws Error, IOError {
|
||||
private async MMUParameters load_mmu_parameters (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (cached_mmu_parameters == null)
|
||||
cached_mmu_parameters = yield MMUParameters.load (debugger, cancellable);
|
||||
return cached_mmu_parameters;
|
||||
}
|
||||
|
||||
private async void perform_protect_pages (uint64 start_va, uint num_pages, Gum.PageProtection prot, MMUParameters p,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var table_cache = new TableWalkCache ();
|
||||
uint pages_processed = 0;
|
||||
|
||||
@@ -708,7 +710,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
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 {
|
||||
uint64 table_pa, MMUParameters p, Cancellable? cancellable) throws Efni.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;
|
||||
@@ -734,7 +736,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async uint64 find_level3_table (uint64 va, MMUParameters p, TableWalkCache cache, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.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);
|
||||
@@ -743,7 +745,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async uint64 walk_to_level3 (uint64 va, uint64 start_table_pa, uint start_level, MMUParameters p,
|
||||
TableWalkCache cache, Cancellable? cancellable) throws Error, IOError {
|
||||
TableWalkCache cache, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
uint64 table_pa = start_table_pa;
|
||||
uint level = start_level;
|
||||
|
||||
@@ -760,7 +762,7 @@ namespace Frida.Barebone {
|
||||
Descriptor desc = Descriptor.parse (raw, level, p.granule);
|
||||
|
||||
if (desc.kind != TABLE)
|
||||
throw new Error.NOT_SUPPORTED ("Walk failed at level %u", level);
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Walk failed at level %u", level);
|
||||
|
||||
table_pa = desc.target_address;
|
||||
level++;
|
||||
@@ -770,7 +772,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void clear_pxn_table_bits_for_va (uint64 va, MMUParameters p, TableWalkCache cache, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
uint64 table_pa = p.tt1;
|
||||
for (uint level = p.first_level; level != 3; level++) {
|
||||
uint entries = compute_max_entries (level, p);
|
||||
@@ -847,7 +849,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async Gee.List<uint64?> scan_ranges (Gee.List<Gum.MemoryRange?> ranges, MatchPattern pattern, uint max_matches,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
unowned uint8[] scanner_blob = Data.Barebone.get_memory_scanner_arm64_elf_blob ().data;
|
||||
|
||||
var raw_scanner = new Bytes.static (scanner_blob);
|
||||
@@ -856,7 +858,7 @@ namespace Frida.Barebone {
|
||||
try {
|
||||
scanner = new Gum.ElfModule.from_blob (raw_scanner);
|
||||
} catch (Gum.Error e) {
|
||||
throw new Error.NOT_SUPPORTED ("%s", e.message);
|
||||
throw new Efni.Error.NOT_SUPPORTED ("%s", e.message);
|
||||
}
|
||||
|
||||
size_t vm_size = (size_t) scanner.mapped_size;
|
||||
@@ -895,7 +897,7 @@ namespace Frida.Barebone {
|
||||
|
||||
RangeDetails? stack_range = writable_ranges.first_match (r => r.contains_virtual_address (old_sp));
|
||||
if (stack_range == null)
|
||||
throw new Error.NOT_SUPPORTED ("Unable to find stack memory range");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unable to find stack memory range");
|
||||
|
||||
uint64 module_pa;
|
||||
size_t logical_page_size = 4096;
|
||||
@@ -950,7 +952,7 @@ namespace Frida.Barebone {
|
||||
DebuggerBreakpoint bp = yield debugger.add_breakpoint (SOFT, landing_zone_va, 4, cancellable);
|
||||
DebuggerException ex = yield debugger.continue_until_exception (cancellable);
|
||||
if (ex.breakpoint != bp)
|
||||
throw new Error.NOT_SUPPORTED ("Breakpoint did not trigger; please file a bug");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Breakpoint did not trigger; please file a bug");
|
||||
yield bp.remove (cancellable);
|
||||
|
||||
var num_matches = (uint) yield thread.read_register ("x0", cancellable);
|
||||
@@ -972,7 +974,7 @@ namespace Frida.Barebone {
|
||||
return matches;
|
||||
}
|
||||
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Error {
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Efni.Error {
|
||||
Gum.ElfArm64Relocation type = (Gum.ElfArm64Relocation) r.type;
|
||||
switch (type) {
|
||||
case ABS64:
|
||||
@@ -986,14 +988,14 @@ namespace Frida.Barebone {
|
||||
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));
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unsupported relocation type: %s",
|
||||
Efni.Marshal.enum_to_nick<Gum.ElfArm64Relocation> (type));
|
||||
}
|
||||
}
|
||||
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (args.length > 8)
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported number of arguments; please open a PR");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unsupported number of arguments; please open a PR");
|
||||
|
||||
bool was_running = debugger.state != STOPPED;
|
||||
if (was_running)
|
||||
@@ -1024,7 +1026,16 @@ namespace Frida.Barebone {
|
||||
|
||||
yield thread.write_registers (regs, cancellable);
|
||||
|
||||
DebuggerThread landed = yield run_until_pc (landing_zone, cancellable);
|
||||
var gdb = debugger as GDB.Client;
|
||||
if (gdb != null && !gdb.suppress_solo)
|
||||
gdb.solo_thread_id = thread.id;
|
||||
DebuggerThread landed = thread;
|
||||
try {
|
||||
landed = yield run_until_pc (landing_zone, cancellable);
|
||||
} finally {
|
||||
if (gdb != null)
|
||||
gdb.solo_thread_id = null;
|
||||
}
|
||||
uint64 retval = yield landed.read_register ("x0", cancellable);
|
||||
|
||||
yield restore_registers (thread, landed, saved_regs, cancellable);
|
||||
@@ -1035,7 +1046,7 @@ namespace Frida.Barebone {
|
||||
return retval;
|
||||
}
|
||||
|
||||
public async void execute (uint64 start, uint64 end, Cancellable? cancellable) throws Error, IOError {
|
||||
public async void execute (uint64 start, uint64 end, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
bool was_running = debugger.state != STOPPED;
|
||||
if (was_running)
|
||||
yield debugger.stop (cancellable);
|
||||
@@ -1062,13 +1073,13 @@ namespace Frida.Barebone {
|
||||
// reschedule onto another core, and the stub identifies threads by core; nothing else reaches
|
||||
// these addresses (a cold landing zone, or the scheduler with a predicate), so whichever
|
||||
// thread stops there is ours.
|
||||
public async DebuggerThread run_until_pc (uint64 address, Cancellable? cancellable) throws Error, IOError {
|
||||
public async DebuggerThread run_until_pc (uint64 address, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
DebuggerBreakpoint bp = yield debugger.add_breakpoint (SOFT, address, 4, cancellable);
|
||||
DebuggerException ex = null;
|
||||
int64 deadline = get_monotonic_time () + LANDING_TIMEOUT_USEC;
|
||||
do {
|
||||
if (get_monotonic_time () >= deadline)
|
||||
throw new Error.TIMED_OUT ("Timed out waiting for the call to return");
|
||||
throw new Efni.Error.TIMED_OUT ("Timed out waiting for the call to return");
|
||||
|
||||
ex = yield debugger.continue_until_exception (cancellable);
|
||||
} while (ex.breakpoint != bp);
|
||||
@@ -1080,7 +1091,7 @@ namespace Frida.Barebone {
|
||||
// points at that core's per-processor data. Handing it the register of the core we began
|
||||
// on would make every later access reach the wrong processor.
|
||||
private async void restore_registers (DebuggerThread origin, DebuggerThread landed,
|
||||
Gee.Map<string, Variant> saved, Cancellable? cancellable) throws Error, IOError {
|
||||
Gee.Map<string, Variant> saved, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var restored = saved;
|
||||
if (landed.id != origin.id) {
|
||||
restored = new Gee.HashMap<string, Variant> ();
|
||||
@@ -1091,7 +1102,7 @@ namespace Frida.Barebone {
|
||||
yield landed.write_registers (restored, cancellable);
|
||||
}
|
||||
|
||||
public async CallFrame load_call_frame (DebuggerThread thread, uint arity, Cancellable? cancellable) throws Error, IOError {
|
||||
public async CallFrame load_call_frame (DebuggerThread thread, uint arity, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var regs = yield thread.read_registers (cancellable);
|
||||
|
||||
Buffer? stack = null;
|
||||
@@ -1194,7 +1205,7 @@ namespace Frida.Barebone {
|
||||
stack_state = MODIFIED;
|
||||
}
|
||||
|
||||
public async void commit (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void commit (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (regs.get_data<bool> ("dirty"))
|
||||
yield thread.write_registers (regs, cancellable);
|
||||
|
||||
@@ -1212,7 +1223,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async InlineHook create_inline_hook (uint64 target, uint64 handler, Allocator allocator, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
size_t page_size = allocator.page_size;
|
||||
var allocation = yield allocator.allocate (page_size, page_size, cancellable);
|
||||
uint64 code_va = allocation.virtual_address;
|
||||
@@ -1326,7 +1337,7 @@ namespace Frida.Barebone {
|
||||
this.debugger = debugger;
|
||||
}
|
||||
|
||||
public async void destroy (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void destroy (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (state == DESTROYED)
|
||||
return;
|
||||
|
||||
@@ -1343,16 +1354,16 @@ namespace Frida.Barebone {
|
||||
yield debugger.resume (cancellable);
|
||||
}
|
||||
|
||||
public async void enable (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void enable (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (state == ENABLED)
|
||||
return;
|
||||
if (state != DISABLED)
|
||||
throw new Error.INVALID_OPERATION ("Invalid operation");
|
||||
throw new Efni.Error.INVALID_OPERATION ("Invalid operation");
|
||||
yield debugger.write_byte_array (target, new_target_code, cancellable);
|
||||
state = ENABLED;
|
||||
}
|
||||
|
||||
public async void disable (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void disable (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (state != ENABLED)
|
||||
return;
|
||||
yield debugger.write_byte_array (target, old_target_code, cancellable);
|
||||
@@ -1370,10 +1381,10 @@ namespace Frida.Barebone {
|
||||
public bool sprr_enabled;
|
||||
public uint64 sprr_perm;
|
||||
|
||||
public static async MMUParameters load (Debugger debugger, Cancellable? cancellable) throws Error, IOError {
|
||||
public static async MMUParameters load (Debugger debugger, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
DebuggerException? exception = debugger.exception;
|
||||
if (exception == null)
|
||||
throw new Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
throw new Efni.Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
DebuggerThread thread = exception.thread;
|
||||
|
||||
MMURegisters regs = yield MMURegisters.read (thread, cancellable);
|
||||
@@ -1413,7 +1424,7 @@ namespace Frida.Barebone {
|
||||
public uint64 sprr_config;
|
||||
public uint64 sprr_perm;
|
||||
|
||||
public static async MMURegisters read (DebuggerThread thread, Cancellable? cancellable) throws Error, IOError {
|
||||
public static async MMURegisters read (DebuggerThread thread, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var regs = new MMURegisters ();
|
||||
|
||||
Debugger client = thread.debugger;
|
||||
@@ -1438,14 +1449,14 @@ namespace Frida.Barebone {
|
||||
// The stub serves no system register, and the monitor command that would
|
||||
// print them aborts the VM whenever another processor is somewhere it
|
||||
// cannot be read from, so leave the caller to manage without them.
|
||||
throw new Error.NOT_SUPPORTED ("Parallels serves no system register");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Parallels serves no system register");
|
||||
} 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) {
|
||||
} catch (Efni.Error e) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1578,9 +1589,9 @@ namespace Frida.Barebone {
|
||||
this.debugger = debugger;
|
||||
}
|
||||
|
||||
public async void deallocate (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void deallocate (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (old_descriptors == null)
|
||||
throw new Error.INVALID_OPERATION ("Already deallocated");
|
||||
throw new Efni.Error.INVALID_OPERATION ("Already deallocated");
|
||||
Bytes d = old_descriptors;
|
||||
old_descriptors = null;
|
||||
bool was_running = yield enter_physical_addressing (debugger, cancellable);
|
||||
@@ -1601,7 +1612,7 @@ namespace Frida.Barebone {
|
||||
64K = 65536
|
||||
}
|
||||
|
||||
private static Granule granule_from_tg1 (uint tg1) throws Error {
|
||||
private static Granule granule_from_tg1 (uint tg1) throws Efni.Error {
|
||||
switch (tg1) {
|
||||
case 1:
|
||||
return 16K;
|
||||
@@ -1610,7 +1621,7 @@ namespace Frida.Barebone {
|
||||
case 3:
|
||||
return 64K;
|
||||
default:
|
||||
throw new Error.PROTOCOL ("Invalid TG1 value");
|
||||
throw new Efni.Error.PROTOCOL ("Invalid TG1 value");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1724,7 +1735,7 @@ namespace Frida.Barebone {
|
||||
return prot;
|
||||
}
|
||||
|
||||
private uint64 apply_protection_bits (uint64 descriptor, Gum.PageProtection prot, MMUParameters p) throws Error {
|
||||
private uint64 apply_protection_bits (uint64 descriptor, Gum.PageProtection prot, MMUParameters p) throws Efni.Error {
|
||||
bool want_exec = (prot & Gum.PageProtection.EXECUTE) != 0;
|
||||
if (want_exec && code_template_known)
|
||||
return apply_code_template (descriptor, p);
|
||||
@@ -1777,7 +1788,7 @@ namespace Frida.Barebone {
|
||||
return result;
|
||||
}
|
||||
|
||||
private static uint find_sprr_index_for_permissions (Gum.PageProtection prot, MMUParameters p) throws Error {
|
||||
private static uint find_sprr_index_for_permissions (Gum.PageProtection prot, MMUParameters p) throws Efni.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;
|
||||
@@ -1810,7 +1821,7 @@ namespace Frida.Barebone {
|
||||
return i;
|
||||
}
|
||||
|
||||
throw new Error.INVALID_ARGUMENT ("No suitable SPRR slot found for protection 0x%x", prot);
|
||||
throw new Efni.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) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public sealed class UnknownMachine : Object, Machine {
|
||||
@@ -18,43 +20,43 @@ namespace Frida.Barebone {
|
||||
Object (debugger: debugger);
|
||||
}
|
||||
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Error, IOError {
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
return 4096;
|
||||
}
|
||||
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Not yet supported");
|
||||
}
|
||||
|
||||
public async void enumerate_ranges (Gum.PageProtection prot, FoundRangeFunc func, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
}
|
||||
|
||||
public async Allocation allocate_pages (Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
throws Efni.Error, IOError {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Not yet supported");
|
||||
}
|
||||
|
||||
public async void protect_pages (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Not yet 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 ();
|
||||
uint max_matches, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Not yet supported");
|
||||
}
|
||||
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Error {
|
||||
throw_not_supported ();
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Efni.Error {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Not yet supported");
|
||||
}
|
||||
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Not yet supported");
|
||||
}
|
||||
|
||||
public async CallFrame load_call_frame (DebuggerThread thread, uint arity, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
var regs = yield thread.read_registers (cancellable);
|
||||
|
||||
return new UnknownCallFrame (thread, regs);
|
||||
@@ -101,7 +103,7 @@ namespace Frida.Barebone {
|
||||
public void force_return () {
|
||||
}
|
||||
|
||||
public async void commit (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void commit (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (regs.get_data<bool> ("dirty"))
|
||||
yield thread.write_registers (regs, cancellable);
|
||||
}
|
||||
@@ -116,8 +118,8 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async InlineHook create_inline_hook (uint64 target, uint64 handler, Allocator allocator, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
throws Efni.Error, IOError {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Not yet supported");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public sealed class IA32Machine : Object, Machine {
|
||||
@@ -31,7 +33,7 @@ namespace Frida.Barebone {
|
||||
page_tables = new X86PageTables (debugger);
|
||||
}
|
||||
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Error, IOError {
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
return 4096;
|
||||
}
|
||||
|
||||
@@ -43,10 +45,10 @@ namespace Frida.Barebone {
|
||||
private const uint64 USER_PRIVILEGE = 3;
|
||||
private const int64 LANDING_TIMEOUT_USEC = 60000000;
|
||||
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
DebuggerException? exception = debugger.exception;
|
||||
if (exception == null)
|
||||
throw new Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
throw new Efni.Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
DebuggerThread thread = exception.thread;
|
||||
|
||||
var cs = yield thread.read_register ("cs", cancellable);
|
||||
@@ -55,7 +57,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async void enumerate_ranges (Gum.PageProtection prot, FoundRangeFunc func, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
foreach (RangeDetails r in coalesce_ranges (yield page_tables.collect_ranges (cancellable))) {
|
||||
if ((r.protection & prot) != prot)
|
||||
continue;
|
||||
@@ -65,19 +67,19 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async Allocation allocate_pages (Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
return yield page_tables.map (physical_addresses, cancellable);
|
||||
}
|
||||
|
||||
public async void protect_pages (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
yield page_tables.protect (virtual_address, size, prot, cancellable);
|
||||
}
|
||||
|
||||
// Read the memory and do the match here. A script asks about small ranges, thus a scanner in
|
||||
// the guest would cost more round trips than it saves.
|
||||
public async Gee.List<uint64?> scan_ranges (Gee.List<Gum.MemoryRange?> ranges, MatchPattern pattern, uint max_matches,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var matches = new Gee.ArrayList<uint64?> ();
|
||||
|
||||
foreach (Gum.MemoryRange r in ranges) {
|
||||
@@ -90,7 +92,7 @@ namespace Frida.Barebone {
|
||||
Bytes chunk;
|
||||
try {
|
||||
chunk = yield debugger.read_byte_array (cursor, chunk_size, cancellable);
|
||||
} catch (Error e) {
|
||||
} catch (Efni.Error e) {
|
||||
cursor += chunk_size;
|
||||
continue;
|
||||
}
|
||||
@@ -113,7 +115,7 @@ namespace Frida.Barebone {
|
||||
// keep the overlap at the boundaries small.
|
||||
private const size_t SCAN_CHUNK_SIZE = 256 * 1024;
|
||||
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Error {
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Efni.Error {
|
||||
Gum.ElfIA32Relocation type = (Gum.ElfIA32Relocation) r.type;
|
||||
switch (type) {
|
||||
case NONE:
|
||||
@@ -132,12 +134,12 @@ namespace Frida.Barebone {
|
||||
// Both ends of the displacement move by the same amount.
|
||||
break;
|
||||
default:
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported relocation type: %s",
|
||||
Marshal.enum_to_nick<Gum.ElfIA32Relocation> (type));
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unsupported relocation type: %s",
|
||||
Efni.Marshal.enum_to_nick<Gum.ElfIA32Relocation> (type));
|
||||
}
|
||||
}
|
||||
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
bool was_running = debugger.state != STOPPED;
|
||||
if (was_running)
|
||||
yield debugger.stop (cancellable);
|
||||
@@ -178,7 +180,7 @@ namespace Frida.Barebone {
|
||||
int64 deadline = get_monotonic_time () + LANDING_TIMEOUT_USEC;
|
||||
while (true) {
|
||||
if (get_monotonic_time () >= deadline)
|
||||
throw new Error.TIMED_OUT ("Timed out waiting for the call to return");
|
||||
throw new Efni.Error.TIMED_OUT ("Timed out waiting for the call to return");
|
||||
|
||||
ex = yield debugger.continue_until_exception (cancellable);
|
||||
if (ex.breakpoint != bp)
|
||||
@@ -200,7 +202,7 @@ namespace Frida.Barebone {
|
||||
return retval;
|
||||
}
|
||||
|
||||
public async CallFrame load_call_frame (DebuggerThread thread, uint arity, Cancellable? cancellable) throws Error, IOError {
|
||||
public async CallFrame load_call_frame (DebuggerThread thread, uint arity, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var regs = yield thread.read_registers (cancellable);
|
||||
|
||||
uint64 original_esp = regs["esp"].get_uint64 ();
|
||||
@@ -289,7 +291,7 @@ namespace Frida.Barebone {
|
||||
stack_state = MODIFIED;
|
||||
}
|
||||
|
||||
public async void commit (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void commit (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (regs.get_data<bool> ("dirty"))
|
||||
yield thread.write_registers (regs, cancellable);
|
||||
|
||||
@@ -307,11 +309,11 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async InlineHook create_inline_hook (uint64 target, uint64 handler, Allocator allocator, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
return yield X86InlineHook.create (target, handler, IA32, allocator, debugger, cancellable);
|
||||
}
|
||||
|
||||
public override async uint64 translate_address (uint64 va, Cancellable? cancellable) throws Error, IOError {
|
||||
public override async uint64 translate_address (uint64 va, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
return yield page_tables.translate (va, cancellable);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public enum CallingConvention {
|
||||
@@ -71,17 +73,17 @@ namespace Frida.Barebone {
|
||||
page_tables = new X86PageTables (debugger);
|
||||
}
|
||||
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Error, IOError {
|
||||
public async size_t query_page_size (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
return 4096;
|
||||
}
|
||||
|
||||
private const uint64 CODE_SELECTOR_PRIVILEGE = 3;
|
||||
private const uint64 USER_PRIVILEGE = 3;
|
||||
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint query_exception_level (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
DebuggerException? exception = debugger.exception;
|
||||
if (exception == null)
|
||||
throw new Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
throw new Efni.Error.INVALID_OPERATION ("Unable to query in current state");
|
||||
DebuggerThread thread = exception.thread;
|
||||
|
||||
var cs = yield thread.read_register ("cs", cancellable);
|
||||
@@ -90,7 +92,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async void enumerate_ranges (Gum.PageProtection prot, FoundRangeFunc func, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
foreach (RangeDetails r in coalesce_ranges (yield page_tables.collect_ranges (cancellable))) {
|
||||
if ((r.protection & prot) != prot)
|
||||
continue;
|
||||
@@ -100,12 +102,12 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async Allocation allocate_pages (Gee.List<uint64?> physical_addresses, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
return yield page_tables.map (physical_addresses, cancellable);
|
||||
}
|
||||
|
||||
public async void protect_pages (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (set_memory_x != 0) {
|
||||
yield set_pages_protection (virtual_address, size, prot, cancellable);
|
||||
return;
|
||||
@@ -115,7 +117,7 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
private async void set_pages_protection (uint64 virtual_address, size_t size, Gum.PageProtection prot,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
uint64 aligned = virtual_address & ~(uint64) 0xfff;
|
||||
uint num_pages = (uint) (((virtual_address + size + 0xfff) & ~(uint64) 0xfff) - aligned) / 4096;
|
||||
|
||||
@@ -130,11 +132,11 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
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 ();
|
||||
Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Not yet supported");
|
||||
}
|
||||
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Error {
|
||||
public void apply_relocation (Gum.ElfRelocationDetails r, uint64 base_va, Buffer relocated) throws Efni.Error {
|
||||
Gum.ElfX64Relocation type = (Gum.ElfX64Relocation) r.type;
|
||||
switch (type) {
|
||||
case NONE:
|
||||
@@ -157,8 +159,8 @@ namespace Frida.Barebone {
|
||||
// Both ends of the displacement move by the same amount.
|
||||
break;
|
||||
default:
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported relocation type: %s",
|
||||
Marshal.enum_to_nick<Gum.ElfX64Relocation> (type));
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unsupported relocation type: %s",
|
||||
Efni.Marshal.enum_to_nick<Gum.ElfX64Relocation> (type));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,9 +169,9 @@ namespace Frida.Barebone {
|
||||
return true;
|
||||
}
|
||||
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Error, IOError {
|
||||
public async uint64 invoke (uint64 impl, uint64[] args, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (args.length > arg_reg_names.length)
|
||||
throw new Error.NOT_SUPPORTED ("Unsupported number of arguments; please open a PR");
|
||||
throw new Efni.Error.NOT_SUPPORTED ("Unsupported number of arguments; please open a PR");
|
||||
|
||||
bool was_running = debugger.state != STOPPED;
|
||||
if (was_running)
|
||||
@@ -206,7 +208,7 @@ namespace Frida.Barebone {
|
||||
int64 deadline = get_monotonic_time () + LANDING_TIMEOUT_USEC;
|
||||
while (true) {
|
||||
if (get_monotonic_time () >= deadline)
|
||||
throw new Error.TIMED_OUT ("Timed out waiting for the call to return");
|
||||
throw new Efni.Error.TIMED_OUT ("Timed out waiting for the call to return");
|
||||
|
||||
ex = yield debugger.continue_until_exception (cancellable);
|
||||
if (ex.breakpoint != bp)
|
||||
@@ -227,7 +229,7 @@ namespace Frida.Barebone {
|
||||
return retval;
|
||||
}
|
||||
|
||||
public async CallFrame load_call_frame (DebuggerThread thread, uint arity, Cancellable? cancellable) throws Error, IOError {
|
||||
public async CallFrame load_call_frame (DebuggerThread thread, uint arity, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
var regs = yield thread.read_registers (cancellable);
|
||||
|
||||
uint64 original_rsp = regs["rsp"].get_uint64 ();
|
||||
@@ -353,7 +355,7 @@ namespace Frida.Barebone {
|
||||
stack_state = MODIFIED;
|
||||
}
|
||||
|
||||
public async void commit (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void commit (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
if (regs.get_data<bool> ("dirty"))
|
||||
yield thread.write_registers (regs, cancellable);
|
||||
|
||||
@@ -371,11 +373,11 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public async InlineHook create_inline_hook (uint64 target, uint64 handler, Allocator allocator, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
return yield X86InlineHook.create (target, handler, AMD64, allocator, debugger, cancellable);
|
||||
}
|
||||
|
||||
public override async uint64 translate_address (uint64 va, Cancellable? cancellable) throws Error, IOError {
|
||||
public override async uint64 translate_address (uint64 va, Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
return yield page_tables.translate (va, cancellable);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
namespace Frida {
|
||||
public sealed class BareboneHostSessionBackend : Object, HostSessionBackend {
|
||||
private BareboneHostSessionProvider? provider;
|
||||
@@ -62,125 +64,132 @@ namespace Frida {
|
||||
|
||||
public async HostSession create (HostSessionHub hub, HostSessionOptions? options, owned ConnectingFunc connecting,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
if (host_session != null)
|
||||
throw new Error.INVALID_OPERATION ("Already created");
|
||||
try {
|
||||
if (host_session != null)
|
||||
throw new Error.INVALID_OPERATION ("Already created");
|
||||
|
||||
BareboneConfig? config = null;
|
||||
if (options != null) {
|
||||
Value? val = options.map["config"];
|
||||
if (val != null) {
|
||||
config = (BareboneConfig) val.get_object ();
|
||||
config.check ();
|
||||
BareboneConfig? config = null;
|
||||
if (options != null) {
|
||||
Value? val = options.map["config"];
|
||||
if (val != null) {
|
||||
config = (BareboneConfig) val.get_object ();
|
||||
config.check ();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unowned string? config_path = Environment.get_variable ("FRIDA_BAREBONE_CONFIG");
|
||||
if (config == null && config_path != null) {
|
||||
unowned string? config_path = Environment.get_variable ("FRIDA_BAREBONE_CONFIG");
|
||||
if (config == null && config_path != null) {
|
||||
try {
|
||||
var config_data = yield FS.read_all_text (File.new_for_path (config_path), cancellable);
|
||||
var cfg = (BareboneConfig) Json.gobject_from_data (typeof (BareboneConfig), config_data);
|
||||
cfg.check ();
|
||||
config = cfg;
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("Unable to load %s: %s", config_path, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
if (config == null)
|
||||
config = new BareboneConfig ();
|
||||
|
||||
var resident_agent = config.agent as BareboneResidentAgentConfig;
|
||||
if (resident_agent != null) {
|
||||
host_session = yield attach_to_resident_agent (resident_agent.transport, cancellable);
|
||||
host_session.agent_session_detached.connect (on_agent_session_detached);
|
||||
|
||||
return host_session;
|
||||
}
|
||||
|
||||
SocketConnectable connectable;
|
||||
try {
|
||||
var config_data = yield FS.read_all_text (File.new_for_path (config_path), cancellable);
|
||||
var cfg = (BareboneConfig) Json.gobject_from_data (typeof (BareboneConfig), config_data);
|
||||
cfg.check ();
|
||||
config = cfg;
|
||||
BareboneConnectionConfig c = config.connection;
|
||||
connectable = NetworkAddress.parse (c.host, c.port);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("Unable to load %s: %s", config_path, e.message);
|
||||
}
|
||||
}
|
||||
|
||||
if (config == null)
|
||||
config = new BareboneConfig ();
|
||||
connecting ("Connecting to the debugger", 0.0);
|
||||
|
||||
var resident_agent = config.agent as BareboneResidentAgentConfig;
|
||||
if (resident_agent != null) {
|
||||
host_session = yield attach_to_resident_agent (resident_agent.transport, cancellable);
|
||||
host_session.agent_session_detached.connect (on_agent_session_detached);
|
||||
if (config.connection.flavor == BareboneStubFlavor.VIRTUALBOX_CONSOLE) {
|
||||
var console_debugger = yield Barebone.VirtualBoxDebugger.open (config.connection.host,
|
||||
config.connection.port, cancellable);
|
||||
host_session = yield establish (config, console_debugger, (owned) connecting, cancellable);
|
||||
host_session.agent_session_detached.connect (on_agent_session_detached);
|
||||
|
||||
return host_session;
|
||||
}
|
||||
|
||||
SocketConnectable connectable;
|
||||
try {
|
||||
BareboneConnectionConfig c = config.connection;
|
||||
connectable = NetworkAddress.parse (c.host, c.port);
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.INVALID_ARGUMENT ("Unable to load %s: %s", config_path, e.message);
|
||||
}
|
||||
|
||||
connecting ("Connecting to the debugger", 0.0);
|
||||
|
||||
if (config.connection.flavor == BareboneStubFlavor.VIRTUALBOX_CONSOLE) {
|
||||
var console_debugger = yield Barebone.VirtualBoxDebugger.open (config.connection.host,
|
||||
config.connection.port, cancellable);
|
||||
host_session = yield establish (config, console_debugger, (owned) connecting, cancellable);
|
||||
host_session.agent_session_detached.connect (on_agent_session_detached);
|
||||
|
||||
return host_session;
|
||||
}
|
||||
|
||||
IOStream stream;
|
||||
try {
|
||||
var client = new SocketClient ();
|
||||
var connection = yield client.connect_async (connectable, cancellable);
|
||||
|
||||
Tcp.enable_nodelay (connection.socket);
|
||||
|
||||
stream = connection;
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.TRANSPORT ("The specified GDB remote stub cannot be reached: %s", e.message);
|
||||
}
|
||||
|
||||
#if WINDOWS || MACOS || (LINUX && !ANDROID)
|
||||
if (config.connection.flavor == BareboneStubFlavor.ANDROID_EMULATOR) {
|
||||
connecting ("Instrumenting the emulator", 0.05);
|
||||
emulator_instrumentation = yield EmulatorInstrumentation.apply (hub, config, cancellable);
|
||||
}
|
||||
#endif
|
||||
|
||||
Debugger debugger;
|
||||
switch (config.connection.flavor) {
|
||||
case BareboneStubFlavor.VZ:
|
||||
debugger = yield Barebone.VzStubClient.open (stream, cancellable);
|
||||
break;
|
||||
case BareboneStubFlavor.PARALLELS:
|
||||
debugger = yield Barebone.ParallelsStubClient.open (stream, cancellable);
|
||||
break;
|
||||
case BareboneStubFlavor.VIRTUALBOX:
|
||||
debugger = yield Barebone.VirtualBoxStubClient.open (stream, cancellable);
|
||||
break;
|
||||
default:
|
||||
debugger = yield GDB.Client.open (stream, cancellable);
|
||||
break;
|
||||
}
|
||||
|
||||
#if WINDOWS
|
||||
if (emulator_instrumentation != null) {
|
||||
var client = debugger as GDB.Client;
|
||||
if (client != null)
|
||||
emulator_instrumentation.adopt_breakpoints (client);
|
||||
}
|
||||
#endif
|
||||
|
||||
try {
|
||||
host_session = yield establish (config, debugger, (owned) connecting, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
if (debugger.state == STOPPED) {
|
||||
try {
|
||||
yield debugger.resume (cancellable);
|
||||
} catch (GLib.Error ee) {
|
||||
}
|
||||
return host_session;
|
||||
}
|
||||
|
||||
IOStream stream;
|
||||
try {
|
||||
yield debugger.close (cancellable);
|
||||
} catch (IOError ee) {
|
||||
var client = new SocketClient ();
|
||||
var connection = yield client.connect_async (connectable, cancellable);
|
||||
|
||||
Tcp.enable_nodelay (connection.socket);
|
||||
|
||||
stream = connection;
|
||||
} catch (GLib.Error e) {
|
||||
throw new Error.TRANSPORT ("The specified GDB remote stub cannot be reached: %s", e.message);
|
||||
}
|
||||
|
||||
#if WINDOWS || MACOS || (LINUX && !ANDROID)
|
||||
if (config.connection.flavor == BareboneStubFlavor.ANDROID_EMULATOR) {
|
||||
connecting ("Instrumenting the emulator", 0.05);
|
||||
emulator_instrumentation = yield EmulatorInstrumentation.apply (hub, config, cancellable);
|
||||
}
|
||||
#endif
|
||||
|
||||
Debugger debugger;
|
||||
switch (config.connection.flavor) {
|
||||
case BareboneStubFlavor.VZ:
|
||||
debugger = yield Barebone.VzStubClient.open (stream, cancellable);
|
||||
break;
|
||||
case BareboneStubFlavor.PARALLELS:
|
||||
debugger = yield Barebone.ParallelsStubClient.open (stream, cancellable);
|
||||
break;
|
||||
case BareboneStubFlavor.VIRTUALBOX:
|
||||
debugger = yield Barebone.VirtualBoxStubClient.open (stream, cancellable);
|
||||
break;
|
||||
case BareboneStubFlavor.ANDROID_EMULATOR:
|
||||
debugger = yield Barebone.AndroidEmulatorStubClient.open (stream, cancellable);
|
||||
break;
|
||||
default:
|
||||
debugger = yield GDB.Client.open (stream, cancellable);
|
||||
break;
|
||||
}
|
||||
|
||||
#if WINDOWS
|
||||
if (emulator_instrumentation != null) {
|
||||
var client = debugger as GDB.Client;
|
||||
if (client != null)
|
||||
emulator_instrumentation.adopt_breakpoints (client);
|
||||
}
|
||||
#endif
|
||||
|
||||
try {
|
||||
host_session = yield establish (config, debugger, (owned) connecting, cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
if (debugger.state == STOPPED) {
|
||||
try {
|
||||
yield debugger.resume (cancellable);
|
||||
} catch (GLib.Error ee) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
yield debugger.close (cancellable);
|
||||
} catch (IOError ee) {
|
||||
}
|
||||
throw_api_error (e);
|
||||
}
|
||||
host_session.agent_session_detached.connect (on_agent_session_detached);
|
||||
|
||||
return host_session;
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
host_session.agent_session_detached.connect (on_agent_session_detached);
|
||||
|
||||
return host_session;
|
||||
}
|
||||
|
||||
private async BareboneHostSession establish (BareboneConfig config, Debugger debugger, owned ConnectingFunc connecting,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Error, Efni.Error, IOError {
|
||||
// The arm64 MMU system registers (TTBR1_EL1/TCR_EL1) are exposed by some stubs and not
|
||||
// others (the Android emulator's does not); detect it from the advertised register set,
|
||||
// which selects host page-table walking versus the kernel's set_memory_* helpers.
|
||||
@@ -223,7 +232,7 @@ namespace Frida {
|
||||
size_t page_size;
|
||||
try {
|
||||
page_size = yield machine.query_page_size (cancellable);
|
||||
} catch (Error e) {
|
||||
} catch (Efni.Error e) {
|
||||
page_size = 0;
|
||||
}
|
||||
|
||||
@@ -307,11 +316,21 @@ namespace Frida {
|
||||
arm_machine.kernel_page_table = kernel_base + swapper.offset;
|
||||
}
|
||||
|
||||
Barebone.Allocator? data_allocator = null;
|
||||
if (config.kernel == LINUX) {
|
||||
BareboneTargetFunctionsAllocatorConfig? dac = infer_linux_data_allocator_config (kernel_symbols,
|
||||
kernel_base);
|
||||
if (dac != null)
|
||||
data_allocator = new Barebone.TargetFunctionsAllocator (machine, page_size,
|
||||
Gum.PageProtection.READ | Gum.PageProtection.WRITE, dac,
|
||||
dac.alloc_function.address, dac.free_function.address);
|
||||
}
|
||||
|
||||
Barebone.AgentConnection? agent_connection = null;
|
||||
var agent_config = config.agent as BareboneInjectedAgentConfig;
|
||||
if (agent_config != null) {
|
||||
agent_connection = new Barebone.AgentConnection (agent_config, config.image, config.kernel, relocation,
|
||||
kernel_base, machine, allocator, kernel_modules, kernel_symbols, kernel_notes);
|
||||
kernel_base, machine, allocator, data_allocator, kernel_modules, kernel_symbols, kernel_notes);
|
||||
agent_connection.progress.connect ((status, fraction) => connecting (status, 0.2 + 0.8 * fraction));
|
||||
yield agent_connection.open (cancellable);
|
||||
}
|
||||
@@ -320,11 +339,15 @@ namespace Frida {
|
||||
|
||||
var services = new Barebone.Services (machine, allocator, interceptor);
|
||||
|
||||
return new BareboneHostSession (agent_connection, services);
|
||||
uint emulator_process = (config.connection.flavor == BareboneStubFlavor.ANDROID_EMULATOR)
|
||||
? config.connection.pid
|
||||
: 0;
|
||||
|
||||
return new BareboneHostSession (agent_connection, services, emulator_process);
|
||||
}
|
||||
|
||||
private async BareboneHostSession attach_to_resident_agent (BareboneResidentTransportConfig transport,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
Cancellable? cancellable) throws Error, Efni.Error, IOError {
|
||||
#if WINDOWS
|
||||
throw new Error.NOT_SUPPORTED ("Resident agents are not available on this OS");
|
||||
#else
|
||||
@@ -347,7 +370,7 @@ namespace Frida {
|
||||
|
||||
var connection = yield Barebone.AgentConnection.open_resident (stream, cancellable);
|
||||
|
||||
return new BareboneHostSession (connection, null);
|
||||
return new BareboneHostSession (connection, null, 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -406,6 +429,29 @@ namespace Frida {
|
||||
};
|
||||
}
|
||||
|
||||
private static BareboneTargetFunctionsAllocatorConfig? infer_linux_data_allocator_config (
|
||||
Gee.List<Barebone.SymbolInfo> kernel_symbols, uint64 kernel_base) {
|
||||
Barebone.SymbolInfo? alloc = find_symbol (kernel_symbols, "vmalloc");
|
||||
Barebone.SymbolInfo? free = find_symbol (kernel_symbols, "vfree");
|
||||
if (alloc == null || free == null)
|
||||
return null;
|
||||
|
||||
var alloc_arguments = new Gee.ArrayList<BareboneCallArgument> ();
|
||||
alloc_arguments.add (new BareboneCallArgument (SIZE, 0));
|
||||
|
||||
var free_arguments = new Gee.ArrayList<BareboneCallArgument> ();
|
||||
free_arguments.add (new BareboneCallArgument (ADDRESS, 0));
|
||||
|
||||
return new BareboneTargetFunctionsAllocatorConfig () {
|
||||
alloc_function = new BareboneNonNullMemoryAddress ("data_allocator.alloc_function",
|
||||
kernel_base + alloc.offset),
|
||||
free_function = new BareboneNonNullMemoryAddress ("data_allocator.free_function",
|
||||
kernel_base + free.offset),
|
||||
alloc_arguments = alloc_arguments,
|
||||
free_arguments = free_arguments,
|
||||
};
|
||||
}
|
||||
|
||||
private static BareboneAllocatorConfig? infer_win9x_allocator_config (
|
||||
Gee.List<Barebone.SymbolInfo> kernel_symbols) {
|
||||
Barebone.SymbolInfo? alloc = find_symbol (kernel_symbols, "_HeapAllocate");
|
||||
@@ -521,6 +567,16 @@ namespace Frida {
|
||||
construct;
|
||||
}
|
||||
|
||||
public uint android_emulator_pid {
|
||||
get;
|
||||
construct;
|
||||
}
|
||||
|
||||
private ProcessEnumerator? host_processes;
|
||||
private Promise<AndroidHelperClient>? android_helper_request;
|
||||
private Gee.HashMap<string, Variant>? android_app_icons;
|
||||
private Gee.HashMap<string, Promise<uint>> android_spawn_requests = new Gee.HashMap<string, Promise<uint>> ();
|
||||
|
||||
private Gee.Map<uint, uint> injected_agents = new Gee.HashMap<uint, uint> ();
|
||||
private uint spawn_helper_pid = 0;
|
||||
private Gee.HashMap<uint, HeldSpawn> pending_spawn = new Gee.HashMap<uint, HeldSpawn> ();
|
||||
@@ -540,8 +596,9 @@ namespace Frida {
|
||||
private Gee.Map<AgentSessionId?, BareboneAgentSession> agent_sessions =
|
||||
new Gee.HashMap<AgentSessionId?, BareboneAgentSession> (AgentSessionId.hash, AgentSessionId.equal);
|
||||
|
||||
public BareboneHostSession (Barebone.AgentConnection? connection, Barebone.Services? services) {
|
||||
Object (connection: connection, services: services);
|
||||
public BareboneHostSession (Barebone.AgentConnection? connection, Barebone.Services? services,
|
||||
uint android_emulator_pid) {
|
||||
Object (connection: connection, services: services, android_emulator_pid: android_emulator_pid);
|
||||
}
|
||||
|
||||
construct {
|
||||
@@ -564,6 +621,15 @@ namespace Frida {
|
||||
yield release_injected_agent (session.pid);
|
||||
}
|
||||
|
||||
if (android_helper_request != null) {
|
||||
try {
|
||||
var helper = yield android_helper_request.future.wait_async (cancellable);
|
||||
on_android_helper_closed (helper.transport);
|
||||
yield helper.close (cancellable);
|
||||
} catch (GLib.Error e) {
|
||||
}
|
||||
}
|
||||
|
||||
if (connection != null)
|
||||
yield connection.close (cancellable);
|
||||
|
||||
@@ -594,45 +660,55 @@ namespace Frida {
|
||||
|
||||
public async HostApplicationInfo[] enumerate_applications (HashTable<string, Variant> options,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
try {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
|
||||
var query = ApplicationQueryOptions._deserialize (options);
|
||||
var selected = new Gee.HashSet<string> ();
|
||||
query.enumerate_selected_identifiers (identifier => {
|
||||
selected.add (identifier);
|
||||
});
|
||||
var query = ApplicationQueryOptions._deserialize (options);
|
||||
|
||||
var applications = yield list_applications (selected.to_array (), cancellable);
|
||||
if (android_emulator_pid != 0) {
|
||||
var helper = yield get_android_helper (cancellable);
|
||||
return yield helper.enumerate_applications (query, cancellable);
|
||||
}
|
||||
|
||||
var running = new Gee.HashMap<string, uint> ();
|
||||
foreach (HostProcessInfo p in yield connection.enumerate_processes (Scope.METADATA, {},
|
||||
cancellable)) {
|
||||
var path = p.parameters["path"];
|
||||
if (path != null)
|
||||
running[basename_of (path.get_string ()).down ()] = p.pid;
|
||||
var selected = new Gee.HashSet<string> ();
|
||||
query.enumerate_selected_identifiers (identifier => {
|
||||
selected.add (identifier);
|
||||
});
|
||||
|
||||
var applications = yield list_applications (selected.to_array (), cancellable);
|
||||
|
||||
var running = new Gee.HashMap<string, uint> ();
|
||||
foreach (HostProcessInfo p in yield connection.enumerate_processes (Scope.METADATA, {},
|
||||
cancellable)) {
|
||||
var path = p.parameters["path"];
|
||||
if (path != null)
|
||||
running[basename_of (path.get_string ()).down ()] = p.pid;
|
||||
}
|
||||
|
||||
var scope = query.scope;
|
||||
var result = new HostApplicationInfo[applications.length];
|
||||
for (int i = 0; i != applications.length; i++) {
|
||||
var app = applications[i];
|
||||
var parameters = make_parameters_dict ();
|
||||
if (scope != MINIMAL)
|
||||
parameters["path"] = app.path;
|
||||
|
||||
uint pid;
|
||||
if (!running.unset (basename_of (app.path).down (), out pid))
|
||||
pid = 0;
|
||||
|
||||
var name = (app.description != "") ? app.description : basename_of (app.path);
|
||||
result[i] = HostApplicationInfo (app.identifier, name, pid, (owned) parameters);
|
||||
}
|
||||
return result;
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
|
||||
var scope = query.scope;
|
||||
var result = new HostApplicationInfo[applications.length];
|
||||
for (int i = 0; i != applications.length; i++) {
|
||||
var app = applications[i];
|
||||
var parameters = make_parameters_dict ();
|
||||
if (scope != MINIMAL)
|
||||
parameters["path"] = app.path;
|
||||
|
||||
uint pid;
|
||||
if (!running.unset (basename_of (app.path).down (), out pid))
|
||||
pid = 0;
|
||||
|
||||
var name = (app.description != "") ? app.description : basename_of (app.path);
|
||||
result[i] = HostApplicationInfo (app.identifier, name, pid, (owned) parameters);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Barebone.AgentConnection.Application[] list_applications (
|
||||
string[] identifiers, Cancellable? cancellable) throws Error, IOError {
|
||||
string[] identifiers, Cancellable? cancellable) throws Error, Efni.Error, IOError {
|
||||
var listed = new Gee.ArrayList<Barebone.AgentConnection.Application> ();
|
||||
listed.add_all_array (yield connection.enumerate_applications (identifiers, cancellable));
|
||||
|
||||
@@ -672,26 +748,145 @@ namespace Frida {
|
||||
|
||||
public async HostProcessInfo[] enumerate_processes (HashTable<string, Variant> options,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
var query = ProcessQueryOptions._deserialize (options);
|
||||
uint[] pids = {};
|
||||
query.enumerate_selected_pids (pid => {
|
||||
pids += pid;
|
||||
});
|
||||
return yield connection.enumerate_processes (query.scope, pids, cancellable);
|
||||
try {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
var query = ProcessQueryOptions._deserialize (options);
|
||||
uint[] pids = {};
|
||||
query.enumerate_selected_pids (pid => {
|
||||
pids += pid;
|
||||
});
|
||||
var processes = yield connection.enumerate_processes (query.scope, pids, cancellable);
|
||||
|
||||
if (query.scope == FULL && android_emulator_pid != 0)
|
||||
yield attach_app_icons (processes, cancellable);
|
||||
|
||||
return processes;
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
private async void attach_app_icons (HostProcessInfo[] processes, Cancellable? cancellable) throws IOError {
|
||||
Gee.HashMap<string, Variant> icons;
|
||||
try {
|
||||
icons = yield resolve_app_icons (cancellable);
|
||||
} catch (Error e) {
|
||||
return;
|
||||
} catch (Efni.Error e) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i != processes.length; i++) {
|
||||
Variant? icon = icons[processes[i].name];
|
||||
if (icon != null)
|
||||
processes[i].parameters["icons"] = icon;
|
||||
}
|
||||
}
|
||||
|
||||
private async Gee.HashMap<string, Variant> resolve_app_icons (Cancellable? cancellable) throws Error, Efni.Error, IOError {
|
||||
if (android_app_icons == null) {
|
||||
var helper = yield get_android_helper (cancellable);
|
||||
|
||||
var options = new ApplicationQueryOptions ();
|
||||
options.scope = FULL;
|
||||
|
||||
var icons = new Gee.HashMap<string, Variant> ();
|
||||
foreach (var app in yield helper.enumerate_applications (options, cancellable)) {
|
||||
Variant? icon = app.parameters["icons"];
|
||||
if (icon != null)
|
||||
icons[app.identifier] = icon;
|
||||
}
|
||||
|
||||
android_app_icons = icons;
|
||||
}
|
||||
|
||||
return android_app_icons;
|
||||
}
|
||||
|
||||
private async AndroidHelperClient get_android_helper (Cancellable? cancellable) throws Error, Efni.Error, IOError {
|
||||
while (android_helper_request != null) {
|
||||
try {
|
||||
return yield android_helper_request.future.wait_async (cancellable);
|
||||
} catch (Error e) {
|
||||
throw e;
|
||||
} catch (IOError e) {
|
||||
cancellable.set_error_if_cancelled ();
|
||||
}
|
||||
}
|
||||
android_helper_request = new Promise<AndroidHelperClient> ();
|
||||
|
||||
try {
|
||||
string serial = yield resolve_emulator_serial (cancellable);
|
||||
var helper = yield AndroidHelperClient.open (serial, cancellable);
|
||||
helper.transport.closed.connect (on_android_helper_closed);
|
||||
|
||||
android_helper_request.resolve (helper);
|
||||
|
||||
return helper;
|
||||
} catch (Error e) {
|
||||
android_helper_request.reject (e);
|
||||
android_helper_request = null;
|
||||
throw e;
|
||||
} catch (IOError e) {
|
||||
android_helper_request.reject (e);
|
||||
android_helper_request = null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void on_android_helper_closed (AndroidHelperTransport transport) {
|
||||
transport.closed.disconnect (on_android_helper_closed);
|
||||
android_helper_request = null;
|
||||
android_app_icons = null;
|
||||
}
|
||||
|
||||
private async string resolve_emulator_serial (Cancellable? cancellable) throws Error, IOError {
|
||||
if (host_processes == null)
|
||||
host_processes = new ProcessEnumerator ();
|
||||
|
||||
var options = new ProcessQueryOptions ();
|
||||
options.scope = FULL;
|
||||
options.select_pid (android_emulator_pid);
|
||||
|
||||
var found = yield host_processes.enumerate_processes (options);
|
||||
if (found.length == 0)
|
||||
throw new Error.INVALID_OPERATION ("Emulator process %u is gone", android_emulator_pid);
|
||||
|
||||
Variant? argv = found[0].parameters["argv"];
|
||||
if (argv == null)
|
||||
throw new Error.NOT_SUPPORTED ("Emulator command line is unavailable");
|
||||
|
||||
return "emulator-" + console_port_from_argv (argv);
|
||||
}
|
||||
|
||||
private static string console_port_from_argv (Variant argv) throws Error {
|
||||
string[] args = argv.dup_strv ();
|
||||
for (int i = 0; i + 1 < args.length; i++) {
|
||||
if (args[i] == "-ports")
|
||||
return args[i + 1].split (",")[0];
|
||||
}
|
||||
throw new Error.NOT_SUPPORTED ("Emulator console port is unavailable");
|
||||
}
|
||||
|
||||
public async void enable_spawn_gating (Cancellable? cancellable) throws Error, IOError {
|
||||
yield start_gating (cancellable);
|
||||
try {
|
||||
yield start_gating (cancellable);
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
public async void enable_spawn_gating_with_options (HashTable<string, Variant> options,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
yield start_gating (cancellable);
|
||||
try {
|
||||
yield start_gating (cancellable);
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
private async void start_gating (Cancellable? cancellable) throws Error, IOError {
|
||||
private async void start_gating (Cancellable? cancellable) throws Error, Efni.Error, IOError {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
|
||||
@@ -701,12 +896,16 @@ namespace Frida {
|
||||
}
|
||||
|
||||
public async void disable_spawn_gating (Cancellable? cancellable) throws Error, IOError {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
try {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
|
||||
yield connection.gate_spawns (false, cancellable);
|
||||
watchdog.clear ();
|
||||
pending_spawn.clear ();
|
||||
yield connection.gate_spawns (false, cancellable);
|
||||
watchdog.clear ();
|
||||
pending_spawn.clear ();
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
public async HostSpawnInfo[] enumerate_pending_spawn (Cancellable? cancellable) throws Error, IOError {
|
||||
@@ -723,45 +922,105 @@ namespace Frida {
|
||||
|
||||
public async uint spawn (string program, HostSpawnOptions options, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
try {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
|
||||
if (connection.spawns_by_itself)
|
||||
return yield connection.spawn_program (words_of (program, options), cancellable);
|
||||
if (android_emulator_pid != 0 && program[0] != '/')
|
||||
return yield spawn_android_app (program, options, cancellable);
|
||||
|
||||
uint helper = yield acquire_spawn_helper (cancellable);
|
||||
if (connection.spawns_by_itself)
|
||||
return yield connection.spawn_program (words_of (program, options), cancellable);
|
||||
|
||||
return yield connection.spawn_process (helper,
|
||||
command_line_of (yield file_of (program, cancellable), options), cancellable);
|
||||
uint helper = yield acquire_spawn_helper (cancellable);
|
||||
|
||||
return yield connection.spawn_process (helper,
|
||||
command_line_of (yield file_of (program, cancellable), options), cancellable);
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
private async uint spawn_android_app (string package, HostSpawnOptions options, Cancellable? cancellable)
|
||||
throws Error, Efni.Error, IOError {
|
||||
var entrypoint = PackageEntrypoint.parse (package, options);
|
||||
|
||||
var helper = yield get_android_helper (cancellable);
|
||||
|
||||
string process_name = yield helper.get_process_name (package, entrypoint.uid, cancellable);
|
||||
string held_name = held_name_of (process_name);
|
||||
|
||||
if (android_spawn_requests.has_key (held_name))
|
||||
throw new Error.INVALID_OPERATION ("Spawn already in progress for %s", package);
|
||||
|
||||
var request = new Promise<uint> ();
|
||||
android_spawn_requests[held_name] = request;
|
||||
|
||||
try {
|
||||
yield connection.arm_named_spawn (process_name, cancellable);
|
||||
|
||||
yield helper.stop_package (package, entrypoint.uid, cancellable);
|
||||
yield helper.start_package (package, entrypoint, cancellable);
|
||||
|
||||
var timeout = new TimeoutSource.seconds (20);
|
||||
timeout.set_callback (() => {
|
||||
request.reject (new Error.TIMED_OUT ("Timed out while waiting for %s to launch", package));
|
||||
return Source.REMOVE;
|
||||
});
|
||||
timeout.attach (MainContext.get_thread_default ());
|
||||
try {
|
||||
return yield request.future.wait_async (cancellable);
|
||||
} finally {
|
||||
timeout.destroy ();
|
||||
}
|
||||
} catch (GLib.Error e) {
|
||||
android_spawn_requests.unset (held_name);
|
||||
try {
|
||||
yield connection.disarm_named_spawn (process_name, cancellable);
|
||||
} catch (GLib.Error de) {
|
||||
}
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
private static string held_name_of (string process_name) {
|
||||
int length = process_name.length;
|
||||
return (length > TASK_COMM_MAX) ? process_name[length - TASK_COMM_MAX:] : process_name;
|
||||
}
|
||||
|
||||
private const int TASK_COMM_MAX = 15;
|
||||
|
||||
public async void input (uint pid, uint8[] data, Cancellable? cancellable) throws Error, IOError {
|
||||
throw_not_supported ();
|
||||
}
|
||||
|
||||
public async void resume (uint pid, Cancellable? cancellable) throws Error, IOError {
|
||||
if (connection.spawns_by_itself) {
|
||||
pending_spawn.unset (pid);
|
||||
watchdog.cancel (pid);
|
||||
try {
|
||||
if (connection.spawns_by_itself) {
|
||||
pending_spawn.unset (pid);
|
||||
watchdog.cancel (pid);
|
||||
|
||||
yield connection.resume_process (0, pid, cancellable);
|
||||
yield connection.resume_process (0, pid, cancellable);
|
||||
|
||||
return;
|
||||
return;
|
||||
}
|
||||
|
||||
uint holder = spawn_helper_pid;
|
||||
|
||||
HeldSpawn? held = pending_spawn[pid];
|
||||
if (held != null) {
|
||||
holder = held.holder_pid;
|
||||
pending_spawn.unset (pid);
|
||||
watchdog.cancel (pid);
|
||||
}
|
||||
|
||||
if (holder == 0)
|
||||
throw new Error.INVALID_ARGUMENT ("Process %u was not spawned by us", pid);
|
||||
|
||||
yield connection.resume_process (holder, pid, cancellable);
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
|
||||
uint holder = spawn_helper_pid;
|
||||
|
||||
HeldSpawn? held = pending_spawn[pid];
|
||||
if (held != null) {
|
||||
holder = held.holder_pid;
|
||||
pending_spawn.unset (pid);
|
||||
watchdog.cancel (pid);
|
||||
}
|
||||
|
||||
if (holder == 0)
|
||||
throw new Error.INVALID_ARGUMENT ("Process %u was not spawned by us", pid);
|
||||
|
||||
yield connection.resume_process (holder, pid, cancellable);
|
||||
}
|
||||
|
||||
public async void kill (uint pid, Cancellable? cancellable) throws Error, IOError {
|
||||
@@ -770,34 +1029,38 @@ namespace Frida {
|
||||
|
||||
public async AgentSessionId attach (uint pid, HashTable<string, Variant> options, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
if (pid != 0) {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
try {
|
||||
if (pid != 0) {
|
||||
if (connection == null)
|
||||
throw_not_supported ();
|
||||
|
||||
yield acquire_injected_agent (pid, cancellable);
|
||||
yield acquire_injected_agent (pid, cancellable);
|
||||
}
|
||||
|
||||
var opts = SessionOptions._deserialize (options);
|
||||
if (opts.realm == EMULATED)
|
||||
throw new Error.NOT_SUPPORTED ("Emulated realm is not supported on Barebone targets");
|
||||
|
||||
var session_id = AgentSessionId.generate ();
|
||||
|
||||
MainContext dbus_context = yield get_dbus_context ();
|
||||
|
||||
BareboneAgentSession session;
|
||||
if (connection != null) {
|
||||
session = new RemoteBareboneAgentSession (connection, pid, session_id, opts.persist_timeout,
|
||||
dbus_context);
|
||||
} else {
|
||||
if (services == null)
|
||||
throw new Error.NOT_SUPPORTED ("Barebone target has neither an agent nor a debugger stub");
|
||||
session = new LocalBareboneAgentSession (services, session_id, opts.persist_timeout, dbus_context);
|
||||
}
|
||||
agent_sessions[session_id] = session;
|
||||
session.closed.connect (on_agent_session_closed);
|
||||
|
||||
return session_id;
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
|
||||
var opts = SessionOptions._deserialize (options);
|
||||
if (opts.realm == EMULATED)
|
||||
throw new Error.NOT_SUPPORTED ("Emulated realm is not supported on Barebone targets");
|
||||
|
||||
var session_id = AgentSessionId.generate ();
|
||||
|
||||
MainContext dbus_context = yield get_dbus_context ();
|
||||
|
||||
BareboneAgentSession session;
|
||||
if (connection != null) {
|
||||
session = new RemoteBareboneAgentSession (connection, pid, session_id, opts.persist_timeout,
|
||||
dbus_context);
|
||||
} else {
|
||||
if (services == null)
|
||||
throw new Error.NOT_SUPPORTED ("Barebone target has neither an agent nor a debugger stub");
|
||||
session = new LocalBareboneAgentSession (services, session_id, opts.persist_timeout, dbus_context);
|
||||
}
|
||||
agent_sessions[session_id] = session;
|
||||
session.closed.connect (on_agent_session_closed);
|
||||
|
||||
return session_id;
|
||||
}
|
||||
|
||||
public async void reattach (AgentSessionId id, Cancellable? cancellable) throws Error, IOError {
|
||||
@@ -864,6 +1127,14 @@ namespace Frida {
|
||||
// Only ring 3 can make a process. Thus one process holds a copy of the agent, and that copy
|
||||
// makes each new process and holds it.
|
||||
private void on_spawn_added (uint pid, string command_line, uint holder_pid) {
|
||||
Promise<uint>? request = android_spawn_requests[command_line];
|
||||
if (request != null) {
|
||||
android_spawn_requests.unset (command_line);
|
||||
pending_spawn[pid] = new HeldSpawn (command_line, holder_pid);
|
||||
request.resolve (pid);
|
||||
return;
|
||||
}
|
||||
|
||||
var identifier = program_of (command_line);
|
||||
pending_spawn[pid] = new HeldSpawn (identifier, holder_pid);
|
||||
watchdog.arm (pid);
|
||||
@@ -895,7 +1166,7 @@ namespace Frida {
|
||||
return (end != -1) ? line[:end] : line;
|
||||
}
|
||||
|
||||
private async uint acquire_spawn_helper (Cancellable? cancellable) throws Error, IOError {
|
||||
private async uint acquire_spawn_helper (Cancellable? cancellable) throws Error, Efni.Error, IOError {
|
||||
if (spawn_helper_pid != 0)
|
||||
return spawn_helper_pid;
|
||||
|
||||
@@ -917,7 +1188,7 @@ namespace Frida {
|
||||
return pid;
|
||||
}
|
||||
|
||||
private async string file_of (string program, Cancellable? cancellable) throws Error, IOError {
|
||||
private async string file_of (string program, Cancellable? cancellable) throws Error, Efni.Error, IOError {
|
||||
if (connection.spawns_by_itself || program.contains ("\\") || program.contains (":"))
|
||||
return program;
|
||||
|
||||
@@ -959,7 +1230,7 @@ namespace Frida {
|
||||
return "\"" + token + "\"";
|
||||
}
|
||||
|
||||
private async void acquire_injected_agent (uint pid, Cancellable? cancellable) throws Error, IOError {
|
||||
private async void acquire_injected_agent (uint pid, Cancellable? cancellable) throws Error, Efni.Error, IOError {
|
||||
uint users = injected_agents[pid];
|
||||
if (users != 0) {
|
||||
injected_agents[pid] = users + 1;
|
||||
@@ -1016,19 +1287,23 @@ namespace Frida {
|
||||
|
||||
public override async AgentScriptId create_script (string source, HashTable<string, Variant> options,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
check_open ();
|
||||
try {
|
||||
check_open ();
|
||||
|
||||
var opts = ScriptOptions._deserialize (options);
|
||||
if (opts.runtime == V8)
|
||||
throw new Error.INVALID_ARGUMENT ("The V8 runtime is not supported by the Barebone backend");
|
||||
var opts = ScriptOptions._deserialize (options);
|
||||
if (opts.runtime == V8)
|
||||
throw new Error.INVALID_ARGUMENT ("The V8 runtime is not supported by the Barebone backend");
|
||||
|
||||
var id = AgentScriptId (next_script_id++);
|
||||
var id = AgentScriptId (next_script_id++);
|
||||
|
||||
var script = BareboneScript.create (id, source, services);
|
||||
scripts[id] = script;
|
||||
script.message.connect (on_message_from_script);
|
||||
var script = BareboneScript.create (id, source, services);
|
||||
scripts[id] = script;
|
||||
script.message.connect (on_message_from_script);
|
||||
|
||||
return id;
|
||||
return id;
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
public override async void destroy_script (AgentScriptId script_id, Cancellable? cancellable) throws Error, IOError {
|
||||
@@ -1116,47 +1391,63 @@ namespace Frida {
|
||||
|
||||
public override async AgentScriptId create_script (string source, HashTable<string, Variant> options,
|
||||
Cancellable? cancellable) throws Error, IOError {
|
||||
check_open ();
|
||||
try {
|
||||
check_open ();
|
||||
|
||||
var opts = ScriptOptions._deserialize (options);
|
||||
if (opts.runtime == V8)
|
||||
throw new Error.INVALID_ARGUMENT ("The V8 runtime is not supported by the Barebone backend");
|
||||
var opts = ScriptOptions._deserialize (options);
|
||||
if (opts.runtime == V8)
|
||||
throw new Error.INVALID_ARGUMENT ("The V8 runtime is not supported by the Barebone backend");
|
||||
|
||||
var script_id = yield connection.create_script (source, pid, cancellable);
|
||||
own_scripts.add (script_id);
|
||||
var script_id = yield connection.create_script (source, pid, cancellable);
|
||||
own_scripts.add (script_id);
|
||||
|
||||
return script_id;
|
||||
return script_id;
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
public override async void destroy_script (AgentScriptId script_id, Cancellable? cancellable) throws Error, IOError {
|
||||
check_open ();
|
||||
try {
|
||||
check_open ();
|
||||
|
||||
yield connection.destroy_script (script_id, pid, cancellable);
|
||||
own_scripts.remove (script_id);
|
||||
yield connection.destroy_script (script_id, pid, cancellable);
|
||||
own_scripts.remove (script_id);
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
public override async void load_script (AgentScriptId script_id, Cancellable? cancellable) throws Error, IOError {
|
||||
check_open ();
|
||||
try {
|
||||
check_open ();
|
||||
|
||||
yield connection.load_script (script_id, pid, cancellable);
|
||||
yield connection.load_script (script_id, pid, cancellable);
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
public override async void post_messages (AgentMessage[] messages, uint batch_id, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
transmitter.check_okay_to_receive ();
|
||||
try {
|
||||
transmitter.check_okay_to_receive ();
|
||||
|
||||
foreach (var m in messages) {
|
||||
switch (m.kind) {
|
||||
case SCRIPT:
|
||||
yield connection.post_script_message (m.script_id, m.text,
|
||||
m.has_data ? new Bytes (m.data) : null, pid, cancellable);
|
||||
break;
|
||||
case DEBUGGER:
|
||||
break;
|
||||
foreach (var m in messages) {
|
||||
switch (m.kind) {
|
||||
case SCRIPT:
|
||||
yield connection.post_script_message (m.script_id, m.text,
|
||||
m.has_data ? new Bytes (m.data) : null, pid, cancellable);
|
||||
break;
|
||||
case DEBUGGER:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
transmitter.notify_rx_batch_id (batch_id);
|
||||
transmitter.notify_rx_batch_id (batch_id);
|
||||
} catch (Efni.Error e) {
|
||||
throw_api_error (e);
|
||||
}
|
||||
}
|
||||
|
||||
// Each copy numbers its scripts from one, thus take only what comes from our own process.
|
||||
|
||||
@@ -23,11 +23,11 @@ namespace Frida.Barebone {
|
||||
private Callback console_log_callback;
|
||||
|
||||
public async CModule.from_blob (Bytes blob, Machine machine, Allocator allocator, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
try {
|
||||
elf = new Gum.ElfModule.from_blob (blob);
|
||||
} catch (Gum.Error e) {
|
||||
throw new Error.NOT_SUPPORTED ("%s", e.message);
|
||||
throw new Efni.Error.NOT_SUPPORTED ("%s", e.message);
|
||||
}
|
||||
|
||||
var raw_elf = new Bytes.static (elf.get_file_data ());
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Efni;
|
||||
|
||||
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
|
||||
namespace Frida.Barebone {
|
||||
public sealed class Callback : Object {
|
||||
@@ -10,7 +12,7 @@ namespace Frida.Barebone {
|
||||
private Cancellable io_cancellable = new Cancellable ();
|
||||
|
||||
public async Callback (uint64 code, CallbackHandler handler, Machine machine, Cancellable? cancellable)
|
||||
throws Error, IOError {
|
||||
throws Efni.Error, IOError {
|
||||
this.code = code;
|
||||
this.handler = handler;
|
||||
this.machine = machine;
|
||||
@@ -26,7 +28,7 @@ namespace Frida.Barebone {
|
||||
debugger.notify["state"].disconnect (on_gdb_state_changed);
|
||||
}
|
||||
|
||||
public async void destroy (Cancellable? cancellable) throws Error, IOError {
|
||||
public async void destroy (Cancellable? cancellable) throws Efni.Error, IOError {
|
||||
yield breakpoint.remove (cancellable);
|
||||
}
|
||||
|
||||
@@ -44,7 +46,7 @@ namespace Frida.Barebone {
|
||||
handle_invocation.begin (exception.thread);
|
||||
}
|
||||
|
||||
private async void handle_invocation (DebuggerThread thread) throws Error, IOError {
|
||||
private async void handle_invocation (DebuggerThread thread) throws Efni.Error, IOError {
|
||||
uint arity = handler.arity;
|
||||
|
||||
var frame = yield machine.load_call_frame (thread, arity, io_cancellable);
|
||||
@@ -69,6 +71,6 @@ namespace Frida.Barebone {
|
||||
}
|
||||
|
||||
public abstract async uint64 handle_invocation (uint64[] args, CallFrame frame, Cancellable? cancellable)
|
||||
throws Error, IOError;
|
||||
throws Efni.Error, IOError;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 323 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user