Compare commits

..
122 Commits
Author SHA1 Message Date
Ole André Vadla Ravnås a62376a3d6 subprojects: Prepare for release 2026-03-27 11:36:34 +01:00
Ole André Vadla Ravnås f5803e76ca subprojects: Bump outdated 2026-03-27 11:34:53 +01:00
Ole André Vadla Ravnås 3b052905d7 package-manager: Fix semver pre-release overflow
Numeric pre-release identifiers like "202508252028" would
fail validation because parse_uint() rejects values beyond
UINT32_MAX. The same overflow affected version comparison,
which also used uint.

Fix validation to only check the semver-mandated rule that
numeric identifiers must not have leading zeros, and fix
comparison to use length-prefixed string comparison, which
handles arbitrarily large numeric identifiers correctly.
2026-03-27 11:32:50 +01:00
Ole André Vadla Ravnås c3864a15a1 subprojects: Prepare for release 2026-03-26 20:43:41 +01:00
Ole André Vadla Ravnås b49aac0765 subprojects: Bump outdated 2026-03-26 20:42:39 +01:00
Ole André Vadla Ravnås 1f77154b83 fruity: Add control-endpoint backend option
Default is `tcp:27042`. Only TCP endpoints are supported.
2026-03-26 20:26:02 +01:00
Ole André Vadla Ravnås d2f2c400dc droidy: Add control-endpoint backend option
Default is `tcp:27042`, but may be set to any endpoint supported by ADB,
such as `localabstract:/my-frida-server`.
2026-03-26 20:26:02 +01:00
Ole André Vadla Ravnås 3df058764b device: Add override_option()
Allow callers to override backend-specific options when creating
a host session.

Overrides take effect when establishing a host session. If a host
session already exists, updated values are applied on the next
connection.

Inspired-by: @giantpune
2026-03-26 20:25:33 +01:00
Ole André Vadla Ravnås f962931617 host-session-options: Add copy() 2026-03-26 20:06:47 +01:00
Ole André Vadla Ravnås be23998210 android: Skip 32-bit helper on 64-bit only systems
Do not waste time trying to spawn it.
2026-03-26 15:24:53 +01:00
Ole André Vadla Ravnås 0bee9cba2b linux: Support injection into group-stopped PIDs 2026-03-26 15:24:53 +01:00
NSEchoandOle André Vadla Ravnås 465698a907 linux: Add eBPF-based spawn gater implementation
Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2026-03-26 15:24:53 +01:00
Ole André Vadla Ravnås 4e5a60a576 subprojects: Prepare for release 2026-03-24 15:40:37 +01:00
Ole André Vadla Ravnås aaa66bbafd subprojects: Bump outdated 2026-03-24 15:39:15 +01:00
Soumik Sarkhel 1dc4435f96 android: Modify RTLD path if dlopen(libart) fails 2026-03-24 15:38:14 +01:00
Ole André Vadla Ravnås ac9f8cac5f fruity: Fix TcpTunnelConnection stalls
The remotepairingdeviced service may defer CDTunnel TLS records
larger than 8192 bytes until a smaller record arrives, which can
stall sustained tunnel output.

When a large write drains the pending output queue, send a minimal
dummy IPv6 datagram to trigger delivery of deferred data and
improve reliability.

Kudos to @tux-mind for identifying this behavior and helping track
it down.

Fixes #1223.
2026-03-24 14:54:04 +01:00
Francesco Tamagni 0ed112fac1 fruity: Leak injector pages on deallocate fail
On iOS 26.4 `lldb.deallocate()` fails all the time for sandbox issues,
probably it's an iOS bug or a new "security" feature from Apple. This is
a sub-optimal workaround that will change in the future.
2026-03-23 14:08:08 +01:00
Francesco Tamagni 266032d035 fruity: Search restartWithDyldInCache by substring 2026-03-23 14:08:08 +01:00
Ole André Vadla Ravnås 8995f83898 fruity: Handle tunnel lost super-early
E.g. because remotepairingdeviced crashes.
2026-03-22 15:24:16 +01:00
Ole André Vadla Ravnås 680159ef78 fruity: Fix TreeSet comparator dropping transports
Gee.TreeSet treats elements as equal when the comparator returns 0.
Our comparator returned 0 for transports with the same score, causing
later transports to be dropped from the set.

This happens on macOS when a CoreDevice transport appears after usbmux
transports with the same score. Because the comparator reported
equality, the CoreDevice transport was not inserted.

As a result Frida would prefer usbmuxd with lwIP instead of the already
available CoreDevice tunnel.

Fix this by adding a deterministic tie-breaker based on pointer identity
so the comparator only returns 0 for the same instance.

Fixes #1220.
2026-03-16 19:34:40 +01:00
Ole André Vadla Ravnås 71e50bfb9e subprojects: Prepare for release 2026-03-14 11:52:00 +01:00
Ole André Vadla Ravnås 0416b95375 subprojects: Bump outdated 2026-03-14 11:51:19 +01:00
Ole André Vadla Ravnås 6c2f1e6ae3 android: Detect setArgV0() in anonymous memory too
Fixes #1219.
2026-03-14 11:50:01 +01:00
Ole André Vadla Ravnås 04aef7f0c4 subprojects: Prepare for release 2026-03-13 13:22:03 +01:00
Ole André Vadla Ravnås eefce5d860 Revert "linux: Rebuild native helpers for arm and arm64"
This reverts commit 5d015c5e1c.
2026-03-13 13:20:53 +01:00
Ole André Vadla Ravnås beb2c221ec ci: Temporarily skip helpers and labrats checks
Will revisit them post-release.
2026-03-13 13:20:53 +01:00
Ole André Vadla Ravnås 5444842b22 subprojects: Bump outdated 2026-03-13 13:12:01 +01:00
Ole André Vadla Ravnås 5d015c5e1c linux: Rebuild native helpers for arm and arm64
To satisfy CI checks after the Android NDK upgrade.
2026-03-13 13:09:21 +01:00
Ole André Vadla Ravnås f1eaccaecd ci: Fix linux-helpers and labrats checks 2026-03-13 13:06:33 +01:00
Ole André Vadla Ravnås 1be2ed39ba linux: Fix helpers A32 build with Android NDK r29 2026-03-13 12:58:37 +01:00
Ole André Vadla Ravnås e51bf43bc3 android: Handle Chrome's zygote process
So it's invisible to our spawn gating, but its children are gated.
2026-03-13 12:33:38 +01:00
Ole André Vadla Ravnås e2fef93e03 linux: Add missing newline to the nolibc patch 2026-03-13 11:47:54 +01:00
Ole André Vadla Ravnås 9414cfe281 ci: Bump Android NDK to r29 2026-03-13 11:44:58 +01:00
Ole André Vadla Ravnås 74cbc8646f linux: Fix helpers build with Android NDK r29 2026-03-13 11:38:52 +01:00
Ole André Vadla Ravnås 5925eda6b2 libc-shim: Fix stdio buffer allocation order
The stdio shim initialized rcap/wcap after allocating rbuf/wbuf, so
buffered streams ended up with zero-sized allocations.

This caused buffered reads like fdopen(..., "r") + fread() to pass an
invalid buffer to read(), which could fail with EFAULT ("Bad address").
2026-03-13 10:11:48 +01:00
Ole André Vadla Ravnås 686cfcfda8 subprojects: Bump outdated 2026-03-13 00:01:18 +01:00
Ole André Vadla Ravnås 98a4f4f3e6 submodules: Bump releng 2026-03-13 00:01:17 +01:00
Ole André Vadla Ravnås 5b1e77a04c android: Only load in namespace if ART ns exists 2026-03-12 23:59:45 +01:00
Ole André Vadla Ravnås 9a93437b68 meson: Fix linking on modern LLVM toolchains
Modern LLVM/LLD linkers are stricter about undefined symbols in version
scripts. Some of our executable version scripts referenced
FreeBSD-specific symbols (__progname and environ), which older linkers
silently ignored but newer ones reject.

Fix this by providing a FreeBSD-specific version script and selecting it
in Meson when targeting FreeBSD.

Also centralize the linker scripts used for executables that export no
symbols into tools/, and reuse them across targets instead of
duplicating identical files.
2026-03-12 23:58:44 +01:00
Ole André Vadla Ravnås 685526c52c compiler: Add musl-compatible backend mode
The Go toolchain emits TLS relocations that musl only supports for
objects present at program startup. This rules out the integration
strategies based on c-archive and c-shared that we use elsewhere for
the compiler backend.

Introduce a third backend mode where the Go code is built as a PIE
executable and embedded as a resource. At runtime we extract it to a
temporary file and spawn it as a long-lived helper process. Requests
and events are exchanged over a simple length-prefixed JSON protocol.

This keeps the existing in-process integration on platforms where
c-archive or c-shared works, while providing a musl-compatible backend
strategy.

Implementation details:

  - Add a new executable backend mode selected automatically when the
    target libc is musl.
  - Extend the Meson detection logic to propagate libc and choose
    between archive, shared, or executable backends.
  - Split the Go frontend into two implementations selected by build
    tags: one exposing the C API and one implementing the stdio
    protocol used by the executable mode.
  - Introduce a BackendProcess implementation on the Vala side that
    manages a persistent backend subprocess and multiplexes build and
    watch requests.

This makes it possible to support the compiler backend on musl without
depending on Go integration modes that conflict with musl's TLS model,
which would preclude loading frida-core as a plugin or after the
initial exec.
2026-03-12 14:39:30 +01:00
Ole André Vadla Ravnås 326dd071e7 Revert "compiler: Fix crash on startup on musl"
This only gets us partway there. The Go toolchain emits initial-exec TLS
relocations (e.g. for runtime.tls_g), which musl only supports for objects
present at program startup.

frida-core may also be loaded via dlopen(), and musl rejects such objects
when they contain initial-exec TLS relocations:

```
initial-exec TLS resolves to dynamic definition
```

This is a separate issue from the constructor crash fixed by the
reverted commit.

This reverts commit e096c363e0.
2026-03-11 19:40:38 +01:00
Ole André Vadla Ravnås e096c363e0 compiler: Fix crash on startup on musl
The Go runtime assumes that constructor functions are called with argc
and argv. This is the case with glibc's RTLD, but not musl's. So to work
around this we modify go.o to remove its initializer from .init_array,
and instead call it manually, so we can pass it argc and argv.
2026-03-10 12:32:18 +00:00
Ole André Vadla Ravnås b588219d80 linux: Improve the process enumeration UID logic
- Handle sysconf(_SC_GETPW_R_SIZE_MAX) failing or returning
  "indeterminate".
- Retry with a larger buffer size if getpwuid_r() returns ERANGE.
- Do not fall back to stringifying the UID as the `user` parameter.
- Add a `uid` parameter that is always present.
2026-03-10 10:57:43 +00:00
Ole André Vadla Ravnås 9b567080e9 libc-shim: Fix setbuffer signature on glibc + musl 2026-03-10 09:36:02 +00:00
Ole André Vadla Ravnås e2580ce294 libc-shim: Plug some more holes in the stdio API
Add implementations for a few remaining BSD stdio entry-points:

- setbuf() and __srget() (currently referenced on Darwin)
- setlinebuf() and setbuffer()
2026-03-10 10:16:51 +01:00
Ole André Vadla Ravnås 1bdf9a2fd3 android: Implement sigchain logic when needed 2026-03-09 11:41:15 +01:00
Ole André Vadla Ravnås d5d500be3a subprojects: Prepare for release 2026-03-08 20:35:38 +01:00
Ole André Vadla Ravnås 6a1aa42685 subprojects: Bump outdated 2026-03-08 19:44:01 +01:00
Ole André Vadla Ravnås 2f75c98c0c syscall-tracer: Make eBPF more verifier-friendly 2026-03-08 18:50:15 +01:00
Ole André Vadla Ravnås c50c6cc6dc linux: Bump BpfObject log buffer size to 128 KiB 2026-03-08 18:49:33 +01:00
Ole André Vadla Ravnås 34742d09c3 android: Use in-process helper everywhere
Even as far back as API level 19.
2026-03-08 17:24:05 +01:00
Ole André Vadla Ravnås b08453341d atomics: Fix -Watomic-alignment warnings
Clang may warn that 64-bit atomic operations are misaligned when guint64
only has 4-byte alignment on the target ABI.

Use an explicitly 8-byte aligned typedef for the atomic helpers and
update the Vala bindings to use typed pointers instead of void *.
2026-03-08 17:05:51 +01:00
Ole André Vadla Ravnås cd9c2183ce android: Support in-process helper on Nougat
And potentially even older OSes.

This brings us another step closer to using in-process everywhere.
2026-03-08 12:27:48 +01:00
Ole André Vadla Ravnås 35bb528992 android: Fix in-process helper on older ARTs
Where ART expects the main executable to export certain symbols. We work
around this by replacing the crashing stubs with a function that does
nothing.
2026-03-08 11:21:16 +01:00
Ole André Vadla Ravnås e3a4a031f8 tests: Fix the icon width/height checks 2026-03-08 00:13:06 +01:00
Ole André Vadla Ravnås e9083013a8 subprojects: Bump outdated 2026-03-07 23:51:36 +01:00
Ole André Vadla Ravnås 1105d0d45d droidy: Port to the new AndroidHelperClient API 2026-03-07 23:45:37 +01:00
Ole André Vadla Ravnås 0f5153a5d0 compiler: Bump @types/frida-gum to 19.0.2 2026-03-07 23:37:23 +01:00
Ole André Vadla Ravnås 23f288c5e5 android: Run android-helper in-process if possible
We only try to do this on modern systems, as older versions of ART
require the main executable to export certain symbols. That precludes
usage in scenarios where frida-core is embedded, e.g. like in r2frida.
2026-03-07 22:36:48 +01:00
Ole André Vadla Ravnås e25b4debac base: Add missing G_{BEGIN,END}_DECLS to headers 2026-03-07 21:54:55 +01:00
Ole André Vadla Ravnås e5e3033415 libc-shim: Omit fseeko64 and ftello64 on QNX
They're implicitly defined.
2026-03-03 21:50:37 +01:00
Ole André Vadla Ravnås 719c0c1161 meson: Ensure libc is defined for non-Linux too 2026-03-03 21:36:48 +01:00
Dep c899e04a9c android-helper: Fix crash on Transsion ROMs
Fix a NullPointerException when the android-helper initializes on
Infinix and other Transsion OS devices.

Their modified ActivityThread expects a fully initialized main
looper. Using Looper.prepare() causes a crash in android.os.Handler
before initialization completes.

Use Looper.prepareMainLooper() instead so the expected main looper
is available.

Verified on a rooted Infinix device by compiling the .dex and
running it via app_process.
2026-03-03 21:33:33 +01:00
Alexander Hude 575161cad7 darwin: Fix early instrumentation on iOS 26.4
In iOS 26.4, Apple changed the signature of restartWithDyldInCache,
which broke the existing detection logic.

Generalize the logic instead of relying on another specific symbol.
2026-03-03 21:26:43 +01:00
Ole André Vadla Ravnås a05633f683 linux: Fix the helpers host_machine auto-detection 2026-03-03 21:23:07 +01:00
Ole André Vadla Ravnås 6053f4eb84 linux: Update helpers/rebuild.sh to match Makefile 2026-03-03 21:22:28 +01:00
Ole André Vadla Ravnås 0753bcf4b8 gadget: Only use versioned stdio symbols on glibc 2026-03-03 21:14:18 +01:00
Ole André Vadla Ravnås a66dff2d71 agent: Only use versioned stdio symbols on glibc 2026-03-03 21:13:43 +01:00
Ole André Vadla Ravnås f0fd7aef7b libc-shim: Plug some more holes in the stdio API
- fseeko, fseeko64
- ftello, ftello64
2026-03-03 19:36:42 +01:00
Ole André Vadla Ravnås 41e02684f3 libc-shim: Version fopen/fopen64 for libstdc++
Static libstdc++ introduces references to fopen@GLIBC_2.2.5 and
fopen64@GLIBC_2.2.5.

Provide matching versioned symbols from the libc shim and define a
GLIBC_2.2.5 node in the embedding version scripts so these bind to the
shim instead of glibc in both agent and gadget.
2026-03-03 19:11:27 +01:00
Ole André Vadla Ravnås 3f251baaa2 libc-shim: Plug some more holes in the stdio API
- getwc, fgetwc, ungetwc
- putc, putwc, fputwc
2026-03-03 15:39:26 +01:00
Ole André Vadla Ravnås 066f2dd718 libc-shim: Skip deinit unless explicitly requested
When the process exits and runs destructor functions, there is no
need to clean up these resources.

Previously this could cause undefined behavior because higher-level
subsystems had not been torn down first, e.g. threads still running
when GThread was torn down. Skipping deinit in this case avoids
teardown-time undefined behavior.
2026-03-03 14:48:40 +01:00
Ole André Vadla Ravnås 1fa296e285 linux: Move to latest syscall-trace protocol
- Use a uint64 for the thread ID. Move it before PID for better packing.
- Support including a module UUID and version string. Not yet wired up
  in the Linux backend.
- Support excluding specific syscalls.

This is to align with the tweaks made for the Fruity implementation.
2026-03-02 15:12:32 +01:00
Ole André Vadla Ravnås 9a4b6ac14d linux: Add uint64 key helpers to BpfMap 2026-03-02 15:12:31 +01:00
Ole André Vadla RavnåsandHåvard Sørbø c23ab3e2c9 fruity: Implement syscall-trace service
Wire up a syscall tracing service on top of CoreProfile ktrace/kdebug.

Configure the ktrace tap to emit syscall entry and exit events and
decode them using the XNU syscall signatures.

Detect syscalls with filesystem path arguments and correlate them with
VFS activity to reconstruct the contents of userspace string pointers
passed to the kernel.

Stitch in callstack events and provide symbolication by leveraging
query_symbolicator_signature().

Stream decoded events to consumer and manage lifecycle, including start,
stop, and cleanup on termination.

Co-authored-by: Håvard Sørbø <[email protected]>
2026-03-02 15:12:30 +01:00
Ole André Vadla Ravnås a6701b2fc9 base: Add XNU syscall enums and signatures
Introduce enums and signature metadata for XNU syscalls.

Define syscall numbers, names, and argument layouts to enable decoding
of ktrace/kdebug events.

Provide a foundation for higher-level tracing and analysis.
2026-03-02 15:02:57 +01:00
Ole André Vadla RavnåsandHåvard Sørbø f810946569 dtx: Introduce CoreProfileService
Provide access to CoreProfile via DTX with initial support for
ktrace/kdebug collection through a TapConfig abstraction.

Add KtraceConfig as the first tap type, modelling a subset of available
flags and filters.

Allow additional tap types and broader configuration to be introduced
later.

Co-authored-by: Håvard Sørbø <[email protected]>
2026-03-02 15:02:57 +01:00
Ole André Vadla Ravnås 5cac7c0c6e dtx: Add per-PID symbolicator signature query
Extend DeviceInfoService with support for retrieving the symbolicator
signature for a specific process.

The returned data describes the process' loaded images, including UUIDs,
segment layouts, load addresses, and versions from each image's
Info.plist. Symbols themselves are not included.

Parse the response into structured types to simplify matching against
crash logs and trace data.
2026-03-02 15:02:57 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 65c694a66d fruity: Support spawning non-debuggable apps
As these cannot be launched suspended through LLDB, fall back to
ProcessControlService and send SIGSTOP immediately after launch.

Ensure the app is not already running before spawning, as relying on
ExistingInstancePolicy.KILL may leave it in an inconsistent state.

Track launched PIDs and resume them by sending SIGCONT when requested.
Clean up tracking when the process terminates.

Co-authored-by: Håvard Sørbø <[email protected]>
2026-03-02 15:02:57 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 13bfcaf1a4 dtx: Extend ProcessControlService process control
Extend ProcessControlService with additional capabilities exposed by
Instruments' processcontrol endpoint.

This adds support for:

- Resolving PID from bundle identifier
- Checking whether a PID is debuggable
- Launching apps with arguments and environment
- Sending signals to a process
- Observing process termination events

Introduce LaunchOptions to control launch behavior such as suspended
start and handling of existing instances.

Expose termination notifications via a new process_terminated signal.

Co-authored-by: Håvard Sørbø <[email protected]>
2026-03-02 15:02:57 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 8f83d5c269 dtx: Lift buffering restrictions
Turned out to be too conservative. And it's hard to decide on
appropriate limits when dealing with bulk data use-cases.

Co-authored-by: Håvard Sørbø <[email protected]>
2026-03-02 15:02:57 +01:00
Ole André Vadla Ravnås b12c30078a dtx: Handle incoming nil arguments 2026-03-02 14:14:22 +01:00
Ole André Vadla Ravnås c7669b9701 numeric: Add bytes_hash() and bytes_equal() 2026-02-24 10:43:40 +01:00
Ole André Vadla Ravnås 5096dbfac4 linux: Fix a stylistic inconsistency 2026-02-23 20:24:45 +01:00
Ole André Vadla Ravnås 9c16fa16fb marshal: Avoid null dereference in enum_to_nick()
Return a formatted fallback string when the enum value is unknown.
2026-02-22 20:20:58 +01:00
Ole André Vadla Ravnås 966f609906 buffer: Make recyclable; add peek + align
Allow Buffer to be reset from either Bytes or an unowned uint8[] without
allocating intermediate Bytes objects.

Extend BufferReader with peeking and alignment helpers and make both
classes reusable through reset() semantics.

This enables zero-allocation parsing in hot paths such as kcdata
stackshot processing.
2026-02-22 15:30:25 +01:00
Ole André Vadla Ravnås 889576e1d5 linux: Simplify build_signatures_variant()
The null-check was a leftover from the older API.
2026-02-21 15:29:38 +01:00
Ole André Vadla Ravnås bb9d9bc6a8 linux: Use int32 for syscall numbers
For consistency with Darwin.
2026-02-21 15:29:34 +01:00
Ole André Vadla Ravnås fc2e14a7cf linux: Simplify the syscall event variant logic 2026-02-21 11:31:00 +01:00
Ole André Vadla Ravnås 868166c23a buffer: Add BufferReader.seek() 2026-02-20 22:19:09 +01:00
Ole André Vadla Ravnås 4d7a0464fb dns: Avoid allocating Bytes object needlessly 2026-02-20 12:42:43 +01:00
Ole André Vadla Ravnås 150e4425ed buffer: Add read_data() to Buffer and BufferReader
To access the raw data without having to allocate a new Bytes object.
2026-02-20 12:39:45 +01:00
Ole André Vadla Ravnås 6bbef7880f buffer: Make read_bytes() zero-copy 2026-02-20 12:39:45 +01:00
Ole André Vadla Ravnås 963a8de514 buffer: Optimize read_fixed_string()
We can't avoid copying, but at least don't waste time on UTF-8
validation. This should be done at the higher level.
2026-02-20 12:39:45 +01:00
Ole André Vadla Ravnås fdb0eebb5e buffer: Optimize read_string()
- Do not copy. The caller should make a copy if the string needs to
  outlive the Buffer/BufferReader.
- Do not validate. This should be done at the higher level.
2026-02-20 12:39:44 +01:00
Ole André Vadla Ravnås ea26ae84b7 subprojects: Bump outdated 2026-02-18 22:53:56 +01:00
Ole André Vadla Ravnås 69016b9d5b submodules: Bump releng 2026-02-18 22:53:55 +01:00
03afdb072a websocket: Pause libsoup input to avoid starvation
Co-authored-by: Håvard Sørbø <[email protected]>
Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2026-02-18 22:52:39 +01:00
bf0830c1a2 network-stack: Handle incoming datagrams async
Incoming datagram delivery previously blocked while waiting for lwIP
thread work to complete.

Switch handle_incoming_datagrams() to an async API and schedule the
processing on the lwIP thread without joining immediately.

Use this to pace callers so they don't monopolize the GLib.MainContext
when floods of datagrams are coming in.

Co-authored-by: Håvard Sørbø <[email protected]>
Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2026-02-18 22:52:39 +01:00
Kerbiter 4aac1ae324 compat: Include x86_64 in Windows x86 builds 2026-02-18 22:28:31 +01:00
Ole André Vadla Ravnås e74d51dd13 keyed-archive: Make to_string() prettier 2026-02-18 01:07:43 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 984413c057 keyed-archive: Improve to_string() support
Intended for debugging during development.

Co-authored-by: Håvard Sørbø <[email protected]>
2026-02-17 23:55:02 +01:00
Ole André Vadla RavnåsandHåvard Sørbø ed78ab19d7 keyed-archive: Support NSSet
Only encoding for now.

Co-authored-by: Håvard Sørbø <[email protected]>
2026-02-17 23:54:57 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 5b877cbbff dtx: Upgrade protocol handling
- Rename DTXMessageType.INVOKE to DISPATCH.
- Rename DTXMessageType.RESULT to OBJECT.
- Fix channel code and is_notification logic.
- Add missing message types.
- Support data messages.
- Do not advertise compression support. We don't support it yet.

Co-authored-by: Håvard Sørbø <[email protected]>
2026-02-17 23:54:54 +01:00
Ole André Vadla Ravnås 3f3457b249 subprojects: Prepare for release 2026-02-16 22:45:39 +01:00
Ole André Vadla Ravnås f1c0e87871 subprojects: Bump outdated 2026-02-16 22:08:06 +01:00
Ole André Vadla Ravnås 6096046b05 syscall-tracer: Decode timespec values
Recognize timespec pointer arguments and decode them into structured
values rather than emitting opaque byte arrays.

Supports both __kernel_timespec and old_timespec32 layouts.
2026-02-16 21:27:26 +01:00
Ole André Vadla Ravnås c0815c4d1a syscall-tracer: Fix a stylistic inconsistency 2026-02-16 21:24:05 +01:00
Ole André Vadla Ravnås ab42fcb1ed syscall-tracer: Remove a redundant check 2026-02-16 21:23:52 +01:00
Ole André Vadla Ravnås cd0a327a3c syscall-tracer: Fix raw attachment lifetime
The GVariant was previously created from data freed before return,
leaving it with a dangling pointer.
2026-02-16 21:01:17 +01:00
Ole André Vadla Ravnås 51ff27a08b syscall-tracer: Fix multi-attachment parsing
Fix parsing of multiple attachments by encoding how much space is
reserved for each attachment.
2026-02-16 20:56:54 +01:00
Ole André Vadla Ravnås 6b54eeb7d8 subprojects: Prepare for release 2026-02-14 10:52:09 +01:00
Ole André Vadla Ravnås 08de3d3d07 subprojects: Bump outdated 2026-02-14 10:50:25 +01:00
Ole André Vadla Ravnås 174b93cbd4 xpc-service: Drop support for redundant casts 2026-02-14 10:44:29 +01:00
Ole André Vadla Ravnås d0f8162a65 android: Fix a stylistic inconsistency 2026-02-13 22:53:59 +01:00
Ole André Vadla Ravnås a3427baeb3 subprojects: Prepare for release 2026-02-13 22:48:30 +01:00
Ole André Vadla Ravnås c792a09002 subprojects: Bump outdated 2026-02-13 22:47:31 +01:00
Ole André Vadla Ravnås 27605f7fde android: Defer spawn completion until setArgV0()
Only record the package name in selinux_android_setcontext(), and delay
contacting RoboLauncher until setArgV0(). This ensures ART is ready so
frida-java-bridge can attach to the VM.

Also refactor Zymbiote code and improve naming.
2026-02-13 22:46:03 +01:00
Ole André Vadla Ravnås ba8784fe8c subprojects: Prepare for release 2026-02-13 15:12:30 +01:00
Ole André Vadla Ravnås 0a6c2103fa subprojects: Bump outdated 2026-02-13 15:09:43 +01:00
Ole André Vadla Ravnås 14de0ef567 android: Fix spawn package name logic on new OSes
Where we should be hooking selinux_android_setcontext() to infer it,
like we used to.
2026-02-13 14:39:22 +01:00
Ole André Vadla Ravnås 4165572919 linux: Avoid repeated /proc/pid/maps parsing
By folding the ProcMapsSoEntry functionality into ProcMapsSnapshot.
2026-02-13 14:39:17 +01:00
129 changed files with 11554 additions and 3515 deletions

No files matched your search

+5 -3
View File
@@ -331,7 +331,7 @@ jobs:
if: startsWith(matrix.id, 'android-')
id: setup-ndk
with:
ndk-version: r25c
ndk-version: r29
- name: Add NDK to env
if: startsWith(matrix.id, 'android-')
run: echo ANDROID_NDK_ROOT=${{ steps.setup-ndk.outputs.ndk-path }} >> $GITHUB_ENV
@@ -428,6 +428,7 @@ jobs:
# in, and we want to ensure that they are up-to-date with respect to the source
# for all architectures.
check-linux-helpers:
if: false
strategy:
matrix:
arch: [x86, x86_64, arm, armbe8, arm64, arm64be, arm64beilp32, mips, mipsel, mips64, mips64el]
@@ -445,7 +446,7 @@ jobs:
- name: Check for unexpected changes
run: |
git config --global --add safe.directory "$(realpath .)"
status_output=$(git status --porcelain tests/labrats/{resident-agent,simple-agent}-linux-${{ matrix.arch }}.so tests/labrats/{forker,sleeper,spawner}-linux-${{ matrix.arch }})
status_output=$(git status --porcelain src/linux/helpers/artifacts)
if [ -n "$status_output" ]; then
echo "Unexpected changes detected:"
echo "$status_output"
@@ -461,6 +462,7 @@ jobs:
# in, and we want to ensure that they are up-to-date with respect to the source
# for all architectures.
check-labrats:
if: false
strategy:
matrix:
arch: [x86, x86_64, arm, armbe8, arm64, arm64be, arm64beilp32, mips, mipsel, mips64, mips64el]
@@ -478,7 +480,7 @@ jobs:
- name: Check for unexpected changes
run: |
git config --global --add safe.directory "$(realpath .)"
status_output=$(git status --porcelain src/linux/helpers/{bootstrapper,loader}-${{ matrix.arch }}.bin)
status_output=$(git status --porcelain tests/labrats/{resident-agent,simple-agent}-linux-${{ matrix.arch }}.so tests/labrats/{forker,sleeper,spawner}-linux-${{ matrix.arch }})
if [ -n "$status_output" ]; then
echo "Unexpected changes detected:"
echo "$status_output"
+19 -8
View File
@@ -149,9 +149,20 @@ def setup(role: Role,
other_triplet: Optional[str] = None
extra_environ: dict[str, str] = {}
if host_os == "windows" and host_arch == "x86_64" and host_config == "mingw":
other_label = "x86"
have_toolchain, other_triplet = detect_mingw_toolchain_for("x86")
if host_os == "windows" and host_arch in {"x86_64", "x86"}:
if host_arch == "x86_64":
other_label = "x86"
other_kind = "legacy"
else:
other_label = "x86_64"
other_kind = "modern"
if host_config == "mingw":
have_toolchain, other_triplet = detect_mingw_toolchain_for(other_label)
else:
have_toolchain = True
other_triplet = None
elif host_os == "linux" and host_arch == "x86_64" and host_config is None:
other_label = "x86"
other_triplet = "i686-linux-gnu"
@@ -179,21 +190,21 @@ def setup(role: Role,
raise ToolchainNotFoundError(f"unable to locate toolchain for {other_triplet}")
missing.append(MissingFeature(other_label, other_triplet))
if host_os == "windows" and host_arch == "x86_64" and have_toolchain:
group = OutputGroup("x86", other_triplet, extra_environ)
if host_os == "windows" and host_arch in {"x86_64", "x86"} and have_toolchain:
group = OutputGroup(other_label, other_triplet, extra_environ)
outputs[group] = [
Output(identifier="helper_legacy",
Output(identifier=f"helper_{other_kind}",
name=HELPER_FILE_WINDOWS.name,
file=HELPER_FILE_WINDOWS,
target=HELPER_TARGET),
Output(identifier="agent_legacy",
Output(identifier=f"agent_{other_kind}",
name=AGENT_FILE_WINDOWS.name,
file=AGENT_FILE_WINDOWS,
target=AGENT_TARGET),
]
if "gadget" in components:
outputs[group] += [
Output(identifier="gadget_legacy",
Output(identifier=f"gadget_{other_kind}",
name=GADGET_FILE_WINDOWS.name,
file=GADGET_FILE_WINDOWS,
target=GADGET_TARGET),
+2 -15
View File
@@ -4,27 +4,14 @@ inject_sources = [
]
system_vala_args = []
if host_os_family != 'windows'
system_vala_args += ['--pkg=posix']
endif
extra_link_args = []
extra_link_depends = []
if host_os_family == 'darwin'
symlist = 'frida-inject.symbols'
extra_link_args += ['-Wl,-exported_symbols_list,' + meson.current_source_dir() / symlist]
extra_link_depends += [symlist]
elif host_os_family != 'windows'
symscript = 'frida-inject.version'
extra_link_args += ['-Wl,--version-script,' + meson.current_source_dir() / symscript]
extra_link_depends += [symscript]
endif
raw_inject = executable('frida-inject-raw', inject_sources,
vala_args: [core_vala_args, system_vala_args],
link_args: extra_link_args,
link_depends: extra_link_depends,
link_args: executable_no_exports_link_args,
link_depends: executable_no_exports_link_depends,
dependencies: [json_glib_dep, core_dep],
)
+2
View File
@@ -51,6 +51,8 @@ void
_frida_agent_environment_deinit (void)
{
#ifndef HAVE_MUSL
frida_libc_shim_prepare_to_deinit ();
gum_shutdown ();
gio_shutdown ();
glib_shutdown ();
+14
View File
@@ -0,0 +1,14 @@
FRIDA_1.0 {
global:
frida_agent_main;
local:
*;
};
GLIBC_2.2.5 {
local:
fopen*;
fseeko*;
ftello*;
} FRIDA_1.0;
+7 -1
View File
@@ -28,7 +28,13 @@ if host_os_family == 'windows'
elif host_os_family == 'darwin'
extra_link_args += '-Wl,-exported_symbol,_frida_agent_main'
else
symscript = (host_os == 'android') ? 'frida-agent-android.version' : 'frida-agent.version'
if libc == 'glibc'
symscript = 'frida-agent-glibc.version'
elif host_os == 'android'
symscript = 'frida-agent-android.version'
else
symscript = 'frida-agent.version'
endif
extra_link_args += '-Wl,--version-script,' + meson.current_source_dir() / symscript
extra_link_depends += symscript
endif
+262 -127
View File
@@ -309,8 +309,17 @@ namespace Frida {
public sealed class Buffer : Object {
public Bytes bytes {
get;
construct;
get {
if (_bytes == null)
_bytes = new Bytes.static (_data);
return _bytes;
}
}
public size_t size {
get {
return _data.length;
}
}
public ByteOrder byte_order {
@@ -323,20 +332,39 @@ namespace Frida {
construct;
}
private unowned uint8 * data;
private size_t size;
private Bytes? _bytes;
private unowned uint8[] _data;
public Buffer (Bytes bytes, ByteOrder byte_order = HOST, uint pointer_size = (uint) sizeof (size_t)) {
Object (
bytes: bytes,
byte_order: byte_order,
pointer_size: pointer_size
);
reset_bytes (bytes);
}
construct {
data = bytes.get_data ();
size = bytes.get_size ();
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) {
@@ -470,17 +498,13 @@ namespace Frida {
return *((double *) &bits);
}
public string read_string (size_t offset) throws Error {
public unowned string read_string (size_t offset) throws Error {
string * start = (string *) get_pointer (offset, sizeof (char));
size_t max_length = size - offset;
size_t max_length = _data.length - offset;
string * end = memchr (start, 0, max_length);
if (end == null)
throw new Error.PROTOCOL ("Missing null character");
size_t size = end - start;
string val = start->substring (0, (long) size);
if (!val.validate ())
throw new Error.PROTOCOL ("Invalid UTF-8 string");
return val;
return start;
}
[CCode (cname = "memchr", cheader_filename = "string.h")]
@@ -488,17 +512,14 @@ namespace Frida {
public string read_fixed_string (size_t offset, size_t size) throws Error {
string * start = (string *) get_pointer (offset, size);
size_t max_length = size_t.min (size, this.size - offset);
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;
string val = start->substring (0, (long) n);
if (!val.validate ())
throw new Error.PROTOCOL ("Invalid UTF-8 string");
return val;
return start->substring (0, (long) n);
}
public unowned Buffer write_string (size_t offset, string val) {
@@ -508,9 +529,14 @@ namespace Frida {
}
public Bytes read_bytes (size_t offset, size_t size) {
var data = new uint8[size + 1];
Memory.copy (data, get_pointer (offset, size), size);
return new Bytes.take ((owned) data);
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) {
@@ -521,129 +547,49 @@ namespace Frida {
private uint8 * get_pointer (size_t offset, size_t n) {
size_t minimum_size = offset + n;
assert (size >= minimum_size);
return data + offset;
assert (_data.length >= minimum_size);
return (uint8 *) _data + offset;
}
}
public sealed class BufferReader {
public Buffer buffer {
get;
}
public size_t offset {
get {
return _offset;
}
get;
}
public size_t available {
get {
return buffer.bytes.get_size () - _offset;
return _size - _offset;
}
}
private Buffer buffer;
private size_t _offset = 0;
private size_t _size;
public BufferReader (Buffer buf) {
buffer = buf;
public BufferReader (Buffer buffer) {
reset (buffer);
}
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 void reset (Buffer buffer) {
_buffer = buffer;
_size = buffer.size;
_offset = 0;
}
public int8 read_int8 () throws Error {
check_available (sizeof (int8));
var val = buffer.read_int8 (_offset);
_offset += sizeof (int8);
return val;
public void reset_at (Buffer buffer, size_t offset) throws Error {
_buffer = buffer;
_size = buffer.size;
seek (offset);
}
public uint8 read_uint8 () throws Error {
check_available (sizeof (uint8));
var val = buffer.read_uint8 (_offset);
_offset += sizeof (uint8);
return val;
}
public int16 read_int16 () throws Error {
check_available (sizeof (int16));
var val = buffer.read_int16 (_offset);
_offset += sizeof (int16);
return val;
}
public uint16 read_uint16 () throws Error {
check_available (sizeof (uint16));
var val = buffer.read_uint16 (_offset);
_offset += sizeof (uint16);
return val;
}
public int32 read_int32 () throws Error {
check_available (sizeof (int32));
var val = buffer.read_int32 (_offset);
_offset += sizeof (int32);
return val;
}
public uint32 read_uint32 () throws Error {
check_available (sizeof (uint32));
var val = buffer.read_uint32 (_offset);
_offset += sizeof (uint32);
return val;
}
public int64 read_int64 () throws Error {
check_available (sizeof (int64));
var val = buffer.read_int64 (_offset);
_offset += sizeof (int64);
return val;
}
public uint64 read_uint64 () throws Error {
check_available (sizeof (uint64));
var val = buffer.read_uint64 (_offset);
_offset += sizeof (uint64);
return val;
}
public float read_float () throws Error {
check_available (sizeof (float));
var val = buffer.read_float (_offset);
_offset += sizeof (float);
return val;
}
public double read_double () throws Error {
check_available (sizeof (double));
var val = buffer.read_double (_offset);
_offset += sizeof (double);
return val;
}
public string read_string () throws Error {
check_available (1);
var val = buffer.read_string (_offset);
_offset += val.length + 1;
return val;
}
public string read_fixed_string (size_t size) throws Error {
check_available (size);
var val = buffer.read_fixed_string (_offset, size);
_offset += size;
return val;
}
public Bytes read_bytes (size_t size) throws Error {
check_available (size);
var val = buffer.bytes[_offset:_offset + size];
_offset += size;
return val;
public unowned BufferReader 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 {
@@ -652,6 +598,195 @@ namespace Frida {
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");
+12 -2
View File
@@ -1,18 +1,26 @@
#ifndef __FRIDA_ATOMICS_H__
#define __FRIDA_ATOMICS_H__
#include <glib.h>
G_BEGIN_DECLS
#ifdef _MSC_VER
/* TODO: Add once needed. */
#else
static inline guint64 frida_atomics_load_u64_acquire (volatile guint64 * p)
typedef guint64 FridaAtomicU64 __attribute__ ((aligned (8)));
static inline guint64
frida_atomics_load_u64_acquire (volatile FridaAtomicU64 * p)
{
return __atomic_load_n (p, __ATOMIC_ACQUIRE);
}
static inline void frida_atomics_store_u64_release (volatile guint64 * p, guint64 v)
static inline void
frida_atomics_store_u64_release (volatile FridaAtomicU64 * p, guint64 v)
{
__atomic_store_n (p, v, __ATOMIC_RELEASE);
}
@@ -24,4 +32,6 @@ static inline guint32 frida_atomics_load_u32_acquire (volatile guint32 * p)
#endif
G_END_DECLS
#endif
+3 -3
View File
@@ -1,6 +1,6 @@
[CCode (cheader_filename = "frida-atomics.h")]
namespace Frida.Atomics {
public static uint64 load_u64_acquire (void * p);
public static void store_u64_release (void * p, uint64 v);
public static uint32 load_u32_acquire (void * p);
public static uint64 load_u64_acquire (uint64 * p);
public static void store_u64_release (uint64 * p, uint64 v);
public static uint32 load_u32_acquire (uint32 * p);
}
+4
View File
@@ -6,6 +6,8 @@
#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);
@@ -17,6 +19,8 @@ void _frida_xpc_connection_send_message_with_reply (xpc_connection_t connection,
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
+41
View File
@@ -0,0 +1,41 @@
#ifndef __FRIDA_JNI_H__
#define __FRIDA_JNI_H__
#include <jni.h>
G_BEGIN_DECLS
typedef jint (* JNIDestroyJavaVMFunc) (JavaVM *);
typedef jint (* JNIAttachCurrentThreadFunc) (JavaVM *, JNIEnv **, void *);
typedef jint (* JNIDetachCurrentThreadFunc) (JavaVM *);
typedef jint (* JNIGetEnvFunc) (JavaVM *, JNIEnv **, jint);
typedef jclass (* JNIFindClassFunc) (JNIEnv *, const char *);
typedef jthrowable (* JNIExceptionOccurredFunc) (JNIEnv *);
typedef void (* JNIExceptionDescribeFunc) (JNIEnv *);
typedef void (* JNIExceptionClearFunc) (JNIEnv *);
typedef jint (* JNIPushLocalFrameFunc) (JNIEnv *, jint);
typedef jobject (* JNIPopLocalFrameFunc) (JNIEnv *, jobject);
typedef jobject (* JNINewGlobalRefFunc) (JNIEnv *, jobject);
typedef void (* JNIDeleteGlobalRefFunc) (JNIEnv *, jobject);
typedef void (* JNIDeleteLocalRefFunc) (JNIEnv *, jobject);
typedef jobject (* JNINewObjectFunc) (JNIEnv *, jclass, jmethodID, ...);
typedef jclass (* JNIGetObjectClassFunc) (JNIEnv *, jobject);
typedef jmethodID (* JNIGetMethodIDFunc) (JNIEnv *, jclass, const char *, const char *);
typedef jobject (* JNICallObjectMethodFunc) (JNIEnv *, jobject, jmethodID, ...);
typedef jstring (* JNINewStringUTFFunc) (JNIEnv *, const char *);
typedef const char * (* JNIGetStringUTFCharsFunc) (JNIEnv *, jstring, jboolean *);
typedef void (* JNIReleaseStringUTFCharsFunc) (JNIEnv *, jstring, const char *);
typedef jboolean (* JNIExceptionCheckFunc) (JNIEnv *);
G_END_DECLS
#endif
+14 -2
View File
@@ -46,7 +46,7 @@ namespace Frida {
public extern unowned LinuxSyscallSignature[]? get_compat32_syscall_signatures ();
public struct LinuxSyscallSignature {
public uint nr;
public int nr;
public string name;
public uint8 nargs;
public LinuxSyscallArg args[6];
@@ -141,7 +141,7 @@ namespace Frida {
private char[] kernel_log_buf;
public static BpfObject open (string name, uint8[] blob) throws Error {
var log_buf = new char[64 * 1024];
var log_buf = new char[128 * 1024];
var opts = Libbpf.Object.OpenOpts ();
opts.sz = sizeof (Libbpf.Object.OpenOpts);
@@ -348,6 +348,18 @@ namespace Frida {
remove_raw ((uint8[]) &key);
}
public void update_u64_u8 (uint64 key, uint8 val) throws Error {
update_raw ((uint8[]) &key, (uint8[]) &val);
}
public void update_u64_u32 (uint64 key, uint32 val) throws Error {
update_raw ((uint8[]) &key, (uint8[]) &val);
}
public void remove_u64 (uint64 key) throws Error {
remove_raw ((uint8[]) &key);
}
public void foreach_percpu_value<T> (uint8[] key, PercpuValueFunc<T> func) throws Error {
var ncpus = check_libbpf_result (Libbpf.num_possible_cpus ());
var percpu_stride = round_up_8 (value_size);
+2
View File
@@ -15,6 +15,8 @@ base_sources = [
'buffer.vala',
'buffer-glue.c',
'value.vala',
'xnu-syscalls' / 'xnu-syscalls.vala',
'xnu-syscalls' / 'xnu-syscalls-glue.c',
]
extra_vala_args = []
+12 -1
View File
@@ -2170,7 +2170,10 @@ namespace Frida {
public static string enum_to_nick<T> (int val) {
var klass = (EnumClass) typeof (T).class_ref ();
return klass.get_value (val).value_nick;
unowned EnumValue? v = klass.get_value (val);
if (v == null)
return "unknown-0x%x".printf (val);
return v.value_nick;
}
}
@@ -2196,5 +2199,13 @@ namespace Frida {
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;
}
}
}
+4
View File
@@ -940,6 +940,9 @@ namespace Frida {
Memory.copy (buffer, recv_queue.data, n);
recv_queue.remove_range (0, (uint) n);
if (recv_queue.len == 0)
websocket.resume_input ();
update_pending_io ();
} else {
if (state == OPEN)
@@ -1006,6 +1009,7 @@ namespace Frida {
private void on_message (int type, Bytes message) {
with_state_lock (() => {
recv_queue.append (message.get_data ());
websocket.pause_input ();
update_pending_io ();
});
}
+860
View File
@@ -0,0 +1,860 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import argparse
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple
MAX_ARGS = 9
@dataclass(frozen=True)
class SyscallArg:
type: str
name: str
@dataclass(frozen=True)
class SyscallSignature:
name: str
args: Tuple[SyscallArg, ...]
MACH_TRAP_INDEXED_CALL_RE = re.compile(r"/\*\s*(?P<idx>\d+)\s*\*/\s*MACH_TRAP\s*\(")
MACH_TRAPS_IFNDEF_KERNEL_RE = re.compile(r"^\s*#ifndef\s+KERNEL\b", re.MULTILINE)
MACH_TRAPS_ELSE_KERNEL_RE = re.compile(r"^\s*#else\b.*\bKERNEL\b", re.MULTILINE)
USER_EXTERN_PROTO_RE = re.compile(
r"^\s*extern\s+(?P<ret>.+?)\s+(?P<fn>[A-Za-z_]\w*)\s*\((?P<args>.*?)\)\s*;",
re.MULTILINE | re.DOTALL,
)
KERNEL_STRUCT_RE = re.compile(
r"\bstruct\s+(?P<name>[A-Za-z_]\w*)\s*\{\s*(?P<body>.*?)\s*\}\s*;",
re.DOTALL,
)
KERNEL_TRAP_EXTERN_RE = re.compile(
r"^\s*(?:extern\s+)?(?P<ret>.+?)\s+(?P<fn>[A-Za-z_]\w*)\s*\(\s*struct\s+(?P<args_struct>[A-Za-z_]\w*)\s*\*\s*args\s*\)\s*;",
re.MULTILINE | re.DOTALL,
)
PAD_ARG_RE = re.compile(
r"\bPAD_ARG_\s*\(\s*(?P<ty>[^,]+?)\s*,\s*(?P<name>[^)]+?)\s*\)\s*;",
)
PLAIN_FIELD_RE = re.compile(r"^\s*(?P<ty>.+?)\s+(?P<name>[A-Za-z_]\w*)\s*;\s*$")
BSD_MASTER_ENTRY_RE = re.compile(
r"^\s*(?P<nr>\d+)\s+(?P<audit>\S+)\s+(?P<files>\S+)\s+\{\s*(?P<proto>[^}]+?)\s*\}\s*(?:\{.*\})?\s*$"
)
BSD_MASTER_PROTO_RE = re.compile(
r"^\s*(?P<ret>.+?)\s+(?P<fn>[A-Za-z_]\w*)\s*\((?P<args>.*)\)\s*(?P<attrs>.*)$",
re.DOTALL,
)
LINE_COMMENT_RE = re.compile(r"//.*$")
BLOCK_COMMENT_RE = re.compile(r"/\*[^*]*\*+(?:[^/*][^*]*\*+)*/")
TRAILING_ARRAY_SUFFIX_RE = re.compile(r"\[[^\]]*\]\s*$")
POINTER_SPACING_RE = re.compile(r"\s*\*\s*")
PARAM_NAME_RE = re.compile(r"[A-Za-z_]\w*$")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--kernel-tree", required=True)
ap.add_argument("--out-vala", required=True)
ap.add_argument("--out-c", required=True)
args = ap.parse_args()
kernel_tree = Path(args.kernel_tree).resolve()
if not kernel_tree.exists():
raise SystemExit(f"--kernel-tree does not exist: {kernel_tree}")
mach_numbers, mach_sigs = load_mach_traps(kernel_tree)
bsd_numbers, bsd_sigs = load_bsd_syscalls_master(kernel_tree)
vala = render_vala(
mach_numbers=mach_numbers,
bsd_numbers=bsd_numbers,
)
c_src = render_c_source(
mach_numbers=mach_numbers,
bsd_numbers=bsd_numbers,
mach_sigs=mach_sigs,
bsd_sigs=bsd_sigs,
)
out_vala = Path(args.out_vala)
out_c = Path(args.out_c)
out_vala.parent.mkdir(parents=True, exist_ok=True)
out_c.parent.mkdir(parents=True, exist_ok=True)
out_vala.write_text(vala, encoding="utf-8")
out_c.write_text(c_src, encoding="utf-8")
return 0
def load_mach_traps(
kernel_tree: Path,
) -> Tuple[Dict[int, str], Dict[str, SyscallSignature]]:
table_path = kernel_tree / "osfmk" / "kern" / "syscall_sw.c"
if not table_path.exists():
raise RuntimeError(f"Missing Mach trap table source: {table_path}")
header_path = kernel_tree / "osfmk" / "mach" / "mach_traps.h"
if not header_path.exists():
raise RuntimeError(f"Missing Mach traps header: {header_path}")
table_text = table_path.read_text(encoding="utf-8", errors="ignore")
trap_routines = parse_mach_trap_table(table_text, table_path)
header_text = header_path.read_text(encoding="utf-8", errors="ignore")
userspace_text, kernel_text = split_mach_traps_header(header_text, header_path)
userspace_protos = parse_userspace_mach_traps_prototypes(
userspace_text, header_path
)
kernel_argmap = parse_kernel_mach_traps_args(kernel_text, header_path)
numbers: Dict[int, str] = {}
sigs: Dict[str, SyscallSignature] = {}
for index, routine in trap_routines:
if routine == "kern_invalid":
continue
nr = -index
public_name = normalize_mach_name(routine)
if public_name == "":
raise RuntimeError(f"{table_path}: empty normalized name from {routine!r}")
if nr in numbers:
raise RuntimeError(f"{table_path}: duplicate mach trap number {nr}")
if public_name in sigs:
raise RuntimeError(
f"{table_path}: normalized Mach name collision for {public_name!r}"
)
args = resolve_mach_trap_signature(
routine=routine,
userspace_protos=userspace_protos,
kernel_argmap=kernel_argmap,
table_path=table_path,
)
if len(args) > MAX_ARGS:
raise RuntimeError(
f"{table_path}: trap {routine!r} has {len(args)} args; max supported is {MAX_ARGS}"
)
numbers[nr] = public_name
sigs[public_name] = SyscallSignature(name=public_name, args=tuple(args))
return numbers, sigs
def parse_mach_trap_table(text: str, path: Path) -> List[Tuple[int, str]]:
anchor = text.find("mach_trap_table")
if anchor == -1:
raise RuntimeError(f"{path}: mach_trap_table not found")
brace = text.find("{", anchor)
if brace == -1:
raise RuntimeError(f"{path}: mach_trap_table '{{' not found")
payload, _ = extract_brace_payload(text, brace, path)
by_index: Dict[int, str] = {}
off = 0
while True:
m = MACH_TRAP_INDEXED_CALL_RE.search(payload, off)
if m is None:
break
idx = int(m.group("idx"), 10)
open_paren = m.end(0) - 1
args_blob, end_off = extract_parentheses_payload(payload, open_paren, path)
parts = [
a.strip() for a in split_top_level_commas(args_blob) if a.strip() != ""
]
if len(parts) < 1:
raise RuntimeError(f"{path}: bad MACH_TRAP() entry: {args_blob!r}")
routine = parts[0]
prev = by_index.get(idx)
if prev is None:
by_index[idx] = routine
else:
if prev == routine:
pass
elif prev == "kern_invalid" and routine != "kern_invalid":
by_index[idx] = routine
elif routine == "kern_invalid" and prev != "kern_invalid":
pass
else:
raise RuntimeError(
f"{path}: conflicting MACH_TRAP entries for index {idx}: {prev!r} vs {routine!r}"
)
off = end_off
return sorted(by_index.items(), key=lambda kv: kv[0])
def split_mach_traps_header(text: str, path: Path) -> Tuple[str, str]:
m_start = MACH_TRAPS_IFNDEF_KERNEL_RE.search(text)
if m_start is None:
raise RuntimeError(f"{path}: missing '#ifndef KERNEL'")
m_else = MACH_TRAPS_ELSE_KERNEL_RE.search(text, m_start.end())
if m_else is None:
raise RuntimeError(f"{path}: missing '#else ... KERNEL ...'")
userspace = text[m_start.end():m_else.start()]
kernel = text[m_else.end():]
return userspace, kernel
def parse_userspace_mach_traps_prototypes(
userspace_text: str, path: Path
) -> Dict[str, Tuple[SyscallArg, ...]]:
protos: Dict[str, Tuple[SyscallArg, ...]] = {}
for m in USER_EXTERN_PROTO_RE.finditer(userspace_text):
fn = m.group("fn").strip()
args_blob = m.group("args").strip()
ret_blob = strip_c_comments(m.group("ret")).strip()
if ret_blob == "":
raise RuntimeError(f"{path}: empty return type for {fn!r}")
line_no = line_number_at_offset(userspace_text, m.start())
args = parse_c_param_list(args_blob, path, line_no)
cur = tuple(args)
prev = protos.get(fn)
if prev is not None and prev != cur:
raise RuntimeError(f"{path}:{line_no}: conflicting prototype for {fn!r}")
protos[fn] = cur
return protos
def parse_kernel_mach_traps_args(
kernel_text: str, path: Path
) -> Dict[str, Tuple[SyscallArg, ...]]:
text = strip_c_comments(kernel_text)
structs: Dict[str, str] = {}
for m in KERNEL_STRUCT_RE.finditer(text):
name = m.group("name").strip()
body = m.group("body")
structs[name] = body
fn_to_struct: Dict[str, str] = {}
for m in KERNEL_TRAP_EXTERN_RE.finditer(text):
fn = m.group("fn").strip()
args_struct = m.group("args_struct").strip()
fn_to_struct[fn] = args_struct
out: Dict[str, Tuple[SyscallArg, ...]] = {}
for fn, args_struct in fn_to_struct.items():
body = structs.get(args_struct)
if body is None:
continue
args = parse_mach_args_struct_body(body, path)
out[fn] = tuple(args)
return out
def parse_mach_args_struct_body(body: str, path: Path) -> List[SyscallArg]:
args: List[SyscallArg] = []
body = strip_c_comments(body)
for raw_ln in body.splitlines():
ln = raw_ln.strip()
if ln == "" or ln.startswith("#"):
continue
if "PAD_ARG_8" in ln:
continue
m = PAD_ARG_RE.search(ln)
if m is not None:
ty = normalize_whitespace(m.group("ty").strip())
name = normalize_whitespace(m.group("name").strip())
if ty == "" or name == "":
raise RuntimeError(f"{path}: bad PAD_ARG_ in args struct: {raw_ln!r}")
args.append(SyscallArg(type=ty, name=name))
continue
m = PLAIN_FIELD_RE.match(ln)
if m is not None:
ty = normalize_whitespace(m.group("ty").strip())
name = m.group("name").strip()
if ty == "" or name == "":
raise RuntimeError(f"{path}: bad field in args struct: {raw_ln!r}")
args.append(SyscallArg(type=ty, name=name))
continue
if len(args) == 1 and args[0].name == "dummy":
return []
return args
def resolve_mach_trap_signature(
*,
routine: str,
userspace_protos: Dict[str, Tuple[SyscallArg, ...]],
kernel_argmap: Dict[str, Tuple[SyscallArg, ...]],
table_path: Path,
) -> List[SyscallArg]:
def get_userspace(name: str) -> Optional[Tuple[SyscallArg, ...]]:
return userspace_protos.get(name)
def get_kernel(name: str) -> Optional[Tuple[SyscallArg, ...]]:
return kernel_argmap.get(name)
proto_args = get_userspace(routine)
if proto_args is None and routine.endswith("_trap"):
proto_args = get_userspace(routine[: -len("_trap")])
if proto_args is not None:
return list(proto_args)
proto_args = get_kernel(routine)
if proto_args is None and routine.endswith("_trap"):
proto_args = get_kernel(routine[: -len("_trap")])
if proto_args is None:
raise RuntimeError(
f"{table_path}: missing userspace prototype for {routine!r}, and no kernel extern(struct *_args *args) mapping found"
)
return list(proto_args)
def normalize_mach_name(routine: str) -> str:
if routine.startswith("_"):
routine = routine[1:]
if routine.startswith("kernelrpc_"):
routine = routine[len("kernelrpc_"):]
if routine.endswith("_trap"):
routine = routine[: -len("_trap")]
return routine
def load_bsd_syscalls_master(
kernel_tree: Path,
) -> Tuple[Dict[int, str], Dict[str, SyscallSignature]]:
path = kernel_tree / "bsd" / "kern" / "syscalls.master"
if not path.exists():
raise RuntimeError(f"Missing BSD master file: {path}")
numbers: Dict[int, str] = {}
sigs: Dict[str, SyscallSignature] = {}
lines = path.read_text(encoding="utf-8", errors="ignore").splitlines()
stack: List[bool] = []
active = True
for line_no, raw in enumerate(lines, start=1):
line = raw.rstrip("\n")
stripped = line.lstrip()
if (
stripped.startswith("#if ")
or stripped.startswith("#ifdef ")
or stripped.startswith("#ifndef ")
):
stack.append(active)
continue
if stripped.startswith("#else"):
if not stack:
raise RuntimeError(f"{path}:{line_no}: #else without #if")
active = False
continue
if stripped.startswith("#endif"):
if not stack:
raise RuntimeError(f"{path}:{line_no}: #endif without #if")
active = stack.pop()
continue
if not active:
continue
m = BSD_MASTER_ENTRY_RE.match(line)
if m is None:
continue
nr = int(m.group("nr"), 10)
proto_blob = strip_c_comments(m.group("proto")).strip()
mp = BSD_MASTER_PROTO_RE.match(proto_blob)
if mp is None:
raise RuntimeError(
f"{path}:{line_no}: cannot parse prototype: {proto_blob!r}"
)
fn = mp.group("fn").strip()
args_blob = mp.group("args").strip()
if fn in {"nosys", "enosys"}:
continue
public_name = normalize_bsd_name(fn)
if public_name == "":
raise RuntimeError(f"{path}:{line_no}: empty normalized name from {fn!r}")
if nr in numbers:
raise RuntimeError(f"{path}:{line_no}: duplicate syscall number {nr}")
if public_name in sigs:
raise RuntimeError(
f"{path}:{line_no}: duplicate syscall name {public_name!r}"
)
args = parse_c_param_list(args_blob, path, line_no)
if len(args) > MAX_ARGS:
raise RuntimeError(
f"{path}:{line_no}: syscall {public_name!r} has {len(args)} args; max supported is {MAX_ARGS}"
)
numbers[nr] = public_name
sigs[public_name] = SyscallSignature(name=public_name, args=tuple(args))
return numbers, sigs
def normalize_bsd_name(fn: str) -> str:
if fn.startswith("sys_"):
return fn[len("sys_"):]
if fn.startswith("__"):
return fn[2:]
return fn
def strip_c_comments(s: str) -> str:
s = LINE_COMMENT_RE.sub("", s)
while True:
new_s = BLOCK_COMMENT_RE.sub("", s)
if new_s == s:
break
s = new_s
return s
def split_top_level_commas(text: str) -> List[str]:
parts: List[str] = []
buf: List[str] = []
depth = 0
in_string = False
string_quote = ""
cursor = 0
while cursor < len(text):
ch = text[cursor]
if in_string:
buf.append(ch)
if ch == "\\" and cursor + 1 < len(text):
buf.append(text[cursor + 1])
cursor += 2
continue
if ch == string_quote:
in_string = False
cursor += 1
continue
if ch in ("'", '"'):
in_string = True
string_quote = ch
buf.append(ch)
cursor += 1
continue
if ch == "(":
depth += 1
elif ch == ")":
depth = max(0, depth - 1)
if ch == "," and depth == 0:
parts.append("".join(buf).strip())
buf = []
cursor += 1
continue
buf.append(ch)
cursor += 1
parts.append("".join(buf).strip())
return parts
def parse_c_param_list(args_blob: str, path: Path, line_no: int) -> List[SyscallArg]:
raw = strip_c_comments(args_blob).strip()
if raw == "" or raw == "void":
return []
raw_params = [p.strip() for p in split_top_level_commas(raw) if p.strip() != ""]
if len(raw_params) == 1 and raw_params[0] == "void":
return []
args: List[SyscallArg] = []
for idx, p in enumerate(raw_params):
ty, name = split_param_decl(p, path, line_no)
if name is None:
name = f"arg{idx}"
if ty == "user_addr_t" and name in {"attrname", "link", "path"}:
ty = "char *"
args.append(SyscallArg(type=ty, name=name))
return args
def split_param_decl(decl: str, path: Path, line_no: int) -> Tuple[str, Optional[str]]:
d = strip_c_comments(decl).strip()
if d == "" or d == "void":
raise RuntimeError(f"{path}:{line_no}: bad parameter decl: {decl!r}")
tokens = _tokenize_decl(d)
ty_tokens, name = _split_type_and_name(tokens)
ty = _format_type(ty_tokens)
if not ty:
raise RuntimeError(
f"{path}:{line_no}: cannot parse parameter type from {decl!r}"
)
return ty, _camel_to_snake(name) if name else None
def _tokenize_decl(s: str) -> list[str]:
out = []
for c in s:
out.append(" * " if c == "*" else c)
return "".join(out).split()
def _split_type_and_name(tokens: list[str]) -> Tuple[list[str], Optional[str]]:
if not tokens:
return [], None
last = tokens[-1]
if last == "*":
return tokens, None
stars, remainder = _split_leading_stars(last)
if stars:
if _is_identifier(remainder):
return tokens[:-1] + ["*"] * stars, remainder
return tokens, None
if _is_identifier(last):
return tokens[:-1], last
return tokens, None
def _format_type(tokens: list[str]) -> str:
formatted: list[str] = []
i = 0
while i < len(tokens):
if tokens[i] != "*":
formatted.append(tokens[i])
i += 1
continue
j = i
while j < len(tokens) and tokens[j] == "*":
j += 1
formatted.append("*" * (j - i))
i = j
return " ".join(formatted).strip()
def _split_leading_stars(token: str) -> Tuple[int, str]:
i = 0
while i < len(token) and token[i] == "*":
i += 1
return i, token[i:]
def _is_identifier(s: str) -> bool:
if not s:
return False
if not (s[0].isalpha() or s[0] == "_"):
return False
return all(c.isalnum() or c == "_" for c in s)
def _camel_to_snake(name: str) -> str:
out = []
for i, c in enumerate(name):
if (
c.isupper()
and i > 0
and (name[i - 1].islower() or (i + 1 < len(name) and name[i + 1].islower()))
):
out.append("_")
out.append(c.lower())
return "".join(out)
def normalize_whitespace(s: str) -> str:
return " ".join(s.split())
def line_number_at_offset(text: str, offset: int) -> int:
return text.count("\n", 0, offset) + 1
def extract_parentheses_payload(
text: str, open_paren_offset: int, path: Path
) -> Tuple[str, int]:
if (
open_paren_offset < 0
or open_paren_offset >= len(text)
or text[open_paren_offset] != "("
):
raise RuntimeError(f"{path}: expected '(' at offset {open_paren_offset}")
depth = 0
cursor = open_paren_offset
start = open_paren_offset + 1
in_string = False
string_quote = ""
while cursor < len(text):
ch = text[cursor]
if in_string:
if ch == "\\":
cursor += 2
continue
if ch == string_quote:
in_string = False
cursor += 1
continue
if ch in ("'", '"'):
in_string = True
string_quote = ch
cursor += 1
continue
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0:
return text[start:cursor], cursor + 1
cursor += 1
raise RuntimeError(f"{path}: unterminated parentheses payload")
def extract_brace_payload(
text: str, open_brace_offset: int, path: Path
) -> Tuple[str, int]:
if (
open_brace_offset < 0
or open_brace_offset >= len(text)
or text[open_brace_offset] != "{"
):
raise RuntimeError(f"{path}: expected '{{' at offset {open_brace_offset}")
depth = 0
cursor = open_brace_offset
start = open_brace_offset + 1
in_string = False
string_quote = ""
while cursor < len(text):
ch = text[cursor]
if in_string:
if ch == "\\":
cursor += 2
continue
if ch == string_quote:
in_string = False
cursor += 1
continue
if ch in ("'", '"'):
in_string = True
string_quote = ch
cursor += 1
continue
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return text[start:cursor], cursor + 1
cursor += 1
raise RuntimeError(f"{path}: unterminated brace payload")
def render_vala(*, mach_numbers: Dict[int, str], bsd_numbers: Dict[int, str]) -> str:
out: List[str] = []
out += [
"// AUTO-GENERATED FILE. DO NOT EDIT.\n",
"\n",
"namespace Frida {\n",
"\tpublic extern unowned XnuSyscallSignature[] get_xnu_mach_traps ();\n",
"\tpublic extern unowned XnuSyscallSignature[] get_xnu_bsd_syscalls ();\n",
"\n",
"\tpublic struct XnuSyscallSignature {\n",
"\t\tpublic int nr;\n",
"\t\tpublic string name;\n",
"\t\tpublic uint8 nargs;\n",
f"\t\tpublic XnuSyscallArg args[{MAX_ARGS}];\n",
"\t}\n",
"\n",
"\tpublic struct XnuSyscallArg {\n",
"\t\tpublic string? type;\n",
"\t\tpublic string? name;\n",
"\t}\n",
"\n",
"\tpublic enum XnuMachTrap {\n",
]
for nr, name in sorted(mach_numbers.items(), key=lambda kv: kv[0], reverse=True):
out += [f"\t\t{name.upper()} = {nr},\n"]
out += [
"\t}\n",
"\n",
"\tpublic enum XnuBsdSyscall {\n",
]
for nr, name in sorted(bsd_numbers.items(), key=lambda kv: kv[0]):
out += [f"\t\t{name.upper()} = {nr},\n"]
out += [
"\t}\n",
"}\n",
]
return "".join(out)
def render_c_source(
*,
mach_numbers: Dict[int, str],
bsd_numbers: Dict[int, str],
mach_sigs: Dict[str, SyscallSignature],
bsd_sigs: Dict[str, SyscallSignature],
) -> str:
out: List[str] = []
out += [
"/* AUTO-GENERATED FILE. DO NOT EDIT. */\n",
"\n",
'#include "frida-base.h"\n',
"\n",
]
emit_c_signature_table(
out,
c_var="frida_xnu_mach_traps",
numbers=mach_numbers,
sigs=mach_sigs,
reverse=True,
)
emit_c_signature_table(
out,
c_var="frida_xnu_bsd_syscalls",
numbers=bsd_numbers,
sigs=bsd_sigs,
)
emit_c_table_getter(
out, c_func="frida_get_xnu_mach_traps", c_var="frida_xnu_mach_traps"
)
out += ["\n"]
emit_c_table_getter(
out, c_func="frida_get_xnu_bsd_syscalls", c_var="frida_xnu_bsd_syscalls"
)
return "".join(out)
def emit_c_signature_table(
out: List[str],
*,
c_var: str,
numbers: Dict[int, str],
sigs: Dict[str, SyscallSignature],
reverse: bool = False,
) -> None:
out += [
f"static const FridaXnuSyscallSignature {c_var}[] =\n",
"{\n",
]
for nr, name in sorted(numbers.items(), key=lambda kv: kv[0], reverse=reverse):
sig = sigs[name]
args_parts: List[str] = []
for a in sig.args:
args_parts += [f"{{ {c_escape(a.type)}, {c_escape(a.name)} }}"]
args_blob = ", ".join(args_parts)
if args_blob != "":
out += [
f" {{ {nr}, {c_escape(name)}, {len(sig.args)}, {{ {args_blob} }} }},\n"
]
else:
out += [f" {{ {nr}, {c_escape(name)}, 0, {{}} }},\n"]
out += [
"};\n",
"\n",
]
def emit_c_table_getter(out: List[str], *, c_func: str, c_var: str) -> None:
out += [
"FridaXnuSyscallSignature *\n",
f"{c_func} (int * len)\n",
"{\n",
" if (len != NULL)\n",
f" *len = G_N_ELEMENTS ({c_var});\n",
f" return (FridaXnuSyscallSignature *) {c_var};\n",
"}\n",
]
def c_escape(s: str) -> str:
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
if __name__ == "__main__":
raise SystemExit(main())
+542
View File
@@ -0,0 +1,542 @@
/* AUTO-GENERATED FILE. DO NOT EDIT. */
#include "frida-base.h"
static const FridaXnuSyscallSignature frida_xnu_mach_traps[] =
{
{ -10, "mach_vm_allocate", 4, { { "mach_port_name_t", "target" }, { "mach_vm_offset_t *", "addr" }, { "mach_vm_size_t", "size" }, { "int", "flags" } } },
{ -11, "mach_vm_purgable_control", 4, { { "mach_port_name_t", "target" }, { "mach_vm_offset_t", "address" }, { "vm_purgable_t", "control" }, { "int *", "state" } } },
{ -12, "mach_vm_deallocate", 3, { { "mach_port_name_t", "target" }, { "mach_vm_address_t", "address" }, { "mach_vm_size_t", "size" } } },
{ -13, "task_dyld_process_info_notify_get", 2, { { "mach_port_name_array_t", "names_addr" }, { "natural_t *", "names_count_addr" } } },
{ -14, "mach_vm_protect", 5, { { "mach_port_name_t", "target" }, { "mach_vm_address_t", "address" }, { "mach_vm_size_t", "size" }, { "boolean_t", "set_maximum" }, { "vm_prot_t", "new_protection" } } },
{ -15, "mach_vm_map", 6, { { "mach_port_name_t", "target" }, { "mach_vm_offset_t *", "address" }, { "mach_vm_size_t", "size" }, { "mach_vm_offset_t", "mask" }, { "int", "flags" }, { "vm_prot_t", "cur_protection" } } },
{ -16, "mach_port_allocate", 3, { { "mach_port_name_t", "target" }, { "mach_port_right_t", "right" }, { "mach_port_name_t *", "name" } } },
{ -18, "mach_port_deallocate", 2, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "name" } } },
{ -19, "mach_port_mod_refs", 4, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "name" }, { "mach_port_right_t", "right" }, { "mach_port_delta_t", "delta" } } },
{ -20, "mach_port_move_member", 3, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "member" }, { "mach_port_name_t", "after" } } },
{ -21, "mach_port_insert_right", 4, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "name" }, { "mach_port_name_t", "poly" }, { "mach_msg_type_name_t", "poly_poly" } } },
{ -22, "mach_port_insert_member", 3, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "name" }, { "mach_port_name_t", "pset" } } },
{ -23, "mach_port_extract_member", 3, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "name" }, { "mach_port_name_t", "pset" } } },
{ -24, "mach_port_construct", 4, { { "mach_port_name_t", "target" }, { "mach_port_options_t *", "options" }, { "uint64_t", "context" }, { "mach_port_name_t *", "name" } } },
{ -25, "mach_port_destruct", 4, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "name" }, { "mach_port_delta_t", "srdelta" }, { "uint64_t", "guard" } } },
{ -26, "mach_reply_port", 0, {} },
{ -27, "thread_self", 0, {} },
{ -28, "task_self", 0, {} },
{ -29, "host_self", 0, {} },
{ -31, "mach_msg", 7, { { "mach_msg_header_t *", "msg" }, { "mach_msg_option_t", "option" }, { "mach_msg_size_t", "send_size" }, { "mach_msg_size_t", "rcv_size" }, { "mach_port_name_t", "rcv_name" }, { "mach_msg_timeout_t", "timeout" }, { "mach_port_name_t", "notify" } } },
{ -32, "mach_msg_overwrite", 9, { { "mach_msg_header_t *", "msg" }, { "mach_msg_option_t", "option" }, { "mach_msg_size_t", "send_size" }, { "mach_msg_size_t", "rcv_size" }, { "mach_port_name_t", "rcv_name" }, { "mach_msg_timeout_t", "timeout" }, { "mach_msg_priority_t", "priority" }, { "mach_msg_header_t *", "rcv_msg" }, { "mach_msg_size_t", "rcv_limit" } } },
{ -33, "semaphore_signal", 1, { { "mach_port_name_t", "signal_name" } } },
{ -34, "semaphore_signal_all", 1, { { "mach_port_name_t", "signal_name" } } },
{ -35, "semaphore_signal_thread", 2, { { "mach_port_name_t", "signal_name" }, { "mach_port_name_t", "thread_name" } } },
{ -36, "semaphore_wait", 1, { { "mach_port_name_t", "wait_name" } } },
{ -37, "semaphore_wait_signal", 2, { { "mach_port_name_t", "wait_name" }, { "mach_port_name_t", "signal_name" } } },
{ -38, "semaphore_timedwait", 3, { { "mach_port_name_t", "wait_name" }, { "unsigned int", "sec" }, { "clock_res_t", "nsec" } } },
{ -39, "semaphore_timedwait_signal", 4, { { "mach_port_name_t", "wait_name" }, { "mach_port_name_t", "signal_name" }, { "unsigned int", "sec" }, { "clock_res_t", "nsec" } } },
{ -40, "mach_port_get_attributes", 5, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "name" }, { "mach_port_flavor_t", "flavor" }, { "mach_port_info_t", "port_info_out" }, { "mach_msg_type_number_t *", "port_info_out_cnt" } } },
{ -41, "mach_port_guard", 4, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "name" }, { "uint64_t", "guard" }, { "boolean_t", "strict" } } },
{ -42, "mach_port_unguard", 3, { { "mach_port_name_t", "target" }, { "mach_port_name_t", "name" }, { "uint64_t", "guard" } } },
{ -43, "mach_generate_activity_id", 3, { { "mach_port_name_t", "target" }, { "int", "count" }, { "uint64_t *", "activity_id" } } },
{ -44, "task_name_for_pid", 3, { { "mach_port_name_t", "target_tport" }, { "int", "pid" }, { "mach_port_name_t *", "tn" } } },
{ -45, "task_for_pid", 3, { { "mach_port_name_t", "target_tport" }, { "int", "pid" }, { "mach_port_name_t *", "t" } } },
{ -46, "pid_for_task", 2, { { "mach_port_name_t", "t" }, { "int *", "x" } } },
{ -47, "mach_msg2", 8, { { "void *", "data" }, { "mach_msg_option64_t", "options" }, { "uint64_t", "msgh_bits_and_send_size" }, { "uint64_t", "msgh_remote_and_local_port" }, { "uint64_t", "msgh_voucher_and_id" }, { "uint64_t", "desc_count_and_rcv_name" }, { "uint64_t", "rcv_size_and_priority" }, { "uint64_t", "timeout" } } },
{ -48, "macx_swapon", 4, { { "uint64_t", "filename" }, { "int", "flags" }, { "int", "size" }, { "int", "priority" } } },
{ -49, "macx_swapoff", 2, { { "uint64_t", "filename" }, { "int", "flags" } } },
{ -50, "thread_get_special_reply_port", 0, {} },
{ -51, "macx_triggers", 4, { { "int", "hi_water" }, { "int", "low_water" }, { "int", "flags" }, { "mach_port_t", "alert_port" } } },
{ -52, "macx_backing_store_suspend", 1, { { "boolean_t", "suspend" } } },
{ -53, "macx_backing_store_recovery", 1, { { "int", "pid" } } },
{ -58, "pfz_exit", 0, {} },
{ -59, "swtch_pri", 1, { { "int", "pri" } } },
{ -60, "swtch", 0, {} },
{ -61, "thread_switch", 3, { { "mach_port_name_t", "thread_name" }, { "int", "option" }, { "mach_msg_timeout_t", "option_time" } } },
{ -62, "clock_sleep", 5, { { "mach_port_name_t", "clock_name" }, { "sleep_type_t", "sleep_type" }, { "int", "sleep_sec" }, { "int", "sleep_nsec" }, { "mach_timespec_t *", "wakeup_time" } } },
{ -63, "mach_vm_reclaim_update_kernel_accounting", 2, { { "mach_port_name_t", "target_tport" }, { "uint64_t *", "bytes_reclaimed" } } },
{ -70, "host_create_mach_voucher", 4, { { "mach_port_name_t", "host" }, { "mach_voucher_attr_raw_recipe_array_t", "recipes" }, { "int", "recipes_size" }, { "mach_port_name_t *", "voucher" } } },
{ -72, "mach_voucher_extract_attr_recipe", 4, { { "mach_port_name_t", "voucher_name" }, { "mach_voucher_attr_key_t", "key" }, { "mach_voucher_attr_raw_recipe_t", "recipe" }, { "mach_msg_type_number_t *", "recipe_size" } } },
{ -76, "mach_port_type", 3, { { "ipc_space_t", "task" }, { "mach_port_name_t", "name" }, { "mach_port_type_t *", "ptype" } } },
{ -77, "mach_port_request_notification", 7, { { "ipc_space_t", "task" }, { "mach_port_name_t", "name" }, { "mach_msg_id_t", "msgid" }, { "mach_port_mscount_t", "sync" }, { "mach_port_name_t", "notify" }, { "mach_msg_type_name_t", "notify_poly" }, { "mach_port_name_t *", "previous" } } },
{ -88, "exclaves_ctl", 8, { { "mach_port_name_t", "name" }, { "uint32_t", "operation_and_flags" }, { "uint64_t", "identifier" }, { "mach_vm_address_t", "buffer" }, { "mach_vm_size_t", "size" }, { "mach_vm_size_t", "size2" }, { "mach_vm_size_t", "offset" }, { "mach_vm_address_t", "status" } } },
{ -89, "mach_timebase_info", 1, { { "user_addr_t", "info" } } },
{ -90, "mach_wait_until", 1, { { "uint64_t", "deadline" } } },
{ -91, "mk_timer_create", 0, {} },
{ -92, "mk_timer_destroy", 1, { { "mach_port_name_t", "name" } } },
{ -93, "mk_timer_arm", 2, { { "mach_port_name_t", "name" }, { "uint64_t", "expire_time" } } },
{ -94, "mk_timer_cancel", 2, { { "mach_port_name_t", "name" }, { "user_addr_t", "result_time" } } },
{ -95, "mk_timer_arm_leeway", 4, { { "mach_port_name_t", "name" }, { "uint64_t", "mk_timer_flags" }, { "uint64_t", "expire_time" }, { "uint64_t", "mk_leeway" } } },
{ -96, "debug_control_port_for_pid", 3, { { "mach_port_name_t", "target_tport" }, { "int", "pid" }, { "mach_port_name_t *", "t" } } },
{ -100, "iokit_user_client", 8, { { "void *", "userClientRef" }, { "uint32_t", "index" }, { "void *", "p1" }, { "void *", "p2" }, { "void *", "p3" }, { "void *", "p4" }, { "void *", "p5" }, { "void *", "p6" } } },
};
static const FridaXnuSyscallSignature frida_xnu_bsd_syscalls[] =
{
{ 1, "exit", 1, { { "int", "rval" } } },
{ 2, "fork", 0, {} },
{ 3, "read", 3, { { "int", "fd" }, { "user_addr_t", "cbuf" }, { "user_size_t", "nbyte" } } },
{ 4, "write", 3, { { "int", "fd" }, { "user_addr_t", "cbuf" }, { "user_size_t", "nbyte" } } },
{ 5, "open", 3, { { "char *", "path" }, { "int", "flags" }, { "int", "mode" } } },
{ 6, "close", 1, { { "int", "fd" } } },
{ 7, "wait4", 4, { { "int", "pid" }, { "user_addr_t", "status" }, { "int", "options" }, { "user_addr_t", "rusage" } } },
{ 9, "link", 2, { { "char *", "path" }, { "char *", "link" } } },
{ 10, "unlink", 1, { { "char *", "path" } } },
{ 12, "chdir", 1, { { "char *", "path" } } },
{ 13, "fchdir", 1, { { "int", "fd" } } },
{ 14, "mknod", 3, { { "char *", "path" }, { "int", "mode" }, { "int", "dev" } } },
{ 15, "chmod", 2, { { "char *", "path" }, { "int", "mode" } } },
{ 16, "chown", 3, { { "char *", "path" }, { "int", "uid" }, { "int", "gid" } } },
{ 18, "getfsstat", 3, { { "user_addr_t", "buf" }, { "int", "bufsize" }, { "int", "flags" } } },
{ 20, "getpid", 0, {} },
{ 23, "setuid", 1, { { "uid_t", "uid" } } },
{ 24, "getuid", 0, {} },
{ 25, "geteuid", 0, {} },
{ 26, "ptrace", 4, { { "int", "req" }, { "pid_t", "pid" }, { "caddr_t", "addr" }, { "int", "data" } } },
{ 27, "recvmsg", 3, { { "int", "s" }, { "struct msghdr *", "msg" }, { "int", "flags" } } },
{ 28, "sendmsg", 3, { { "int", "s" }, { "caddr_t", "msg" }, { "int", "flags" } } },
{ 29, "recvfrom", 6, { { "int", "s" }, { "void *", "buf" }, { "size_t", "len" }, { "int", "flags" }, { "struct sockaddr *", "from" }, { "int *", "fromlenaddr" } } },
{ 30, "accept", 3, { { "int", "s" }, { "caddr_t", "name" }, { "socklen_t *", "anamelen" } } },
{ 31, "getpeername", 3, { { "int", "fdes" }, { "caddr_t", "asa" }, { "socklen_t *", "alen" } } },
{ 32, "getsockname", 3, { { "int", "fdes" }, { "caddr_t", "asa" }, { "socklen_t *", "alen" } } },
{ 33, "access", 2, { { "char *", "path" }, { "int", "flags" } } },
{ 34, "chflags", 2, { { "char *", "path" }, { "int", "flags" } } },
{ 35, "fchflags", 2, { { "int", "fd" }, { "int", "flags" } } },
{ 36, "sync", 0, {} },
{ 37, "kill", 3, { { "int", "pid" }, { "int", "signum" }, { "int", "posix" } } },
{ 38, "crossarch_trap", 1, { { "uint32_t", "name" } } },
{ 39, "getppid", 0, {} },
{ 41, "dup", 1, { { "u_int", "fd" } } },
{ 42, "pipe", 0, {} },
{ 43, "getegid", 0, {} },
{ 46, "sigaction", 3, { { "int", "signum" }, { "struct __sigaction *", "nsa" }, { "struct sigaction *", "osa" } } },
{ 47, "getgid", 0, {} },
{ 48, "sigprocmask", 3, { { "int", "how" }, { "user_addr_t", "mask" }, { "user_addr_t", "omask" } } },
{ 49, "getlogin", 2, { { "char *", "namebuf" }, { "u_int", "namelen" } } },
{ 50, "setlogin", 1, { { "char *", "namebuf" } } },
{ 51, "acct", 1, { { "char *", "path" } } },
{ 52, "sigpending", 1, { { "struct sigvec *", "osv" } } },
{ 53, "sigaltstack", 2, { { "struct sigaltstack *", "nss" }, { "struct sigaltstack *", "oss" } } },
{ 54, "ioctl", 3, { { "int", "fd" }, { "u_long", "com" }, { "caddr_t", "data" } } },
{ 55, "reboot", 2, { { "int", "opt" }, { "char *", "msg" } } },
{ 56, "revoke", 1, { { "char *", "path" } } },
{ 57, "symlink", 2, { { "char *", "path" }, { "char *", "link" } } },
{ 58, "readlink", 3, { { "char *", "path" }, { "char *", "buf" }, { "int", "count" } } },
{ 59, "execve", 3, { { "char *", "fname" }, { "char **", "argp" }, { "char **", "envp" } } },
{ 60, "umask", 1, { { "int", "newmask" } } },
{ 61, "chroot", 1, { { "char *", "path" } } },
{ 65, "msync", 3, { { "caddr_ut", "addr" }, { "size_ut", "len" }, { "int", "flags" } } },
{ 66, "vfork", 0, {} },
{ 67, "oslog_coproc_reg", 3, { { "const char *", "uuid" }, { "const char *", "file_path" }, { "size_t", "file_path_len" } } },
{ 68, "oslog_coproc", 7, { { "void *", "buff" }, { "uint64_t", "buff_len" }, { "uint32_t", "type" }, { "const char *", "uuid" }, { "uint64_t", "timestamp" }, { "uint32_t", "offset" }, { "uint32_t", "stream_log" } } },
{ 73, "munmap", 2, { { "caddr_ut", "addr" }, { "size_ut", "len" } } },
{ 74, "mprotect", 3, { { "caddr_ut", "addr" }, { "size_ut", "len" }, { "int", "prot" } } },
{ 75, "madvise", 3, { { "caddr_ut", "addr" }, { "size_ut", "len" }, { "int", "behav" } } },
{ 78, "mincore", 3, { { "caddr_ut", "addr" }, { "size_ut", "len" }, { "user_addr_t", "vec" } } },
{ 79, "getgroups", 2, { { "u_int", "gidsetsize" }, { "gid_t *", "gidset" } } },
{ 80, "setgroups", 2, { { "u_int", "gidsetsize" }, { "gid_t *", "gidset" } } },
{ 81, "getpgrp", 0, {} },
{ 82, "setpgid", 2, { { "int", "pid" }, { "int", "pgid" } } },
{ 83, "setitimer", 3, { { "u_int", "which" }, { "struct itimerval *", "itv" }, { "struct itimerval *", "oitv" } } },
{ 85, "swapon", 0, {} },
{ 86, "getitimer", 2, { { "u_int", "which" }, { "struct itimerval *", "itv" } } },
{ 89, "getdtablesize", 0, {} },
{ 90, "dup2", 2, { { "u_int", "from" }, { "u_int", "to" } } },
{ 92, "fcntl", 3, { { "int", "fd" }, { "int", "cmd" }, { "long", "arg" } } },
{ 93, "select", 5, { { "int", "nd" }, { "u_int32_t *", "in" }, { "u_int32_t *", "ou" }, { "u_int32_t *", "ex" }, { "struct timeval *", "tv" } } },
{ 95, "fsync", 1, { { "int", "fd" } } },
{ 96, "setpriority", 3, { { "int", "which" }, { "id_t", "who" }, { "int", "prio" } } },
{ 97, "socket", 3, { { "int", "domain" }, { "int", "type" }, { "int", "protocol" } } },
{ 98, "connect", 3, { { "int", "s" }, { "caddr_t", "name" }, { "socklen_t", "namelen" } } },
{ 100, "getpriority", 2, { { "int", "which" }, { "id_t", "who" } } },
{ 104, "bind", 3, { { "int", "s" }, { "caddr_t", "name" }, { "socklen_t", "namelen" } } },
{ 105, "setsockopt", 5, { { "int", "s" }, { "int", "level" }, { "int", "name" }, { "caddr_t", "val" }, { "socklen_t", "valsize" } } },
{ 106, "listen", 2, { { "int", "s" }, { "int", "backlog" } } },
{ 111, "sigsuspend", 1, { { "sigset_t", "mask" } } },
{ 116, "gettimeofday", 3, { { "struct timeval *", "tp" }, { "struct timezone *", "tzp" }, { "uint64_t *", "mach_absolute_time" } } },
{ 117, "getrusage", 2, { { "int", "who" }, { "struct rusage *", "rusage" } } },
{ 118, "getsockopt", 5, { { "int", "s" }, { "int", "level" }, { "int", "name" }, { "caddr_t", "val" }, { "socklen_t *", "avalsize" } } },
{ 120, "readv", 3, { { "int", "fd" }, { "struct iovec *", "iovp" }, { "u_int", "iovcnt" } } },
{ 121, "writev", 3, { { "int", "fd" }, { "struct iovec *", "iovp" }, { "u_int", "iovcnt" } } },
{ 122, "settimeofday", 2, { { "struct timeval *", "tv" }, { "struct timezone *", "tzp" } } },
{ 123, "fchown", 3, { { "int", "fd" }, { "int", "uid" }, { "int", "gid" } } },
{ 124, "fchmod", 2, { { "int", "fd" }, { "int", "mode" } } },
{ 126, "setreuid", 2, { { "uid_t", "ruid" }, { "uid_t", "euid" } } },
{ 127, "setregid", 2, { { "gid_t", "rgid" }, { "gid_t", "egid" } } },
{ 128, "rename", 2, { { "char *", "from" }, { "char *", "to" } } },
{ 131, "flock", 2, { { "int", "fd" }, { "int", "how" } } },
{ 132, "mkfifo", 2, { { "char *", "path" }, { "int", "mode" } } },
{ 133, "sendto", 6, { { "int", "s" }, { "caddr_t", "buf" }, { "size_t", "len" }, { "int", "flags" }, { "caddr_t", "to" }, { "socklen_t", "tolen" } } },
{ 134, "shutdown", 2, { { "int", "s" }, { "int", "how" } } },
{ 135, "socketpair", 4, { { "int", "domain" }, { "int", "type" }, { "int", "protocol" }, { "int *", "rsv" } } },
{ 136, "mkdir", 2, { { "char *", "path" }, { "int", "mode" } } },
{ 137, "rmdir", 1, { { "char *", "path" } } },
{ 138, "utimes", 2, { { "char *", "path" }, { "struct timeval *", "tptr" } } },
{ 139, "futimes", 2, { { "int", "fd" }, { "struct timeval *", "tptr" } } },
{ 140, "adjtime", 2, { { "struct timeval *", "delta" }, { "struct timeval *", "olddelta" } } },
{ 142, "gethostuuid", 2, { { "unsigned char *", "uuid_buf" }, { "const struct timespec *", "timeoutp" } } },
{ 147, "setsid", 0, {} },
{ 151, "getpgid", 1, { { "pid_t", "pid" } } },
{ 152, "setprivexec", 1, { { "int", "flag" } } },
{ 153, "pread", 4, { { "int", "fd" }, { "user_addr_t", "buf" }, { "user_size_t", "nbyte" }, { "off_t", "offset" } } },
{ 154, "pwrite", 4, { { "int", "fd" }, { "user_addr_t", "buf" }, { "user_size_t", "nbyte" }, { "off_t", "offset" } } },
{ 155, "nfssvc", 2, { { "int", "flag" }, { "caddr_t", "argp" } } },
{ 157, "statfs", 2, { { "char *", "path" }, { "struct statfs *", "buf" } } },
{ 158, "fstatfs", 2, { { "int", "fd" }, { "struct statfs *", "buf" } } },
{ 159, "unmount", 2, { { "char *", "path" }, { "int", "flags" } } },
{ 161, "getfh", 2, { { "char *", "fname" }, { "fhandle_t *", "fhp" } } },
{ 164, "funmount", 2, { { "int", "fd" }, { "int", "flags" } } },
{ 165, "quotactl", 4, { { "const char *", "path" }, { "int", "cmd" }, { "int", "uid" }, { "caddr_t", "arg" } } },
{ 167, "mount", 4, { { "char *", "type" }, { "char *", "path" }, { "int", "flags" }, { "caddr_t", "data" } } },
{ 169, "csops", 4, { { "pid_t", "pid" }, { "uint32_t", "ops" }, { "user_addr_t", "useraddr" }, { "user_size_t", "usersize" } } },
{ 170, "csops_audittoken", 5, { { "pid_t", "pid" }, { "uint32_t", "ops" }, { "user_addr_t", "useraddr" }, { "user_size_t", "usersize" }, { "user_addr_t", "uaudittoken" } } },
{ 173, "waitid", 4, { { "idtype_t", "idtype" }, { "id_t", "id" }, { "siginfo_t *", "infop" }, { "int", "options" } } },
{ 177, "kdebug_typefilter", 2, { { "void **", "addr" }, { "size_t *", "size" } } },
{ 178, "kdebug_trace_string", 3, { { "uint32_t", "debugid" }, { "uint64_t", "str_id" }, { "const char *", "str" } } },
{ 179, "kdebug_trace64", 5, { { "uint32_t", "code" }, { "uint64_t", "arg1" }, { "uint64_t", "arg2" }, { "uint64_t", "arg3" }, { "uint64_t", "arg4" } } },
{ 180, "kdebug_trace", 5, { { "uint32_t", "code" }, { "u_long", "arg1" }, { "u_long", "arg2" }, { "u_long", "arg3" }, { "u_long", "arg4" } } },
{ 181, "setgid", 1, { { "gid_t", "gid" } } },
{ 182, "setegid", 1, { { "gid_t", "egid" } } },
{ 183, "seteuid", 1, { { "uid_t", "euid" } } },
{ 184, "sigreturn", 3, { { "struct ucontext *", "uctx" }, { "int", "infostyle" }, { "user_addr_t", "token" } } },
{ 185, "panic_with_data", 5, { { "uuid_t", "uuid" }, { "void *", "addr" }, { "uint32_t", "len" }, { "uint32_t", "flags" }, { "const char *", "msg" } } },
{ 186, "thread_selfcounts", 3, { { "uint32_t", "kind" }, { "user_addr_t", "buf" }, { "user_size_t", "size" } } },
{ 187, "fdatasync", 1, { { "int", "fd" } } },
{ 188, "stat", 2, { { "char *", "path" }, { "user_addr_t", "ub" } } },
{ 189, "fstat", 2, { { "int", "fd" }, { "user_addr_t", "ub" } } },
{ 190, "lstat", 2, { { "char *", "path" }, { "user_addr_t", "ub" } } },
{ 191, "pathconf", 2, { { "char *", "path" }, { "int", "name" } } },
{ 192, "fpathconf", 2, { { "int", "fd" }, { "int", "name" } } },
{ 194, "getrlimit", 2, { { "u_int", "which" }, { "struct rlimit *", "rlp" } } },
{ 195, "setrlimit", 2, { { "u_int", "which" }, { "struct rlimit *", "rlp" } } },
{ 196, "getdirentries", 4, { { "int", "fd" }, { "char *", "buf" }, { "u_int", "count" }, { "long *", "basep" } } },
{ 197, "mmap", 6, { { "caddr_ut", "addr" }, { "size_ut", "len" }, { "int", "prot" }, { "int", "flags" }, { "int", "fd" }, { "off_t", "pos" } } },
{ 199, "lseek", 3, { { "int", "fd" }, { "off_t", "offset" }, { "int", "whence" } } },
{ 200, "truncate", 2, { { "char *", "path" }, { "off_t", "length" } } },
{ 201, "ftruncate", 2, { { "int", "fd" }, { "off_t", "length" } } },
{ 202, "sysctl", 6, { { "int *", "name" }, { "u_int", "namelen" }, { "void *", "old" }, { "size_t *", "oldlenp" }, { "void *", "new" }, { "size_t", "newlen" } } },
{ 203, "mlock", 2, { { "caddr_ut", "addr" }, { "size_ut", "len" } } },
{ 204, "munlock", 2, { { "caddr_ut", "addr" }, { "size_ut", "len" } } },
{ 205, "undelete", 1, { { "char *", "path" } } },
{ 216, "open_dprotected_np", 5, { { "char *", "path" }, { "int", "flags" }, { "int", "class" }, { "int", "dpflags" }, { "int", "mode" } } },
{ 217, "fsgetpath_ext", 5, { { "user_addr_t", "buf" }, { "size_t", "bufsize" }, { "user_addr_t", "fsid" }, { "uint64_t", "objid" }, { "uint32_t", "options" } } },
{ 218, "openat_dprotected_np", 7, { { "int", "fd" }, { "char *", "path" }, { "int", "flags" }, { "int", "class" }, { "int", "dpflags" }, { "int", "mode" }, { "int", "authfd" } } },
{ 220, "getattrlist", 5, { { "const char *", "path" }, { "struct attrlist *", "alist" }, { "void *", "attribute_buffer" }, { "size_t", "buffer_size" }, { "u_long", "options" } } },
{ 221, "setattrlist", 5, { { "const char *", "path" }, { "struct attrlist *", "alist" }, { "void *", "attribute_buffer" }, { "size_t", "buffer_size" }, { "u_long", "options" } } },
{ 222, "getdirentriesattr", 8, { { "int", "fd" }, { "struct attrlist *", "alist" }, { "void *", "buffer" }, { "size_t", "buffersize" }, { "u_long *", "count" }, { "u_long *", "basep" }, { "u_long *", "newstate" }, { "u_long", "options" } } },
{ 223, "exchangedata", 3, { { "const char *", "path1" }, { "const char *", "path2" }, { "u_long", "options" } } },
{ 225, "searchfs", 6, { { "const char *", "path" }, { "struct fssearchblock *", "searchblock" }, { "uint32_t *", "nummatches" }, { "uint32_t", "scriptcode" }, { "uint32_t", "options" }, { "struct searchstate *", "state" } } },
{ 226, "delete", 1, { { "char *", "path" } } },
{ 227, "copyfile", 4, { { "char *", "from" }, { "char *", "to" }, { "int", "mode" }, { "int", "flags" } } },
{ 228, "fgetattrlist", 5, { { "int", "fd" }, { "struct attrlist *", "alist" }, { "void *", "attribute_buffer" }, { "size_t", "buffer_size" }, { "u_long", "options" } } },
{ 229, "fsetattrlist", 5, { { "int", "fd" }, { "struct attrlist *", "alist" }, { "void *", "attribute_buffer" }, { "size_t", "buffer_size" }, { "u_long", "options" } } },
{ 230, "poll", 3, { { "struct pollfd *", "fds" }, { "u_int", "nfds" }, { "int", "timeout" } } },
{ 234, "getxattr", 6, { { "char *", "path" }, { "char *", "attrname" }, { "user_addr_t", "value" }, { "size_t", "size" }, { "uint32_t", "position" }, { "int", "options" } } },
{ 235, "fgetxattr", 6, { { "int", "fd" }, { "char *", "attrname" }, { "user_addr_t", "value" }, { "size_t", "size" }, { "uint32_t", "position" }, { "int", "options" } } },
{ 236, "setxattr", 6, { { "char *", "path" }, { "char *", "attrname" }, { "user_addr_t", "value" }, { "size_t", "size" }, { "uint32_t", "position" }, { "int", "options" } } },
{ 237, "fsetxattr", 6, { { "int", "fd" }, { "char *", "attrname" }, { "user_addr_t", "value" }, { "size_t", "size" }, { "uint32_t", "position" }, { "int", "options" } } },
{ 238, "removexattr", 3, { { "char *", "path" }, { "char *", "attrname" }, { "int", "options" } } },
{ 239, "fremovexattr", 3, { { "int", "fd" }, { "char *", "attrname" }, { "int", "options" } } },
{ 240, "listxattr", 4, { { "char *", "path" }, { "user_addr_t", "namebuf" }, { "size_t", "bufsize" }, { "int", "options" } } },
{ 241, "flistxattr", 4, { { "int", "fd" }, { "user_addr_t", "namebuf" }, { "size_t", "bufsize" }, { "int", "options" } } },
{ 242, "fsctl", 4, { { "const char *", "path" }, { "u_long", "cmd" }, { "caddr_t", "data" }, { "u_int", "options" } } },
{ 243, "initgroups", 3, { { "u_int", "gidsetsize" }, { "gid_t *", "gidset" }, { "int", "gmuid" } } },
{ 244, "posix_spawn", 5, { { "pid_t *", "pid" }, { "const char *", "path" }, { "const struct _posix_spawn_args_desc *", "adesc" }, { "char **", "argv" }, { "char **", "envp" } } },
{ 245, "ffsctl", 4, { { "int", "fd" }, { "u_long", "cmd" }, { "caddr_t", "data" }, { "u_int", "options" } } },
{ 248, "fhopen", 2, { { "const struct fhandle *", "u_fhp" }, { "int", "flags" } } },
{ 250, "minherit", 3, { { "caddr_ut", "addr" }, { "size_ut", "len" }, { "int", "inherit" } } },
{ 251, "semsys", 5, { { "u_int", "which" }, { "int", "a2" }, { "int", "a3" }, { "int", "a4" }, { "int", "a5" } } },
{ 252, "msgsys", 5, { { "u_int", "which" }, { "int", "a2" }, { "int", "a3" }, { "int", "a4" }, { "int", "a5" } } },
{ 253, "shmsys", 4, { { "u_int", "which" }, { "int", "a2" }, { "int", "a3" }, { "int", "a4" } } },
{ 254, "semctl", 4, { { "int", "semid" }, { "int", "semnum" }, { "int", "cmd" }, { "semun_t", "arg" } } },
{ 255, "semget", 3, { { "key_t", "key" }, { "int", "nsems" }, { "int", "semflg" } } },
{ 256, "semop", 3, { { "int", "semid" }, { "struct sembuf *", "sops" }, { "int", "nsops" } } },
{ 258, "msgctl", 3, { { "int", "msqid" }, { "int", "cmd" }, { "struct msqid_ds *", "buf" } } },
{ 259, "msgget", 2, { { "key_t", "key" }, { "int", "msgflg" } } },
{ 260, "msgsnd", 4, { { "int", "msqid" }, { "void *", "msgp" }, { "size_t", "msgsz" }, { "int", "msgflg" } } },
{ 261, "msgrcv", 5, { { "int", "msqid" }, { "void *", "msgp" }, { "size_t", "msgsz" }, { "long", "msgtyp" }, { "int", "msgflg" } } },
{ 262, "shmat", 3, { { "int", "shmid" }, { "void *", "shmaddr" }, { "int", "shmflg" } } },
{ 263, "shmctl", 3, { { "int", "shmid" }, { "int", "cmd" }, { "struct shmid_ds *", "buf" } } },
{ 264, "shmdt", 1, { { "void *", "shmaddr" } } },
{ 265, "shmget", 3, { { "key_t", "key" }, { "size_t", "size" }, { "int", "shmflg" } } },
{ 266, "shm_open", 3, { { "const char *", "name" }, { "int", "oflag" }, { "int", "mode" } } },
{ 267, "shm_unlink", 1, { { "const char *", "name" } } },
{ 268, "sem_open", 4, { { "const char *", "name" }, { "int", "oflag" }, { "int", "mode" }, { "int", "value" } } },
{ 269, "sem_close", 1, { { "sem_t *", "sem" } } },
{ 270, "sem_unlink", 1, { { "const char *", "name" } } },
{ 271, "sem_wait", 1, { { "sem_t *", "sem" } } },
{ 272, "sem_trywait", 1, { { "sem_t *", "sem" } } },
{ 273, "sem_post", 1, { { "sem_t *", "sem" } } },
{ 274, "sysctlbyname", 6, { { "const char *", "name" }, { "size_t", "namelen" }, { "void *", "old" }, { "size_t *", "oldlenp" }, { "void *", "new" }, { "size_t", "newlen" } } },
{ 277, "open_extended", 6, { { "char *", "path" }, { "int", "flags" }, { "uid_t", "uid" }, { "gid_t", "gid" }, { "int", "mode" }, { "user_addr_t", "xsecurity" } } },
{ 278, "umask_extended", 2, { { "int", "newmask" }, { "user_addr_t", "xsecurity" } } },
{ 279, "stat_extended", 4, { { "char *", "path" }, { "user_addr_t", "ub" }, { "user_addr_t", "xsecurity" }, { "user_addr_t", "xsecurity_size" } } },
{ 280, "lstat_extended", 4, { { "char *", "path" }, { "user_addr_t", "ub" }, { "user_addr_t", "xsecurity" }, { "user_addr_t", "xsecurity_size" } } },
{ 281, "fstat_extended", 4, { { "int", "fd" }, { "user_addr_t", "ub" }, { "user_addr_t", "xsecurity" }, { "user_addr_t", "xsecurity_size" } } },
{ 282, "chmod_extended", 5, { { "char *", "path" }, { "uid_t", "uid" }, { "gid_t", "gid" }, { "int", "mode" }, { "user_addr_t", "xsecurity" } } },
{ 283, "fchmod_extended", 5, { { "int", "fd" }, { "uid_t", "uid" }, { "gid_t", "gid" }, { "int", "mode" }, { "user_addr_t", "xsecurity" } } },
{ 284, "access_extended", 4, { { "user_addr_t", "entries" }, { "size_t", "size" }, { "user_addr_t", "results" }, { "uid_t", "uid" } } },
{ 285, "settid", 2, { { "uid_t", "uid" }, { "gid_t", "gid" } } },
{ 286, "gettid", 2, { { "uid_t *", "uidp" }, { "gid_t *", "gidp" } } },
{ 287, "setsgroups", 2, { { "int", "setlen" }, { "user_addr_t", "guidset" } } },
{ 288, "getsgroups", 2, { { "user_addr_t", "setlen" }, { "user_addr_t", "guidset" } } },
{ 289, "setwgroups", 2, { { "int", "setlen" }, { "user_addr_t", "guidset" } } },
{ 290, "getwgroups", 2, { { "user_addr_t", "setlen" }, { "user_addr_t", "guidset" } } },
{ 291, "mkfifo_extended", 5, { { "char *", "path" }, { "uid_t", "uid" }, { "gid_t", "gid" }, { "int", "mode" }, { "user_addr_t", "xsecurity" } } },
{ 292, "mkdir_extended", 5, { { "char *", "path" }, { "uid_t", "uid" }, { "gid_t", "gid" }, { "int", "mode" }, { "user_addr_t", "xsecurity" } } },
{ 293, "identitysvc", 2, { { "int", "opcode" }, { "user_addr_t", "message" } } },
{ 294, "shared_region_check_np", 1, { { "uint64_t *", "start_address" } } },
{ 296, "vm_pressure_monitor", 3, { { "int", "wait_for_pressure" }, { "int", "nsecs_monitored" }, { "uint32_t *", "pages_reclaimed" } } },
{ 297, "psynch_rw_longrdlock", 5, { { "user_addr_t", "rwlock" }, { "uint32_t", "lgenval" }, { "uint32_t", "ugenval" }, { "uint32_t", "rw_wc" }, { "int", "flags" } } },
{ 298, "psynch_rw_yieldwrlock", 5, { { "user_addr_t", "rwlock" }, { "uint32_t", "lgenval" }, { "uint32_t", "ugenval" }, { "uint32_t", "rw_wc" }, { "int", "flags" } } },
{ 299, "psynch_rw_downgrade", 5, { { "user_addr_t", "rwlock" }, { "uint32_t", "lgenval" }, { "uint32_t", "ugenval" }, { "uint32_t", "rw_wc" }, { "int", "flags" } } },
{ 300, "psynch_rw_upgrade", 5, { { "user_addr_t", "rwlock" }, { "uint32_t", "lgenval" }, { "uint32_t", "ugenval" }, { "uint32_t", "rw_wc" }, { "int", "flags" } } },
{ 301, "psynch_mutexwait", 5, { { "user_addr_t", "mutex" }, { "uint32_t", "mgen" }, { "uint32_t", "ugen" }, { "uint64_t", "tid" }, { "uint32_t", "flags" } } },
{ 302, "psynch_mutexdrop", 5, { { "user_addr_t", "mutex" }, { "uint32_t", "mgen" }, { "uint32_t", "ugen" }, { "uint64_t", "tid" }, { "uint32_t", "flags" } } },
{ 303, "psynch_cvbroad", 7, { { "user_addr_t", "cv" }, { "uint64_t", "cvlsgen" }, { "uint64_t", "cvudgen" }, { "uint32_t", "flags" }, { "user_addr_t", "mutex" }, { "uint64_t", "mugen" }, { "uint64_t", "tid" } } },
{ 304, "psynch_cvsignal", 8, { { "user_addr_t", "cv" }, { "uint64_t", "cvlsgen" }, { "uint32_t", "cvugen" }, { "int", "thread_port" }, { "user_addr_t", "mutex" }, { "uint64_t", "mugen" }, { "uint64_t", "tid" }, { "uint32_t", "flags" } } },
{ 305, "psynch_cvwait", 8, { { "user_addr_t", "cv" }, { "uint64_t", "cvlsgen" }, { "uint32_t", "cvugen" }, { "user_addr_t", "mutex" }, { "uint64_t", "mugen" }, { "uint32_t", "flags" }, { "int64_t", "sec" }, { "uint32_t", "nsec" } } },
{ 306, "psynch_rw_rdlock", 5, { { "user_addr_t", "rwlock" }, { "uint32_t", "lgenval" }, { "uint32_t", "ugenval" }, { "uint32_t", "rw_wc" }, { "int", "flags" } } },
{ 307, "psynch_rw_wrlock", 5, { { "user_addr_t", "rwlock" }, { "uint32_t", "lgenval" }, { "uint32_t", "ugenval" }, { "uint32_t", "rw_wc" }, { "int", "flags" } } },
{ 308, "psynch_rw_unlock", 5, { { "user_addr_t", "rwlock" }, { "uint32_t", "lgenval" }, { "uint32_t", "ugenval" }, { "uint32_t", "rw_wc" }, { "int", "flags" } } },
{ 309, "psynch_rw_unlock2", 5, { { "user_addr_t", "rwlock" }, { "uint32_t", "lgenval" }, { "uint32_t", "ugenval" }, { "uint32_t", "rw_wc" }, { "int", "flags" } } },
{ 310, "getsid", 1, { { "pid_t", "pid" } } },
{ 311, "settid_with_pid", 2, { { "pid_t", "pid" }, { "int", "assume" } } },
{ 312, "psynch_cvclrprepost", 7, { { "user_addr_t", "cv" }, { "uint32_t", "cvgen" }, { "uint32_t", "cvugen" }, { "uint32_t", "cvsgen" }, { "uint32_t", "prepocnt" }, { "uint32_t", "preposeq" }, { "uint32_t", "flags" } } },
{ 313, "aio_fsync", 2, { { "int", "op" }, { "user_addr_t", "aiocbp" } } },
{ 314, "aio_return", 1, { { "user_addr_t", "aiocbp" } } },
{ 315, "aio_suspend", 3, { { "user_addr_t", "aiocblist" }, { "int", "nent" }, { "user_addr_t", "timeoutp" } } },
{ 316, "aio_cancel", 2, { { "int", "fd" }, { "user_addr_t", "aiocbp" } } },
{ 317, "aio_error", 1, { { "user_addr_t", "aiocbp" } } },
{ 318, "aio_read", 1, { { "user_addr_t", "aiocbp" } } },
{ 319, "aio_write", 1, { { "user_addr_t", "aiocbp" } } },
{ 320, "lio_listio", 4, { { "int", "mode" }, { "user_addr_t", "aiocblist" }, { "int", "nent" }, { "user_addr_t", "sigp" } } },
{ 322, "iopolicysys", 2, { { "int", "cmd" }, { "void *", "arg" } } },
{ 323, "process_policy", 7, { { "int", "scope" }, { "int", "action" }, { "int", "policy" }, { "int", "policy_subtype" }, { "user_addr_t", "attrp" }, { "pid_t", "target_pid" }, { "uint64_t", "target_threadid" } } },
{ 324, "mlockall", 1, { { "int", "how" } } },
{ 325, "munlockall", 1, { { "int", "how" } } },
{ 327, "issetugid", 0, {} },
{ 328, "pthread_kill", 2, { { "int", "thread_port" }, { "int", "sig" } } },
{ 329, "pthread_sigmask", 3, { { "int", "how" }, { "user_addr_t", "set" }, { "user_addr_t", "oset" } } },
{ 330, "sigwait", 2, { { "user_addr_t", "set" }, { "user_addr_t", "sig" } } },
{ 331, "disable_threadsignal", 1, { { "int", "value" } } },
{ 332, "pthread_markcancel", 1, { { "int", "thread_port" } } },
{ 333, "pthread_canceled", 1, { { "int", "action" } } },
{ 334, "semwait_signal", 6, { { "int", "cond_sem" }, { "int", "mutex_sem" }, { "int", "timeout" }, { "int", "relative" }, { "int64_t", "tv_sec" }, { "int32_t", "tv_nsec" } } },
{ 336, "proc_info", 6, { { "int32_t", "callnum" }, { "int32_t", "pid" }, { "uint32_t", "flavor" }, { "uint64_t", "arg" }, { "user_addr_t", "buffer" }, { "int32_t", "buffersize" } } },
{ 337, "sendfile", 6, { { "int", "fd" }, { "int", "s" }, { "off_t", "offset" }, { "off_t *", "nbytes" }, { "struct sf_hdtr *", "hdtr" }, { "int", "flags" } } },
{ 338, "stat64", 2, { { "char *", "path" }, { "user_addr_t", "ub" } } },
{ 339, "fstat64", 2, { { "int", "fd" }, { "user_addr_t", "ub" } } },
{ 340, "lstat64", 2, { { "char *", "path" }, { "user_addr_t", "ub" } } },
{ 341, "stat64_extended", 4, { { "char *", "path" }, { "user_addr_t", "ub" }, { "user_addr_t", "xsecurity" }, { "user_addr_t", "xsecurity_size" } } },
{ 342, "lstat64_extended", 4, { { "char *", "path" }, { "user_addr_t", "ub" }, { "user_addr_t", "xsecurity" }, { "user_addr_t", "xsecurity_size" } } },
{ 343, "fstat64_extended", 4, { { "int", "fd" }, { "user_addr_t", "ub" }, { "user_addr_t", "xsecurity" }, { "user_addr_t", "xsecurity_size" } } },
{ 344, "getdirentries64", 4, { { "int", "fd" }, { "void *", "buf" }, { "user_size_t", "bufsize" }, { "off_t *", "position" } } },
{ 345, "statfs64", 2, { { "char *", "path" }, { "struct statfs64 *", "buf" } } },
{ 346, "fstatfs64", 2, { { "int", "fd" }, { "struct statfs64 *", "buf" } } },
{ 347, "getfsstat64", 3, { { "user_addr_t", "buf" }, { "int", "bufsize" }, { "int", "flags" } } },
{ 348, "pthread_chdir", 1, { { "char *", "path" } } },
{ 349, "pthread_fchdir", 1, { { "int", "fd" } } },
{ 350, "audit", 2, { { "void *", "record" }, { "int", "length" } } },
{ 351, "auditon", 3, { { "int", "cmd" }, { "void *", "data" }, { "int", "length" } } },
{ 353, "getauid", 1, { { "au_id_t *", "auid" } } },
{ 354, "setauid", 1, { { "au_id_t *", "auid" } } },
{ 357, "getaudit_addr", 2, { { "struct auditinfo_addr *", "auditinfo_addr" }, { "int", "length" } } },
{ 358, "setaudit_addr", 2, { { "struct auditinfo_addr *", "auditinfo_addr" }, { "int", "length" } } },
{ 359, "auditctl", 1, { { "char *", "path" } } },
{ 360, "bsdthread_create", 5, { { "user_addr_t", "func" }, { "user_addr_t", "func_arg" }, { "user_addr_t", "stack" }, { "user_addr_t", "pthread" }, { "uint32_t", "flags" } } },
{ 361, "bsdthread_terminate", 4, { { "user_addr_t", "stackaddr" }, { "size_t", "freesize" }, { "uint32_t", "port" }, { "user_addr_t", "sema_or_ulock" } } },
{ 362, "kqueue", 0, {} },
{ 363, "kevent", 6, { { "int", "fd" }, { "const struct kevent *", "changelist" }, { "int", "nchanges" }, { "struct kevent *", "eventlist" }, { "int", "nevents" }, { "const struct timespec *", "timeout" } } },
{ 364, "lchown", 3, { { "char *", "path" }, { "uid_t", "owner" }, { "gid_t", "group" } } },
{ 366, "bsdthread_register", 7, { { "user_addr_t", "threadstart" }, { "user_addr_t", "wqthread" }, { "uint32_t", "flags" }, { "user_addr_t", "stack_addr_hint" }, { "user_addr_t", "targetconc_ptr" }, { "uint32_t", "dispatchqueue_offset" }, { "uint32_t", "tsd_offset" } } },
{ 367, "workq_open", 0, {} },
{ 368, "workq_kernreturn", 4, { { "int", "options" }, { "user_addr_t", "item" }, { "int", "affinity" }, { "int", "prio" } } },
{ 369, "kevent64", 7, { { "int", "fd" }, { "const struct kevent64_s *", "changelist" }, { "int", "nchanges" }, { "struct kevent64_s *", "eventlist" }, { "int", "nevents" }, { "unsigned int", "flags" }, { "const struct timespec *", "timeout" } } },
{ 372, "thread_selfid", 0, {} },
{ 373, "ledger", 4, { { "int", "cmd" }, { "caddr_t", "arg1" }, { "caddr_t", "arg2" }, { "caddr_t", "arg3" } } },
{ 374, "kevent_qos", 8, { { "int", "fd" }, { "const struct kevent_qos_s *", "changelist" }, { "int", "nchanges" }, { "struct kevent_qos_s *", "eventlist" }, { "int", "nevents" }, { "void *", "data_out" }, { "size_t *", "data_available" }, { "unsigned int", "flags" } } },
{ 375, "kevent_id", 8, { { "uint64_t", "id" }, { "const struct kevent_qos_s *", "changelist" }, { "int", "nchanges" }, { "struct kevent_qos_s *", "eventlist" }, { "int", "nevents" }, { "void *", "data_out" }, { "size_t *", "data_available" }, { "unsigned int", "flags" } } },
{ 380, "mac_execve", 4, { { "char *", "fname" }, { "char **", "argp" }, { "char **", "envp" }, { "struct mac *", "mac_p" } } },
{ 381, "mac_syscall", 3, { { "char *", "policy" }, { "int", "call" }, { "user_addr_t", "arg" } } },
{ 382, "mac_get_file", 2, { { "char *", "path_p" }, { "struct mac *", "mac_p" } } },
{ 383, "mac_set_file", 2, { { "char *", "path_p" }, { "struct mac *", "mac_p" } } },
{ 384, "mac_get_link", 2, { { "char *", "path_p" }, { "struct mac *", "mac_p" } } },
{ 385, "mac_set_link", 2, { { "char *", "path_p" }, { "struct mac *", "mac_p" } } },
{ 386, "mac_get_proc", 1, { { "struct mac *", "mac_p" } } },
{ 387, "mac_set_proc", 1, { { "struct mac *", "mac_p" } } },
{ 388, "mac_get_fd", 2, { { "int", "fd" }, { "struct mac *", "mac_p" } } },
{ 389, "mac_set_fd", 2, { { "int", "fd" }, { "struct mac *", "mac_p" } } },
{ 390, "mac_get_pid", 2, { { "pid_t", "pid" }, { "struct mac *", "mac_p" } } },
{ 394, "pselect", 6, { { "int", "nd" }, { "u_int32_t *", "in" }, { "u_int32_t *", "ou" }, { "u_int32_t *", "ex" }, { "const struct timespec *", "ts" }, { "const struct sigset_t *", "mask" } } },
{ 395, "pselect_nocancel", 6, { { "int", "nd" }, { "u_int32_t *", "in" }, { "u_int32_t *", "ou" }, { "u_int32_t *", "ex" }, { "const struct timespec *", "ts" }, { "const struct sigset_t *", "mask" } } },
{ 396, "read_nocancel", 3, { { "int", "fd" }, { "user_addr_t", "cbuf" }, { "user_size_t", "nbyte" } } },
{ 397, "write_nocancel", 3, { { "int", "fd" }, { "user_addr_t", "cbuf" }, { "user_size_t", "nbyte" } } },
{ 398, "open_nocancel", 3, { { "char *", "path" }, { "int", "flags" }, { "int", "mode" } } },
{ 399, "close_nocancel", 1, { { "int", "fd" } } },
{ 400, "wait4_nocancel", 4, { { "int", "pid" }, { "user_addr_t", "status" }, { "int", "options" }, { "user_addr_t", "rusage" } } },
{ 401, "recvmsg_nocancel", 3, { { "int", "s" }, { "struct msghdr *", "msg" }, { "int", "flags" } } },
{ 402, "sendmsg_nocancel", 3, { { "int", "s" }, { "caddr_t", "msg" }, { "int", "flags" } } },
{ 403, "recvfrom_nocancel", 6, { { "int", "s" }, { "void *", "buf" }, { "size_t", "len" }, { "int", "flags" }, { "struct sockaddr *", "from" }, { "int *", "fromlenaddr" } } },
{ 404, "accept_nocancel", 3, { { "int", "s" }, { "caddr_t", "name" }, { "socklen_t *", "anamelen" } } },
{ 405, "msync_nocancel", 3, { { "caddr_ut", "addr" }, { "size_ut", "len" }, { "int", "flags" } } },
{ 406, "fcntl_nocancel", 3, { { "int", "fd" }, { "int", "cmd" }, { "long", "arg" } } },
{ 407, "select_nocancel", 5, { { "int", "nd" }, { "u_int32_t *", "in" }, { "u_int32_t *", "ou" }, { "u_int32_t *", "ex" }, { "struct timeval *", "tv" } } },
{ 408, "fsync_nocancel", 1, { { "int", "fd" } } },
{ 409, "connect_nocancel", 3, { { "int", "s" }, { "caddr_t", "name" }, { "socklen_t", "namelen" } } },
{ 410, "sigsuspend_nocancel", 1, { { "sigset_t", "mask" } } },
{ 411, "readv_nocancel", 3, { { "int", "fd" }, { "struct iovec *", "iovp" }, { "u_int", "iovcnt" } } },
{ 412, "writev_nocancel", 3, { { "int", "fd" }, { "struct iovec *", "iovp" }, { "u_int", "iovcnt" } } },
{ 413, "sendto_nocancel", 6, { { "int", "s" }, { "caddr_t", "buf" }, { "size_t", "len" }, { "int", "flags" }, { "caddr_t", "to" }, { "socklen_t", "tolen" } } },
{ 414, "pread_nocancel", 4, { { "int", "fd" }, { "user_addr_t", "buf" }, { "user_size_t", "nbyte" }, { "off_t", "offset" } } },
{ 415, "pwrite_nocancel", 4, { { "int", "fd" }, { "user_addr_t", "buf" }, { "user_size_t", "nbyte" }, { "off_t", "offset" } } },
{ 416, "waitid_nocancel", 4, { { "idtype_t", "idtype" }, { "id_t", "id" }, { "siginfo_t *", "infop" }, { "int", "options" } } },
{ 417, "poll_nocancel", 3, { { "struct pollfd *", "fds" }, { "u_int", "nfds" }, { "int", "timeout" } } },
{ 418, "msgsnd_nocancel", 4, { { "int", "msqid" }, { "void *", "msgp" }, { "size_t", "msgsz" }, { "int", "msgflg" } } },
{ 419, "msgrcv_nocancel", 5, { { "int", "msqid" }, { "void *", "msgp" }, { "size_t", "msgsz" }, { "long", "msgtyp" }, { "int", "msgflg" } } },
{ 420, "sem_wait_nocancel", 1, { { "sem_t *", "sem" } } },
{ 421, "aio_suspend_nocancel", 3, { { "user_addr_t", "aiocblist" }, { "int", "nent" }, { "user_addr_t", "timeoutp" } } },
{ 422, "sigwait_nocancel", 2, { { "user_addr_t", "set" }, { "user_addr_t", "sig" } } },
{ 423, "semwait_signal_nocancel", 6, { { "int", "cond_sem" }, { "int", "mutex_sem" }, { "int", "timeout" }, { "int", "relative" }, { "int64_t", "tv_sec" }, { "int32_t", "tv_nsec" } } },
{ 424, "mac_mount", 5, { { "char *", "type" }, { "char *", "path" }, { "int", "flags" }, { "caddr_t", "data" }, { "struct mac *", "mac_p" } } },
{ 425, "mac_get_mount", 2, { { "char *", "path" }, { "struct mac *", "mac_p" } } },
{ 426, "mac_getfsstat", 5, { { "user_addr_t", "buf" }, { "int", "bufsize" }, { "user_addr_t", "mac" }, { "int", "macsize" }, { "int", "flags" } } },
{ 427, "fsgetpath", 4, { { "user_addr_t", "buf" }, { "size_t", "bufsize" }, { "user_addr_t", "fsid" }, { "uint64_t", "objid" } } },
{ 428, "audit_session_self", 0, {} },
{ 429, "audit_session_join", 1, { { "mach_port_name_t", "port" } } },
{ 430, "fileport_makeport", 2, { { "int", "fd" }, { "user_addr_t", "portnamep" } } },
{ 431, "fileport_makefd", 1, { { "mach_port_name_t", "port" } } },
{ 432, "audit_session_port", 2, { { "au_asid_t", "asid" }, { "user_addr_t", "portnamep" } } },
{ 433, "pid_suspend", 1, { { "int", "pid" } } },
{ 434, "pid_resume", 1, { { "int", "pid" } } },
{ 435, "pid_hibernate", 1, { { "int", "pid" } } },
{ 436, "pid_shutdown_sockets", 2, { { "int", "pid" }, { "int", "level" } } },
{ 439, "kas_info", 3, { { "int", "selector" }, { "void *", "value" }, { "size_t *", "size" } } },
{ 440, "memorystatus_control", 5, { { "uint32_t", "command" }, { "int32_t", "pid" }, { "uint32_t", "flags" }, { "user_addr_t", "buffer" }, { "size_t", "buffersize" } } },
{ 441, "guarded_open_np", 5, { { "char *", "path" }, { "const guardid_t *", "guard" }, { "u_int", "guardflags" }, { "int", "flags" }, { "int", "mode" } } },
{ 442, "guarded_close_np", 2, { { "int", "fd" }, { "const guardid_t *", "guard" } } },
{ 443, "guarded_kqueue_np", 2, { { "const guardid_t *", "guard" }, { "u_int", "guardflags" } } },
{ 444, "change_fdguard_np", 6, { { "int", "fd" }, { "const guardid_t *", "guard" }, { "u_int", "guardflags" }, { "const guardid_t *", "nguard" }, { "u_int", "nguardflags" }, { "int *", "fdflagsp" } } },
{ 445, "usrctl", 1, { { "uint32_t", "flags" } } },
{ 446, "proc_rlimit_control", 3, { { "pid_t", "pid" }, { "int", "flavor" }, { "void *", "arg" } } },
{ 447, "connectx", 8, { { "int", "socket" }, { "const sa_endpoints_t *", "endpoints" }, { "sae_associd_t", "associd" }, { "unsigned int", "flags" }, { "const struct iovec *", "iov" }, { "unsigned int", "iovcnt" }, { "size_t *", "len" }, { "sae_connid_t *", "connid" } } },
{ 448, "disconnectx", 3, { { "int", "s" }, { "sae_associd_t", "aid" }, { "sae_connid_t", "cid" } } },
{ 449, "peeloff", 2, { { "int", "s" }, { "sae_associd_t", "aid" } } },
{ 450, "socket_delegate", 4, { { "int", "domain" }, { "int", "type" }, { "int", "protocol" }, { "pid_t", "epid" } } },
{ 451, "telemetry", 6, { { "uint64_t", "cmd" }, { "uint64_t", "deadline" }, { "uint64_t", "interval" }, { "uint64_t", "leeway" }, { "uint64_t", "arg4" }, { "uint64_t", "arg5" } } },
{ 452, "proc_uuid_policy", 4, { { "uint32_t", "operation" }, { "uuid_t", "uuid" }, { "size_t", "uuidlen" }, { "uint32_t", "flags" } } },
{ 453, "memorystatus_get_level", 1, { { "user_addr_t", "level" } } },
{ 454, "system_override", 2, { { "uint64_t", "timeout" }, { "uint64_t", "flags" } } },
{ 455, "vfs_purge", 0, {} },
{ 456, "sfi_ctl", 4, { { "uint32_t", "operation" }, { "uint32_t", "sfi_class" }, { "uint64_t", "time" }, { "uint64_t *", "out_time" } } },
{ 457, "sfi_pidctl", 4, { { "uint32_t", "operation" }, { "pid_t", "pid" }, { "uint32_t", "sfi_flags" }, { "uint32_t *", "out_sfi_flags" } } },
{ 458, "coalition", 3, { { "uint32_t", "operation" }, { "uint64_t *", "cid" }, { "uint32_t", "flags" } } },
{ 459, "coalition_info", 4, { { "uint32_t", "flavor" }, { "uint64_t *", "cid" }, { "void *", "buffer" }, { "size_t *", "bufsize" } } },
{ 460, "necp_match_policy", 3, { { "uint8_t *", "parameters" }, { "size_t", "parameters_size" }, { "struct necp_aggregate_result *", "returned_result" } } },
{ 461, "getattrlistbulk", 5, { { "int", "dirfd" }, { "struct attrlist *", "alist" }, { "void *", "attribute_buffer" }, { "size_t", "buffer_size" }, { "uint64_t", "options" } } },
{ 462, "clonefileat", 5, { { "int", "src_dirfd" }, { "user_addr_t", "src" }, { "int", "dst_dirfd" }, { "user_addr_t", "dst" }, { "uint32_t", "flags" } } },
{ 463, "openat", 4, { { "int", "fd" }, { "char *", "path" }, { "int", "flags" }, { "int", "mode" } } },
{ 464, "openat_nocancel", 4, { { "int", "fd" }, { "char *", "path" }, { "int", "flags" }, { "int", "mode" } } },
{ 465, "renameat", 4, { { "int", "fromfd" }, { "char *", "from" }, { "int", "tofd" }, { "char *", "to" } } },
{ 466, "faccessat", 4, { { "int", "fd" }, { "char *", "path" }, { "int", "amode" }, { "int", "flag" } } },
{ 467, "fchmodat", 4, { { "int", "fd" }, { "char *", "path" }, { "int", "mode" }, { "int", "flag" } } },
{ 468, "fchownat", 5, { { "int", "fd" }, { "char *", "path" }, { "uid_t", "uid" }, { "gid_t", "gid" }, { "int", "flag" } } },
{ 469, "fstatat", 4, { { "int", "fd" }, { "char *", "path" }, { "user_addr_t", "ub" }, { "int", "flag" } } },
{ 470, "fstatat64", 4, { { "int", "fd" }, { "char *", "path" }, { "user_addr_t", "ub" }, { "int", "flag" } } },
{ 471, "linkat", 5, { { "int", "fd1" }, { "char *", "path" }, { "int", "fd2" }, { "char *", "link" }, { "int", "flag" } } },
{ 472, "unlinkat", 3, { { "int", "fd" }, { "char *", "path" }, { "int", "flag" } } },
{ 473, "readlinkat", 4, { { "int", "fd" }, { "char *", "path" }, { "user_addr_t", "buf" }, { "size_t", "bufsize" } } },
{ 474, "symlinkat", 3, { { "user_addr_t *", "path1" }, { "int", "fd" }, { "user_addr_t", "path2" } } },
{ 475, "mkdirat", 3, { { "int", "fd" }, { "char *", "path" }, { "int", "mode" } } },
{ 476, "getattrlistat", 6, { { "int", "fd" }, { "const char *", "path" }, { "struct attrlist *", "alist" }, { "void *", "attribute_buffer" }, { "size_t", "buffer_size" }, { "u_long", "options" } } },
{ 477, "proc_trace_log", 2, { { "pid_t", "pid" }, { "uint64_t", "uniqueid" } } },
{ 478, "bsdthread_ctl", 4, { { "user_addr_t", "cmd" }, { "user_addr_t", "arg1" }, { "user_addr_t", "arg2" }, { "user_addr_t", "arg3" } } },
{ 479, "openbyid_np", 3, { { "user_addr_t", "fsid" }, { "user_addr_t", "objid" }, { "int", "oflags" } } },
{ 480, "recvmsg_x", 4, { { "int", "s" }, { "struct msghdr_x *", "msgp" }, { "u_int", "cnt" }, { "int", "flags" } } },
{ 481, "sendmsg_x", 4, { { "int", "s" }, { "struct msghdr_x *", "msgp" }, { "u_int", "cnt" }, { "int", "flags" } } },
{ 482, "thread_selfusage", 0, {} },
{ 483, "csrctl", 3, { { "uint32_t", "op" }, { "user_addr_t", "useraddr" }, { "user_addr_t", "usersize" } } },
{ 484, "guarded_open_dprotected_np", 7, { { "char *", "path" }, { "const guardid_t *", "guard" }, { "u_int", "guardflags" }, { "int", "flags" }, { "int", "dpclass" }, { "int", "dpflags" }, { "int", "mode" } } },
{ 485, "guarded_write_np", 4, { { "int", "fd" }, { "const guardid_t *", "guard" }, { "user_addr_t", "cbuf" }, { "user_size_t", "nbyte" } } },
{ 486, "guarded_pwrite_np", 5, { { "int", "fd" }, { "const guardid_t *", "guard" }, { "user_addr_t", "buf" }, { "user_size_t", "nbyte" }, { "off_t", "offset" } } },
{ 487, "guarded_writev_np", 4, { { "int", "fd" }, { "const guardid_t *", "guard" }, { "struct iovec *", "iovp" }, { "int", "iovcnt" } } },
{ 488, "renameatx_np", 5, { { "int", "fromfd" }, { "char *", "from" }, { "int", "tofd" }, { "char *", "to" }, { "u_int", "flags" } } },
{ 489, "mremap_encrypted", 5, { { "caddr_ut", "addr" }, { "size_ut", "len" }, { "uint32_t", "cryptid" }, { "uint32_t", "cputype" }, { "uint32_t", "cpusubtype" } } },
{ 490, "netagent_trigger", 2, { { "uuid_t", "agent_uuid" }, { "size_t", "agent_uuidlen" } } },
{ 491, "stack_snapshot_with_config", 3, { { "int", "stackshot_config_version" }, { "user_addr_t", "stackshot_config" }, { "size_t", "stackshot_config_size" } } },
{ 492, "microstackshot", 3, { { "user_addr_t", "tracebuf" }, { "uint32_t", "tracebuf_size" }, { "uint32_t", "flags" } } },
{ 493, "grab_pgo_data", 4, { { "user_addr_t", "uuid" }, { "int", "flags" }, { "user_addr_t", "buffer" }, { "user_ssize_t", "size" } } },
{ 494, "persona", 6, { { "uint32_t", "operation" }, { "uint32_t", "flags" }, { "struct kpersona_info *", "info" }, { "uid_t *", "id" }, { "size_t *", "idlen" }, { "char *", "path" } } },
{ 496, "mach_eventlink_signal", 2, { { "mach_port_name_t", "eventlink_port" }, { "uint64_t", "signal_count" } } },
{ 497, "mach_eventlink_wait_until", 5, { { "mach_port_name_t", "eventlink_port" }, { "uint64_t", "wait_count" }, { "uint64_t", "deadline" }, { "uint32_t", "clock_id" }, { "uint32_t", "option" } } },
{ 498, "mach_eventlink_signal_wait_until", 6, { { "mach_port_name_t", "eventlink_port" }, { "uint64_t", "wait_count" }, { "uint64_t", "signal_count" }, { "uint64_t", "deadline" }, { "uint32_t", "clock_id" }, { "uint32_t", "option" } } },
{ 499, "work_interval_ctl", 4, { { "uint32_t", "operation" }, { "uint64_t", "work_interval_id" }, { "void *", "arg" }, { "size_t", "len" } } },
{ 500, "getentropy", 2, { { "void *", "buffer" }, { "size_t", "size" } } },
{ 502, "necp_client_action", 6, { { "int", "necp_fd" }, { "uint32_t", "action" }, { "uuid_t", "client_id" }, { "size_t", "client_id_len" }, { "uint8_t *", "buffer" }, { "size_t", "buffer_size" } } },
{ 503, "nexus_open", 2, { { "struct nxctl_init *", "init" }, { "uint32_t", "init_len" } } },
{ 504, "nexus_register", 5, { { "int", "ctl" }, { "struct nxprov_reg *", "reg" }, { "uint32_t", "reg_len" }, { "uuid_t *", "prov_uuid" }, { "uint32_t", "prov_uuid_len" } } },
{ 505, "nexus_deregister", 3, { { "int", "ctl" }, { "uuid_t", "prov_uuid" }, { "uint32_t", "prov_uuid_len" } } },
{ 506, "nexus_create", 5, { { "int", "ctl" }, { "uuid_t", "prov_uuid" }, { "uint32_t", "prov_uuid_len" }, { "uuid_t *", "nx_uuid" }, { "uint32_t", "nx_uuid_len" } } },
{ 507, "nexus_destroy", 3, { { "int", "ctl" }, { "uuid_t", "nx_uuid" }, { "uint32_t", "nx_uuid_len" } } },
{ 508, "nexus_get_opt", 4, { { "int", "ctl" }, { "uint32_t", "opt" }, { "void *", "aoptval" }, { "uint32_t *", "aoptlen" } } },
{ 509, "nexus_set_opt", 4, { { "int", "ctl" }, { "uint32_t", "opt" }, { "const void *", "aoptval" }, { "uint32_t", "optlen" } } },
{ 510, "channel_open", 2, { { "struct ch_init *", "init" }, { "uint32_t", "init_len" } } },
{ 511, "channel_get_info", 3, { { "int", "c" }, { "struct ch_info *", "cinfo" }, { "uint32_t", "cinfolen" } } },
{ 512, "channel_sync", 3, { { "int", "c" }, { "int", "mode" }, { "int", "flags" } } },
{ 513, "channel_get_opt", 4, { { "int", "c" }, { "uint32_t", "opt" }, { "void *", "aoptval" }, { "uint32_t *", "aoptlen" } } },
{ 514, "channel_set_opt", 4, { { "int", "c" }, { "uint32_t", "opt" }, { "const void *", "aoptval" }, { "uint32_t", "optlen" } } },
{ 515, "ulock_wait", 4, { { "uint32_t", "operation" }, { "void *", "addr" }, { "uint64_t", "value" }, { "uint32_t", "timeout" } } },
{ 516, "ulock_wake", 3, { { "uint32_t", "operation" }, { "void *", "addr" }, { "uint64_t", "wake_value" } } },
{ 517, "fclonefileat", 4, { { "int", "src_fd" }, { "int", "dst_dirfd" }, { "user_addr_t", "dst" }, { "uint32_t", "flags" } } },
{ 518, "fs_snapshot", 6, { { "uint32_t", "op" }, { "int", "dirfd" }, { "user_addr_t", "name1" }, { "user_addr_t", "name2" }, { "user_addr_t", "data" }, { "uint32_t", "flags" } } },
{ 520, "terminate_with_payload", 7, { { "int", "pid" }, { "uint32_t", "reason_namespace" }, { "uint64_t", "reason_code" }, { "void *", "payload" }, { "uint32_t", "payload_size" }, { "const char *", "reason_string" }, { "uint64_t", "reason_flags" } } },
{ 521, "abort_with_payload", 6, { { "uint32_t", "reason_namespace" }, { "uint64_t", "reason_code" }, { "void *", "payload" }, { "uint32_t", "payload_size" }, { "const char *", "reason_string" }, { "uint64_t", "reason_flags" } } },
{ 523, "necp_session_action", 6, { { "int", "necp_fd" }, { "uint32_t", "action" }, { "uint8_t *", "in_buffer" }, { "size_t", "in_buffer_length" }, { "uint8_t *", "out_buffer" }, { "size_t", "out_buffer_length" } } },
{ 524, "setattrlistat", 6, { { "int", "fd" }, { "const char *", "path" }, { "struct attrlist *", "alist" }, { "void *", "attribute_buffer" }, { "size_t", "buffer_size" }, { "uint32_t", "options" } } },
{ 525, "net_qos_guideline", 2, { { "struct net_qos_param *", "param" }, { "uint32_t", "param_len" } } },
{ 526, "fmount", 4, { { "const char *", "type" }, { "int", "fd" }, { "int", "flags" }, { "void *", "data" } } },
{ 527, "ntp_adjtime", 1, { { "struct timex *", "tp" } } },
{ 528, "ntp_gettime", 1, { { "struct ntptimeval *", "ntvp" } } },
{ 529, "os_fault_with_payload", 6, { { "uint32_t", "reason_namespace" }, { "uint64_t", "reason_code" }, { "void *", "payload" }, { "uint32_t", "payload_size" }, { "const char *", "reason_string" }, { "uint64_t", "reason_flags" } } },
{ 530, "kqueue_workloop_ctl", 4, { { "user_addr_t", "cmd" }, { "uint64_t", "options" }, { "user_addr_t", "addr" }, { "size_t", "sz" } } },
{ 531, "mach_bridge_remote_time", 1, { { "uint64_t", "local_timestamp" } } },
{ 532, "coalition_ledger", 4, { { "uint32_t", "operation" }, { "uint64_t *", "cid" }, { "void *", "buffer" }, { "size_t *", "bufsize" } } },
{ 533, "log_data", 4, { { "unsigned int", "tag" }, { "unsigned int", "flags" }, { "void *", "buffer" }, { "unsigned int", "size" } } },
{ 534, "memorystatus_available_memory", 0, {} },
{ 535, "objc_bp_assist_cfg_np", 2, { { "uint64_t", "adr" }, { "uint64_t", "ctl" } } },
{ 536, "shared_region_map_and_slide_2_np", 4, { { "uint32_t", "files_count" }, { "const struct shared_file_np *", "files" }, { "uint32_t", "mappings_count" }, { "const shared_file_mapping_slide_np_ut *", "mappings_u" } } },
{ 537, "pivot_root", 2, { { "const char *", "new_rootfs_path_before" }, { "const char *", "old_rootfs_path_after" } } },
{ 538, "task_inspect_for_pid", 3, { { "mach_port_name_t", "target_tport" }, { "int", "pid" }, { "mach_port_name_t *", "t" } } },
{ 539, "task_read_for_pid", 3, { { "mach_port_name_t", "target_tport" }, { "int", "pid" }, { "mach_port_name_t *", "t" } } },
{ 540, "preadv", 4, { { "int", "fd" }, { "struct iovec *", "iovp" }, { "int", "iovcnt" }, { "off_t", "offset" } } },
{ 541, "pwritev", 4, { { "int", "fd" }, { "struct iovec *", "iovp" }, { "int", "iovcnt" }, { "off_t", "offset" } } },
{ 542, "preadv_nocancel", 4, { { "int", "fd" }, { "struct iovec *", "iovp" }, { "int", "iovcnt" }, { "off_t", "offset" } } },
{ 543, "pwritev_nocancel", 4, { { "int", "fd" }, { "struct iovec *", "iovp" }, { "int", "iovcnt" }, { "off_t", "offset" } } },
{ 544, "ulock_wait2", 5, { { "uint32_t", "operation" }, { "void *", "addr" }, { "uint64_t", "value" }, { "uint64_t", "timeout" }, { "uint64_t", "value2" } } },
{ 545, "proc_info_extended_id", 8, { { "int32_t", "callnum" }, { "int32_t", "pid" }, { "uint32_t", "flavor" }, { "uint32_t", "flags" }, { "uint64_t", "ext_id" }, { "uint64_t", "arg" }, { "user_addr_t", "buffer" }, { "int32_t", "buffersize" } } },
{ 546, "tracker_action", 3, { { "int", "action" }, { "char *", "buffer" }, { "size_t", "buffer_size" } } },
{ 547, "debug_syscall_reject", 1, { { "uint64_t", "packed_selectors" } } },
{ 548, "debug_syscall_reject_config", 3, { { "uint64_t", "packed_selectors1" }, { "uint64_t", "packed_selectors2" }, { "uint64_t", "flags" } } },
{ 549, "graftdmg", 4, { { "int", "dmg_fd" }, { "const char *", "mountdir" }, { "uint32_t", "graft_type" }, { "graftdmg_args_un *", "gda" } } },
{ 550, "map_with_linking_np", 4, { { "void *", "regions" }, { "uint32_t", "region_count" }, { "void *", "link_info" }, { "uint32_t", "link_info_size" } } },
{ 551, "freadlink", 3, { { "int", "fd" }, { "user_addr_t", "buf" }, { "user_size_t", "bufsize" } } },
{ 552, "record_system_event", 4, { { "uint32_t", "type" }, { "uint32_t", "subsystem" }, { "const char *", "event" }, { "const char *", "payload" } } },
{ 553, "mkfifoat", 3, { { "int", "fd" }, { "char *", "path" }, { "int", "mode" } } },
{ 554, "mknodat", 4, { { "int", "fd" }, { "char *", "path" }, { "int", "mode" }, { "int", "dev" } } },
{ 555, "ungraftdmg", 2, { { "const char *", "mountdir" }, { "uint64_t", "flags" } } },
{ 556, "coalition_policy_set", 3, { { "uint64_t", "cid" }, { "uint32_t", "flavor" }, { "uint32_t", "value" } } },
{ 557, "coalition_policy_get", 2, { { "uint64_t", "cid" }, { "uint32_t", "flavor" } } },
};
FridaXnuSyscallSignature *
frida_get_xnu_mach_traps (int * len)
{
if (len != NULL)
*len = G_N_ELEMENTS (frida_xnu_mach_traps);
return (FridaXnuSyscallSignature *) frida_xnu_mach_traps;
}
FridaXnuSyscallSignature *
frida_get_xnu_bsd_syscalls (int * len)
{
if (len != NULL)
*len = G_N_ELEMENTS (frida_xnu_bsd_syscalls);
return (FridaXnuSyscallSignature *) frida_xnu_bsd_syscalls;
}
+539
View File
@@ -0,0 +1,539 @@
// AUTO-GENERATED FILE. DO NOT EDIT.
namespace Frida {
public extern unowned XnuSyscallSignature[] get_xnu_mach_traps ();
public extern unowned XnuSyscallSignature[] get_xnu_bsd_syscalls ();
public struct XnuSyscallSignature {
public int nr;
public string name;
public uint8 nargs;
public XnuSyscallArg args[9];
}
public struct XnuSyscallArg {
public string? type;
public string? name;
}
public enum XnuMachTrap {
MACH_VM_ALLOCATE = -10,
MACH_VM_PURGABLE_CONTROL = -11,
MACH_VM_DEALLOCATE = -12,
TASK_DYLD_PROCESS_INFO_NOTIFY_GET = -13,
MACH_VM_PROTECT = -14,
MACH_VM_MAP = -15,
MACH_PORT_ALLOCATE = -16,
MACH_PORT_DEALLOCATE = -18,
MACH_PORT_MOD_REFS = -19,
MACH_PORT_MOVE_MEMBER = -20,
MACH_PORT_INSERT_RIGHT = -21,
MACH_PORT_INSERT_MEMBER = -22,
MACH_PORT_EXTRACT_MEMBER = -23,
MACH_PORT_CONSTRUCT = -24,
MACH_PORT_DESTRUCT = -25,
MACH_REPLY_PORT = -26,
THREAD_SELF = -27,
TASK_SELF = -28,
HOST_SELF = -29,
MACH_MSG = -31,
MACH_MSG_OVERWRITE = -32,
SEMAPHORE_SIGNAL = -33,
SEMAPHORE_SIGNAL_ALL = -34,
SEMAPHORE_SIGNAL_THREAD = -35,
SEMAPHORE_WAIT = -36,
SEMAPHORE_WAIT_SIGNAL = -37,
SEMAPHORE_TIMEDWAIT = -38,
SEMAPHORE_TIMEDWAIT_SIGNAL = -39,
MACH_PORT_GET_ATTRIBUTES = -40,
MACH_PORT_GUARD = -41,
MACH_PORT_UNGUARD = -42,
MACH_GENERATE_ACTIVITY_ID = -43,
TASK_NAME_FOR_PID = -44,
TASK_FOR_PID = -45,
PID_FOR_TASK = -46,
MACH_MSG2 = -47,
MACX_SWAPON = -48,
MACX_SWAPOFF = -49,
THREAD_GET_SPECIAL_REPLY_PORT = -50,
MACX_TRIGGERS = -51,
MACX_BACKING_STORE_SUSPEND = -52,
MACX_BACKING_STORE_RECOVERY = -53,
PFZ_EXIT = -58,
SWTCH_PRI = -59,
SWTCH = -60,
THREAD_SWITCH = -61,
CLOCK_SLEEP = -62,
MACH_VM_RECLAIM_UPDATE_KERNEL_ACCOUNTING = -63,
HOST_CREATE_MACH_VOUCHER = -70,
MACH_VOUCHER_EXTRACT_ATTR_RECIPE = -72,
MACH_PORT_TYPE = -76,
MACH_PORT_REQUEST_NOTIFICATION = -77,
EXCLAVES_CTL = -88,
MACH_TIMEBASE_INFO = -89,
MACH_WAIT_UNTIL = -90,
MK_TIMER_CREATE = -91,
MK_TIMER_DESTROY = -92,
MK_TIMER_ARM = -93,
MK_TIMER_CANCEL = -94,
MK_TIMER_ARM_LEEWAY = -95,
DEBUG_CONTROL_PORT_FOR_PID = -96,
IOKIT_USER_CLIENT = -100,
}
public enum XnuBsdSyscall {
EXIT = 1,
FORK = 2,
READ = 3,
WRITE = 4,
OPEN = 5,
CLOSE = 6,
WAIT4 = 7,
LINK = 9,
UNLINK = 10,
CHDIR = 12,
FCHDIR = 13,
MKNOD = 14,
CHMOD = 15,
CHOWN = 16,
GETFSSTAT = 18,
GETPID = 20,
SETUID = 23,
GETUID = 24,
GETEUID = 25,
PTRACE = 26,
RECVMSG = 27,
SENDMSG = 28,
RECVFROM = 29,
ACCEPT = 30,
GETPEERNAME = 31,
GETSOCKNAME = 32,
ACCESS = 33,
CHFLAGS = 34,
FCHFLAGS = 35,
SYNC = 36,
KILL = 37,
CROSSARCH_TRAP = 38,
GETPPID = 39,
DUP = 41,
PIPE = 42,
GETEGID = 43,
SIGACTION = 46,
GETGID = 47,
SIGPROCMASK = 48,
GETLOGIN = 49,
SETLOGIN = 50,
ACCT = 51,
SIGPENDING = 52,
SIGALTSTACK = 53,
IOCTL = 54,
REBOOT = 55,
REVOKE = 56,
SYMLINK = 57,
READLINK = 58,
EXECVE = 59,
UMASK = 60,
CHROOT = 61,
MSYNC = 65,
VFORK = 66,
OSLOG_COPROC_REG = 67,
OSLOG_COPROC = 68,
MUNMAP = 73,
MPROTECT = 74,
MADVISE = 75,
MINCORE = 78,
GETGROUPS = 79,
SETGROUPS = 80,
GETPGRP = 81,
SETPGID = 82,
SETITIMER = 83,
SWAPON = 85,
GETITIMER = 86,
GETDTABLESIZE = 89,
DUP2 = 90,
FCNTL = 92,
SELECT = 93,
FSYNC = 95,
SETPRIORITY = 96,
SOCKET = 97,
CONNECT = 98,
GETPRIORITY = 100,
BIND = 104,
SETSOCKOPT = 105,
LISTEN = 106,
SIGSUSPEND = 111,
GETTIMEOFDAY = 116,
GETRUSAGE = 117,
GETSOCKOPT = 118,
READV = 120,
WRITEV = 121,
SETTIMEOFDAY = 122,
FCHOWN = 123,
FCHMOD = 124,
SETREUID = 126,
SETREGID = 127,
RENAME = 128,
FLOCK = 131,
MKFIFO = 132,
SENDTO = 133,
SHUTDOWN = 134,
SOCKETPAIR = 135,
MKDIR = 136,
RMDIR = 137,
UTIMES = 138,
FUTIMES = 139,
ADJTIME = 140,
GETHOSTUUID = 142,
SETSID = 147,
GETPGID = 151,
SETPRIVEXEC = 152,
PREAD = 153,
PWRITE = 154,
NFSSVC = 155,
STATFS = 157,
FSTATFS = 158,
UNMOUNT = 159,
GETFH = 161,
FUNMOUNT = 164,
QUOTACTL = 165,
MOUNT = 167,
CSOPS = 169,
CSOPS_AUDITTOKEN = 170,
WAITID = 173,
KDEBUG_TYPEFILTER = 177,
KDEBUG_TRACE_STRING = 178,
KDEBUG_TRACE64 = 179,
KDEBUG_TRACE = 180,
SETGID = 181,
SETEGID = 182,
SETEUID = 183,
SIGRETURN = 184,
PANIC_WITH_DATA = 185,
THREAD_SELFCOUNTS = 186,
FDATASYNC = 187,
STAT = 188,
FSTAT = 189,
LSTAT = 190,
PATHCONF = 191,
FPATHCONF = 192,
GETRLIMIT = 194,
SETRLIMIT = 195,
GETDIRENTRIES = 196,
MMAP = 197,
LSEEK = 199,
TRUNCATE = 200,
FTRUNCATE = 201,
SYSCTL = 202,
MLOCK = 203,
MUNLOCK = 204,
UNDELETE = 205,
OPEN_DPROTECTED_NP = 216,
FSGETPATH_EXT = 217,
OPENAT_DPROTECTED_NP = 218,
GETATTRLIST = 220,
SETATTRLIST = 221,
GETDIRENTRIESATTR = 222,
EXCHANGEDATA = 223,
SEARCHFS = 225,
DELETE = 226,
COPYFILE = 227,
FGETATTRLIST = 228,
FSETATTRLIST = 229,
POLL = 230,
GETXATTR = 234,
FGETXATTR = 235,
SETXATTR = 236,
FSETXATTR = 237,
REMOVEXATTR = 238,
FREMOVEXATTR = 239,
LISTXATTR = 240,
FLISTXATTR = 241,
FSCTL = 242,
INITGROUPS = 243,
POSIX_SPAWN = 244,
FFSCTL = 245,
FHOPEN = 248,
MINHERIT = 250,
SEMSYS = 251,
MSGSYS = 252,
SHMSYS = 253,
SEMCTL = 254,
SEMGET = 255,
SEMOP = 256,
MSGCTL = 258,
MSGGET = 259,
MSGSND = 260,
MSGRCV = 261,
SHMAT = 262,
SHMCTL = 263,
SHMDT = 264,
SHMGET = 265,
SHM_OPEN = 266,
SHM_UNLINK = 267,
SEM_OPEN = 268,
SEM_CLOSE = 269,
SEM_UNLINK = 270,
SEM_WAIT = 271,
SEM_TRYWAIT = 272,
SEM_POST = 273,
SYSCTLBYNAME = 274,
OPEN_EXTENDED = 277,
UMASK_EXTENDED = 278,
STAT_EXTENDED = 279,
LSTAT_EXTENDED = 280,
FSTAT_EXTENDED = 281,
CHMOD_EXTENDED = 282,
FCHMOD_EXTENDED = 283,
ACCESS_EXTENDED = 284,
SETTID = 285,
GETTID = 286,
SETSGROUPS = 287,
GETSGROUPS = 288,
SETWGROUPS = 289,
GETWGROUPS = 290,
MKFIFO_EXTENDED = 291,
MKDIR_EXTENDED = 292,
IDENTITYSVC = 293,
SHARED_REGION_CHECK_NP = 294,
VM_PRESSURE_MONITOR = 296,
PSYNCH_RW_LONGRDLOCK = 297,
PSYNCH_RW_YIELDWRLOCK = 298,
PSYNCH_RW_DOWNGRADE = 299,
PSYNCH_RW_UPGRADE = 300,
PSYNCH_MUTEXWAIT = 301,
PSYNCH_MUTEXDROP = 302,
PSYNCH_CVBROAD = 303,
PSYNCH_CVSIGNAL = 304,
PSYNCH_CVWAIT = 305,
PSYNCH_RW_RDLOCK = 306,
PSYNCH_RW_WRLOCK = 307,
PSYNCH_RW_UNLOCK = 308,
PSYNCH_RW_UNLOCK2 = 309,
GETSID = 310,
SETTID_WITH_PID = 311,
PSYNCH_CVCLRPREPOST = 312,
AIO_FSYNC = 313,
AIO_RETURN = 314,
AIO_SUSPEND = 315,
AIO_CANCEL = 316,
AIO_ERROR = 317,
AIO_READ = 318,
AIO_WRITE = 319,
LIO_LISTIO = 320,
IOPOLICYSYS = 322,
PROCESS_POLICY = 323,
MLOCKALL = 324,
MUNLOCKALL = 325,
ISSETUGID = 327,
PTHREAD_KILL = 328,
PTHREAD_SIGMASK = 329,
SIGWAIT = 330,
DISABLE_THREADSIGNAL = 331,
PTHREAD_MARKCANCEL = 332,
PTHREAD_CANCELED = 333,
SEMWAIT_SIGNAL = 334,
PROC_INFO = 336,
SENDFILE = 337,
STAT64 = 338,
FSTAT64 = 339,
LSTAT64 = 340,
STAT64_EXTENDED = 341,
LSTAT64_EXTENDED = 342,
FSTAT64_EXTENDED = 343,
GETDIRENTRIES64 = 344,
STATFS64 = 345,
FSTATFS64 = 346,
GETFSSTAT64 = 347,
PTHREAD_CHDIR = 348,
PTHREAD_FCHDIR = 349,
AUDIT = 350,
AUDITON = 351,
GETAUID = 353,
SETAUID = 354,
GETAUDIT_ADDR = 357,
SETAUDIT_ADDR = 358,
AUDITCTL = 359,
BSDTHREAD_CREATE = 360,
BSDTHREAD_TERMINATE = 361,
KQUEUE = 362,
KEVENT = 363,
LCHOWN = 364,
BSDTHREAD_REGISTER = 366,
WORKQ_OPEN = 367,
WORKQ_KERNRETURN = 368,
KEVENT64 = 369,
THREAD_SELFID = 372,
LEDGER = 373,
KEVENT_QOS = 374,
KEVENT_ID = 375,
MAC_EXECVE = 380,
MAC_SYSCALL = 381,
MAC_GET_FILE = 382,
MAC_SET_FILE = 383,
MAC_GET_LINK = 384,
MAC_SET_LINK = 385,
MAC_GET_PROC = 386,
MAC_SET_PROC = 387,
MAC_GET_FD = 388,
MAC_SET_FD = 389,
MAC_GET_PID = 390,
PSELECT = 394,
PSELECT_NOCANCEL = 395,
READ_NOCANCEL = 396,
WRITE_NOCANCEL = 397,
OPEN_NOCANCEL = 398,
CLOSE_NOCANCEL = 399,
WAIT4_NOCANCEL = 400,
RECVMSG_NOCANCEL = 401,
SENDMSG_NOCANCEL = 402,
RECVFROM_NOCANCEL = 403,
ACCEPT_NOCANCEL = 404,
MSYNC_NOCANCEL = 405,
FCNTL_NOCANCEL = 406,
SELECT_NOCANCEL = 407,
FSYNC_NOCANCEL = 408,
CONNECT_NOCANCEL = 409,
SIGSUSPEND_NOCANCEL = 410,
READV_NOCANCEL = 411,
WRITEV_NOCANCEL = 412,
SENDTO_NOCANCEL = 413,
PREAD_NOCANCEL = 414,
PWRITE_NOCANCEL = 415,
WAITID_NOCANCEL = 416,
POLL_NOCANCEL = 417,
MSGSND_NOCANCEL = 418,
MSGRCV_NOCANCEL = 419,
SEM_WAIT_NOCANCEL = 420,
AIO_SUSPEND_NOCANCEL = 421,
SIGWAIT_NOCANCEL = 422,
SEMWAIT_SIGNAL_NOCANCEL = 423,
MAC_MOUNT = 424,
MAC_GET_MOUNT = 425,
MAC_GETFSSTAT = 426,
FSGETPATH = 427,
AUDIT_SESSION_SELF = 428,
AUDIT_SESSION_JOIN = 429,
FILEPORT_MAKEPORT = 430,
FILEPORT_MAKEFD = 431,
AUDIT_SESSION_PORT = 432,
PID_SUSPEND = 433,
PID_RESUME = 434,
PID_HIBERNATE = 435,
PID_SHUTDOWN_SOCKETS = 436,
KAS_INFO = 439,
MEMORYSTATUS_CONTROL = 440,
GUARDED_OPEN_NP = 441,
GUARDED_CLOSE_NP = 442,
GUARDED_KQUEUE_NP = 443,
CHANGE_FDGUARD_NP = 444,
USRCTL = 445,
PROC_RLIMIT_CONTROL = 446,
CONNECTX = 447,
DISCONNECTX = 448,
PEELOFF = 449,
SOCKET_DELEGATE = 450,
TELEMETRY = 451,
PROC_UUID_POLICY = 452,
MEMORYSTATUS_GET_LEVEL = 453,
SYSTEM_OVERRIDE = 454,
VFS_PURGE = 455,
SFI_CTL = 456,
SFI_PIDCTL = 457,
COALITION = 458,
COALITION_INFO = 459,
NECP_MATCH_POLICY = 460,
GETATTRLISTBULK = 461,
CLONEFILEAT = 462,
OPENAT = 463,
OPENAT_NOCANCEL = 464,
RENAMEAT = 465,
FACCESSAT = 466,
FCHMODAT = 467,
FCHOWNAT = 468,
FSTATAT = 469,
FSTATAT64 = 470,
LINKAT = 471,
UNLINKAT = 472,
READLINKAT = 473,
SYMLINKAT = 474,
MKDIRAT = 475,
GETATTRLISTAT = 476,
PROC_TRACE_LOG = 477,
BSDTHREAD_CTL = 478,
OPENBYID_NP = 479,
RECVMSG_X = 480,
SENDMSG_X = 481,
THREAD_SELFUSAGE = 482,
CSRCTL = 483,
GUARDED_OPEN_DPROTECTED_NP = 484,
GUARDED_WRITE_NP = 485,
GUARDED_PWRITE_NP = 486,
GUARDED_WRITEV_NP = 487,
RENAMEATX_NP = 488,
MREMAP_ENCRYPTED = 489,
NETAGENT_TRIGGER = 490,
STACK_SNAPSHOT_WITH_CONFIG = 491,
MICROSTACKSHOT = 492,
GRAB_PGO_DATA = 493,
PERSONA = 494,
MACH_EVENTLINK_SIGNAL = 496,
MACH_EVENTLINK_WAIT_UNTIL = 497,
MACH_EVENTLINK_SIGNAL_WAIT_UNTIL = 498,
WORK_INTERVAL_CTL = 499,
GETENTROPY = 500,
NECP_CLIENT_ACTION = 502,
NEXUS_OPEN = 503,
NEXUS_REGISTER = 504,
NEXUS_DEREGISTER = 505,
NEXUS_CREATE = 506,
NEXUS_DESTROY = 507,
NEXUS_GET_OPT = 508,
NEXUS_SET_OPT = 509,
CHANNEL_OPEN = 510,
CHANNEL_GET_INFO = 511,
CHANNEL_SYNC = 512,
CHANNEL_GET_OPT = 513,
CHANNEL_SET_OPT = 514,
ULOCK_WAIT = 515,
ULOCK_WAKE = 516,
FCLONEFILEAT = 517,
FS_SNAPSHOT = 518,
TERMINATE_WITH_PAYLOAD = 520,
ABORT_WITH_PAYLOAD = 521,
NECP_SESSION_ACTION = 523,
SETATTRLISTAT = 524,
NET_QOS_GUIDELINE = 525,
FMOUNT = 526,
NTP_ADJTIME = 527,
NTP_GETTIME = 528,
OS_FAULT_WITH_PAYLOAD = 529,
KQUEUE_WORKLOOP_CTL = 530,
MACH_BRIDGE_REMOTE_TIME = 531,
COALITION_LEDGER = 532,
LOG_DATA = 533,
MEMORYSTATUS_AVAILABLE_MEMORY = 534,
OBJC_BP_ASSIST_CFG_NP = 535,
SHARED_REGION_MAP_AND_SLIDE_2_NP = 536,
PIVOT_ROOT = 537,
TASK_INSPECT_FOR_PID = 538,
TASK_READ_FOR_PID = 539,
PREADV = 540,
PWRITEV = 541,
PREADV_NOCANCEL = 542,
PWRITEV_NOCANCEL = 543,
ULOCK_WAIT2 = 544,
PROC_INFO_EXTENDED_ID = 545,
TRACKER_ACTION = 546,
DEBUG_SYSCALL_REJECT = 547,
DEBUG_SYSCALL_REJECT_CONFIG = 548,
GRAFTDMG = 549,
MAP_WITH_LINKING_NP = 550,
FREADLINK = 551,
RECORD_SYSTEM_EVENT = 552,
MKFIFOAT = 553,
MKNODAT = 554,
UNGRAFTDMG = 555,
COALITION_POLICY_SET = 556,
COALITION_POLICY_GET = 557,
}
}
+11
View File
@@ -0,0 +1,11 @@
FRIDA_1.0 {
local:
*;
};
GLIBC_2.2.5 {
local:
fopen*;
fseeko*;
ftello*;
} FRIDA_1.0;
+2
View File
@@ -118,6 +118,8 @@ frida_gadget_environment_deinit (void)
g_assert (worker_loop != NULL);
frida_libc_shim_prepare_to_deinit ();
source = g_idle_source_new ();
g_source_set_priority (source, G_PRIORITY_LOW);
g_source_set_callback (source, stop_worker_loop, NULL, NULL);
+1 -1
View File
@@ -45,7 +45,7 @@ elif host_os_family == 'darwin'
extra_link_args += '-Wl,-exported_symbols_list,' + meson.current_source_dir() / symlist
extra_link_depends += symlist
else
symscript = 'frida-gadget.version'
symscript = (libc == 'glibc') ? 'frida-gadget-glibc.version' : 'frida-gadget.version'
extra_link_args += '-Wl,--version-script,' + meson.current_source_dir() / symscript
extra_link_depends += symscript
endif
+404 -30
View File
@@ -10,6 +10,7 @@
# include <assert.h>
# include <fcntl.h>
# include <unistd.h>
# include <wchar.h>
#endif
#if defined (HAVE_DARWIN)
# include <sys/attr.h>
@@ -23,23 +24,50 @@
# include <xlocale.h>
#endif
#undef __srget
#undef feof
#undef ferror
#undef fgetwc
#undef fopen
#undef fopen64
#undef fputwc
#undef fseek
#undef fseeko
#undef fseeko64
#undef ftell
#undef ftello
#undef ftello64
#undef getc
#undef getc_unlocked
#undef getwc
#undef memcpy
#undef putc
#undef putchar
#undef putwc
#undef setbuf
#undef setbuffer
#undef setlinebuf
#undef snprintf
#undef sprintf
#undef stderr
#undef stdin
#undef stdout
#undef ungetc
#undef ungetwc
#undef vsnprintf
#ifdef HAVE_MUSL
# define FRIDA_STDIO_OPAQUE_FILE 1
#endif
static gboolean frida_deinit_expected = FALSE;
void
frida_libc_shim_prepare_to_deinit (void)
{
frida_deinit_expected = TRUE;
}
#if defined (HAVE_WINDOWS) || defined (HAVE_ASAN)
void
@@ -70,6 +98,9 @@ __attribute__ ((destructor)) static
void
frida_libc_shim_deinit (void)
{
if (!frida_deinit_expected)
return;
# ifdef HAVE_ASAN
gum_deinit ();
# else
@@ -134,16 +165,18 @@ struct _FridaFile
int err;
guint8 * rbuf;
gboolean owns_rbuf;
size_t rcap;
size_t rpos;
size_t rlen;
guint8 * wbuf;
gboolean owns_wbuf;
size_t wcap;
size_t wlen;
int ungot;
gboolean has_ungot;
guint8 ungot_buf[8];
guint ungot_len;
};
struct _FridaFileHandle
@@ -171,6 +204,10 @@ struct _FridaDir
#endif
static FILE * frida_fopen_impl (const char * pathname, const char * mode);
static int frida_fseek_impl (FILE * stream, off_t offset, int whence);
static off_t frida_ftell_impl (FILE * stream);
static void frida_stdio_register_stream (FILE * stream);
static void frida_stdio_unregister_stream (FILE * stream);
#ifdef HAVE_FRIDA_DIR
@@ -193,6 +230,8 @@ static void frida_parse_fopen_mode (const char * mode, int * oflags);
static int frida_write_formatted_to_fd (int fd, const char * format, va_list args);
static gboolean frida_utf8_expected_len (guint8 first, guint * out_len);
#ifdef HAVE_FRIDA_DIR
static FridaDir * frida_dir_get_impl (DIR * dirp);
static DIR * frida_dir_wrap (FridaDir * impl);
@@ -317,6 +356,9 @@ frida_libc_shim_deinit (void)
fflush (NULL);
if (!frida_deinit_expected)
return;
G_LOCK (frida_stdio);
g_hash_table_iter_init (&iter, frida_streams);
@@ -639,8 +681,34 @@ asprintf_l (char ** ret, locale_t loc, const char * format, ...)
#endif
#ifdef HAVE_GLIBC
G_GNUC_INTERNAL FILE *
frida_fopen_glibc_225 (const char * pathname, const char * mode)
{
return frida_fopen_impl (pathname, mode);
}
__asm__ (".symver frida_fopen_glibc_225,fopen@@GLIBC_2.2.5");
G_GNUC_INTERNAL FILE *
frida_fopen64_glibc_225 (const char * pathname, const char * mode)
{
return frida_fopen_impl (pathname, mode);
}
__asm__ (".symver frida_fopen64_glibc_225,fopen64@@GLIBC_2.2.5");
#else
G_GNUC_INTERNAL FILE *
fopen (const char * pathname, const char * mode)
{
return frida_fopen_impl (pathname, mode);
}
#endif
static FILE *
frida_fopen_impl (const char * pathname, const char * mode)
{
FILE * result;
int oflags, fd;
@@ -714,8 +782,17 @@ setvbuf (FILE * stream, char * buf, int mode, size_t size)
if (mode == _IONBF)
{
g_clear_pointer (&f->rbuf, g_free);
g_clear_pointer (&f->wbuf, g_free);
if (f->owns_rbuf)
g_clear_pointer (&f->rbuf, g_free);
else
f->rbuf = NULL;
f->owns_rbuf = FALSE;
if (f->owns_wbuf)
g_clear_pointer (&f->wbuf, g_free);
else
f->wbuf = NULL;
f->owns_wbuf = FALSE;
f->rcap = 0;
f->wcap = 0;
@@ -727,13 +804,40 @@ setvbuf (FILE * stream, char * buf, int mode, size_t size)
}
if (size == 0)
size = FRIDA_STDIO_BUFSIZE;
size = BUFSIZ;
if (!f->owns_rbuf)
{
f->rbuf = NULL;
f->rcap = 0;
}
f->rbuf = g_realloc (f->rbuf, size);
f->wbuf = g_realloc (f->wbuf, size);
f->owns_rbuf = TRUE;
f->rcap = size;
f->wcap = size;
if (buf != NULL)
{
if (f->owns_wbuf)
g_clear_pointer (&f->wbuf, g_free);
f->wbuf = (guint8 *) buf;
f->owns_wbuf = FALSE;
f->wcap = size;
}
else
{
if (!f->owns_wbuf)
{
f->wbuf = NULL;
f->wcap = 0;
}
f->wbuf = g_realloc (f->wbuf, size);
f->owns_wbuf = TRUE;
f->wcap = size;
}
f->rpos = 0;
f->rlen = 0;
f->wlen = 0;
@@ -741,6 +845,39 @@ setvbuf (FILE * stream, char * buf, int mode, size_t size)
return 0;
}
G_GNUC_INTERNAL void
setbuf (FILE * stream, char * buf)
{
if (buf == NULL)
(void) setvbuf (stream, NULL, _IONBF, 0);
else
(void) setvbuf (stream, buf, _IOFBF, BUFSIZ);
}
#if defined (HAVE_DARWIN) || defined (HAVE_ANDROID) || defined (HAVE_FREEBSD)
G_GNUC_INTERNAL int
setlinebuf (FILE * stream)
{
return setvbuf (stream, NULL, _IOLBF, 0);
}
#else
G_GNUC_INTERNAL void
setlinebuf (FILE * stream)
{
setvbuf (stream, NULL, _IOLBF, 0);
}
#endif
G_GNUC_INTERNAL void
#if defined (HAVE_DARWIN) || defined (HAVE_ANDROID) || defined (HAVE_FREEBSD)
setbuffer (FILE * stream, char * buf, int size)
#else
setbuffer (FILE * stream, char * buf, size_t size)
#endif
{
(void) setvbuf (stream, buf, (buf != NULL) ? _IOFBF : _IONBF, size);
}
G_GNUC_INTERNAL int
fflush (FILE * stream)
{
@@ -801,11 +938,8 @@ getc_unlocked (FILE * stream)
f = frida_file_get_impl (stream);
if (f->has_ungot)
{
f->has_ungot = FALSE;
return f->ungot;
}
if (f->ungot_len != 0)
return f->ungot_buf[--f->ungot_len];
if (f->buf_mode == _IONBF)
{
@@ -846,6 +980,64 @@ getc (FILE * stream)
return getc_unlocked (stream);
}
G_GNUC_INTERNAL int
__srget (FILE * stream)
{
return getc_unlocked (stream);
}
G_GNUC_INTERNAL wint_t
getwc (FILE * stream)
{
return fgetwc (stream);
}
G_GNUC_INTERNAL wint_t
fgetwc (FILE * stream)
{
char bytes[4];
guint need, have;
int c;
gunichar ch;
c = getc_unlocked (stream);
if (c == EOF)
return WEOF;
bytes[0] = c;
if (!frida_utf8_expected_len (bytes[0], &need))
{
errno = EILSEQ;
frida_file_get_impl (stream)->err = errno;
return WEOF;
}
have = 1;
while (have != need)
{
c = getc_unlocked (stream);
if (c == EOF)
{
errno = EILSEQ;
frida_file_get_impl (stream)->err = errno;
return WEOF;
}
bytes[have++] = c;
}
ch = g_utf8_get_char_validated (bytes, (gssize) need);
if (ch == (gunichar) -1 || ch == (gunichar) -2)
{
errno = EILSEQ;
frida_file_get_impl (stream)->err = errno;
return WEOF;
}
return (wint_t) ch;
}
G_GNUC_INTERNAL int
ungetc (int c, FILE * stream)
{
@@ -856,16 +1048,46 @@ ungetc (int c, FILE * stream)
if (c == EOF)
return EOF;
if (f->has_ungot)
if (f->ungot_len == G_N_ELEMENTS (f->ungot_buf))
return EOF;
f->ungot = c;
f->has_ungot = TRUE;
f->ungot_buf[f->ungot_len++] = c;
f->eof = FALSE;
return c;
}
G_GNUC_INTERNAL wint_t
ungetwc (wint_t wc, FILE * stream)
{
FridaFile * f;
char tmp[4];
int len;
int i;
if (wc == WEOF)
return WEOF;
f = frida_file_get_impl (stream);
len = g_unichar_to_utf8 ((gunichar) wc, tmp);
if (len <= 0 || len > 4)
{
errno = EILSEQ;
f->err = errno;
return WEOF;
}
if (f->ungot_len + len > G_N_ELEMENTS (f->ungot_buf))
return WEOF;
for (i = 0; i != len; i++)
f->ungot_buf[f->ungot_len++] = tmp[i];
f->eof = FALSE;
return wc;
}
G_GNUC_INTERNAL size_t
fread (void * ptr, size_t size, size_t nmemb, FILE * stream)
{
@@ -884,10 +1106,9 @@ fread (void * ptr, size_t size, size_t nmemb, FILE * stream)
while (got != want)
{
if (f->has_ungot)
if (f->ungot_len != 0)
{
out[got++] = (guint8) f->ungot;
f->has_ungot = FALSE;
out[got++] = f->ungot_buf[--f->ungot_len];
continue;
}
@@ -1006,6 +1227,12 @@ fwrite (const void * ptr, size_t size, size_t nmemb, FILE * stream)
return off / size;
}
G_GNUC_INTERNAL int
putc (int c, FILE * stream)
{
return fputc (c, stream);
}
G_GNUC_INTERNAL int
fputc (int c, FILE * stream)
{
@@ -1019,6 +1246,37 @@ fputc (int c, FILE * stream)
return ch;
}
G_GNUC_INTERNAL wint_t
putwc (wchar_t wc, FILE * stream)
{
return fputwc (wc, stream);
}
G_GNUC_INTERNAL wint_t
fputwc (wchar_t wc, FILE * stream)
{
char tmp[4];
int len;
size_t n;
if (wc == WEOF)
return WEOF;
len = g_unichar_to_utf8 ((gunichar) wc, tmp);
if (len <= 0 || len > 4)
{
errno = EILSEQ;
frida_file_get_impl (stream)->err = errno;
return WEOF;
}
n = fwrite (tmp, 1, len, stream);
if (n != len)
return WEOF;
return (wint_t) wc;
}
G_GNUC_INTERNAL int
fputs (const char * s, FILE * stream)
{
@@ -1062,6 +1320,84 @@ fgets (char * s, int size, FILE * stream)
G_GNUC_INTERNAL int
fseek (FILE * stream, long offset, int whence)
{
return frida_fseek_impl (stream, (off_t) offset, whence);
}
G_GNUC_INTERNAL long
ftell (FILE * stream)
{
off_t pos = frida_ftell_impl (stream);
if (pos == (off_t) -1)
return -1;
return (long) pos;
}
#ifdef HAVE_GLIBC
G_GNUC_INTERNAL int
frida_fseeko_glibc_225 (FILE * stream, off_t offset, int whence)
{
return frida_fseek_impl (stream, offset, whence);
}
__asm__ (".symver frida_fseeko_glibc_225,fseeko@@GLIBC_2.2.5");
G_GNUC_INTERNAL int
frida_fseeko64_glibc_225 (FILE * stream, off_t offset, int whence)
{
return frida_fseek_impl (stream, offset, whence);
}
__asm__ (".symver frida_fseeko64_glibc_225,fseeko64@@GLIBC_2.2.5");
G_GNUC_INTERNAL off_t
frida_ftello_glibc_225 (FILE * stream)
{
return frida_ftell_impl (stream);
}
__asm__ (".symver frida_ftello_glibc_225,ftello@@GLIBC_2.2.5");
G_GNUC_INTERNAL off_t
frida_ftello64_glibc_225 (FILE * stream)
{
return frida_ftell_impl (stream);
}
__asm__ (".symver frida_ftello64_glibc_225,ftello64@@GLIBC_2.2.5");
#else
G_GNUC_INTERNAL int
fseeko (FILE * stream, off_t offset, int whence)
{
return frida_fseek_impl (stream, offset, whence);
}
G_GNUC_INTERNAL off_t
ftello (FILE * stream)
{
return frida_ftell_impl (stream);
}
# ifndef HAVE_QNX
G_GNUC_INTERNAL int
fseeko64 (FILE * stream, off_t offset, int whence)
{
return frida_fseek_impl (stream, offset, whence);
}
G_GNUC_INTERNAL off_t
ftello64 (FILE * stream)
{
return frida_ftell_impl (stream);
}
# endif
#endif
static int
frida_fseek_impl (FILE * stream, off_t offset, int whence)
{
FridaFile * f;
off_t r;
@@ -1073,10 +1409,10 @@ fseek (FILE * stream, long offset, int whence)
f->rpos = 0;
f->rlen = 0;
f->has_ungot = FALSE;
f->ungot_len = 0;
f->eof = FALSE;
r = frida_lseek_nointr (f->fd, (off_t) offset, whence);
r = frida_lseek_nointr (f->fd, offset, whence);
if (r == (off_t) -1)
{
f->err = errno;
@@ -1086,8 +1422,8 @@ fseek (FILE * stream, long offset, int whence)
return 0;
}
G_GNUC_INTERNAL long
ftell (FILE * stream)
static off_t
frida_ftell_impl (FILE * stream)
{
FridaFile * f;
off_t pos;
@@ -1104,10 +1440,9 @@ ftell (FILE * stream)
if (f->buf_mode != _IONBF)
pos -= (off_t) (f->rlen - f->rpos);
if (f->has_ungot)
pos -= 1;
pos -= f->ungot_len;
return (long) pos;
return pos;
}
G_GNUC_INTERNAL void
@@ -1718,10 +2053,12 @@ frida_file_new (int fd, gboolean close_fd, int buf_mode)
if (buf_mode != _IONBF)
{
f->rcap = FRIDA_STDIO_BUFSIZE;
f->wcap = FRIDA_STDIO_BUFSIZE;
f->rbuf = g_malloc (f->rcap);
f->owns_rbuf = TRUE;
f->wcap = FRIDA_STDIO_BUFSIZE;
f->wbuf = g_malloc (f->wcap);
f->owns_wbuf = TRUE;
}
return f;
@@ -1733,8 +2070,15 @@ frida_file_free (FridaFile * f)
if (f == NULL)
return;
g_clear_pointer (&f->rbuf, g_free);
g_clear_pointer (&f->wbuf, g_free);
if (f->owns_rbuf)
g_clear_pointer (&f->rbuf, g_free);
else
f->rbuf = NULL;
if (f->owns_wbuf)
g_clear_pointer (&f->wbuf, g_free);
else
f->wbuf = NULL;
g_free (f);
}
@@ -1866,6 +2210,36 @@ beach:
}
}
static gboolean
frida_utf8_expected_len (guint8 first, guint * out_len)
{
if (first < 0x80)
{
*out_len = 1;
return TRUE;
}
if ((first & 0xe0) == 0xc0)
{
*out_len = 2;
return TRUE;
}
if ((first & 0xf0) == 0xe0)
{
*out_len = 3;
return TRUE;
}
if ((first & 0xf8) == 0xf0)
{
*out_len = 4;
return TRUE;
}
return FALSE;
}
#ifdef HAVE_FRIDA_DIR
static FridaDir *
+1
View File
@@ -1,4 +1,5 @@
namespace Frida {
public extern void libc_shim_prepare_to_deinit ();
#if DARWIN
public extern void libc_shim_deinit ();
#endif
+30 -4
View File
@@ -302,6 +302,10 @@ if host_os == 'linux'
endif
cdata.set('HAVE_' + libc.to_upper(), 1)
vala_flags += '--define=' + libc.to_upper()
elif host_os == 'android'
libc = 'bionic'
else
libc = 'other'
endif
if get_option('b_sanitize') == 'address'
@@ -449,6 +453,7 @@ have_barebone_backend = get_option('barebone_backend') \
compiler_backend_opt = get_option('compiler_backend') \
.disable_auto_if(host_os == 'watchos')
have_compiler_backend = false
compiler_backend_mode = ''
if compiler_backend_opt.allowed()
go = find_program('go', native: true, required: false)
if go.found()
@@ -460,6 +465,8 @@ if compiler_backend_opt.allowed()
go,
host_os,
host_abi,
libc,
exe_suffix,
shlib_suffix,
cc.get_id(),
'>>>', cc.cmd_array(), '<<<',
@@ -475,11 +482,17 @@ if compiler_backend_opt.allowed()
if status == 'ok'
have_compiler_backend = true
tokens = lines[1].split(' ')
go_mode = tokens[0]
compiler_backend_mode = tokens[0]
go_config = tokens[1]
compiler_backend_static_compilation = go_mode == 'c-archive'
if compiler_backend_static_compilation
vala_flags += '--define=COMPILER_BACKEND_STATIC_COMPILATION'
if compiler_backend_mode == 'c-archive'
vala_flags += '--define=COMPILER_BACKEND_EMBEDDED'
elif compiler_backend_mode == 'c-shared'
vala_flags += '--define=COMPILER_BACKEND_SHARED'
elif compiler_backend_mode == 'pie'
vala_flags += '--define=COMPILER_BACKEND_EXECUTABLE'
else
error('Unsupported compiler backend mode: ' + compiler_backend_mode)
endif
else
error_message = lines[1]
@@ -753,6 +766,19 @@ post_process = [
'@INPUT0@',
]
executable_no_exports_link_args = []
executable_no_exports_link_depends = []
if host_os_family == 'darwin'
script = meson.project_source_root() / 'tools' / 'executable-no-exports.symbols'
executable_no_exports_link_args = ['-Wl,-exported_symbols_list,' + script]
executable_no_exports_link_depends = [script]
elif host_os_family != 'windows'
script_name = (host_os == 'freebsd') ? 'executable-no-exports-freebsd.version' : 'executable-no-exports.version'
script = meson.project_source_root() / 'tools' / script_name
executable_no_exports_link_args = ['-Wl,--version-script,' + script]
executable_no_exports_link_depends = [script]
endif
compile_js_agent = files('tools' / 'compile-js-agent.py')
mapper_opt = get_option('mapper')
-1
View File
@@ -1 +0,0 @@
# No exported symbols.
-9
View File
@@ -1,9 +0,0 @@
{
global:
# FreeBSD needs these two:
__progname;
environ;
local:
*;
};
+2 -14
View File
@@ -2,18 +2,6 @@ portal_sources = [
'portal.vala',
]
extra_link_args = []
extra_link_depends = []
if host_os_family == 'darwin'
symlist = 'frida-portal.symbols'
extra_link_args += ['-Wl,-exported_symbols_list,' + meson.current_source_dir() / symlist]
extra_link_depends += [symlist]
elif host_os_family != 'windows'
symscript = 'frida-portal.version'
extra_link_args += ['-Wl,--version-script,' + meson.current_source_dir() / symscript]
extra_link_depends += [symscript]
endif
extra_deps = []
if tls_provider_dep.found()
extra_deps += tls_provider_dep
@@ -21,8 +9,8 @@ endif
raw_portal = executable('frida-portal-raw', portal_sources,
vala_args: [core_vala_args, tls_provider_vala_args, '--pkg=posix'],
link_args: extra_link_args,
link_depends: extra_link_depends,
link_args: executable_no_exports_link_args,
link_depends: executable_no_exports_link_depends,
dependencies: [core_dep] + extra_deps,
)
+1 -1
Submodule releng updated: 7ed66fe687...5595d31705.
+11
View File
@@ -0,0 +1,11 @@
{
global:
# FreeBSD needs these two:
__progname;
environ;
# Allow users to load the server as a shared library with dlopen() and call main() directly
main;
local:
*;
};
+2 -1
View File
@@ -1 +1,2 @@
# No exported symbols.
# Allow users to load the server as a shared library with dlopen() and call main() directly
_main
-3
View File
@@ -1,8 +1,5 @@
{
global:
# FreeBSD needs these two:
__progname;
environ;
# Allow users to load the server as a shared library with dlopen() and call main() directly
main;
+1 -1
View File
@@ -19,7 +19,7 @@ if host_os_family == 'darwin'
extra_link_args += ['-Wl,-exported_symbols_list,' + meson.current_source_dir() / symlist]
extra_link_depends += [symlist]
elif host_os_family != 'windows'
symscript = 'frida-server.version'
symscript = (host_os == 'freebsd') ? 'frida-server-freebsd.version' : 'frida-server.version'
extra_link_args += ['-Wl,--version-script,' + meson.current_source_dir() / symscript]
extra_link_depends += [symscript]
endif
+1 -1
View File
@@ -11,7 +11,7 @@ helper.dex: build/frida-helper.jar
$<
mv build/classes.dex $@
build/frida-helper.jar: re/frida/Helper.java
build/frida-helper.jar: re/frida/Helper.java re/frida/HelperBackend.java
javac \
-cp .:$(android_jar) \
-bootclasspath $(android_jar) \
+87 -71
View File
@@ -1,66 +1,12 @@
namespace Frida {
public sealed class AndroidHelperClient : Object, AsyncInitable {
public signal void closed ();
public IOStream stream {
public sealed class AndroidHelperClient : Object {
public AndroidHelperTransport transport {
get;
construct;
}
private BufferedInputStream input;
private OutputStream output;
private Cancellable io_cancellable = new Cancellable ();
private State state = CLOSED;
private Gee.Queue<Request> pending_requests = new Gee.ArrayQueue<Request> ();
private ByteArray pending_output = new ByteArray ();
private bool writing = false;
private enum State {
CLOSED,
OPEN
}
private const uint32 MAX_RESPONSE_SIZE = 100 * 1024 * 1024;
public AndroidHelperClient (IOStream stream) {
Object (stream: stream);
}
construct {
input = (BufferedInputStream) Object.new (typeof (BufferedInputStream),
"base-stream", stream.get_input_stream (),
"close-base-stream", false,
"buffer-size", 128 * 1024);
output = stream.get_output_stream ();
state = OPEN;
process_incoming_responses.begin ();
}
public async void close (Cancellable? cancellable) throws IOError {
io_cancellable.cancel ();
var source = new IdleSource ();
source.set_callback (close.callback);
source.attach (MainContext.get_thread_default ());
yield;
try {
yield stream.close_async (Priority.DEFAULT, cancellable);
} catch (IOError e) {
}
ensure_closed ();
}
private void ensure_closed () {
if (state == CLOSED)
return;
state = CLOSED;
closed ();
public AndroidHelperClient (AndroidHelperTransport transport) {
Object (transport: transport);
}
public async HostApplicationInfo get_frontmost_application (FrontmostQueryOptions options,
@@ -72,7 +18,7 @@ namespace Frida {
.add_string_value (options.scope.to_nick ())
.end_array ();
Json.Node response = yield request (stanza.get_root (), cancellable);
Json.Node response = yield transport.request (stanza.get_root (), cancellable);
if (response.is_null ())
return HostApplicationInfo.empty ();
@@ -127,7 +73,7 @@ namespace Frida {
.add_string_value (options.scope.to_nick ())
.end_array ();
Json.Node response = yield request (stanza.get_root (), cancellable);
Json.Node response = yield transport.request (stanza.get_root (), cancellable);
Json.Reader reader = new Json.Reader (response);
@@ -193,7 +139,7 @@ namespace Frida {
.add_string_value (options.scope.to_nick ())
.end_array ();
Json.Node response = yield request (stanza.get_root (), cancellable);
Json.Node response = yield transport.request (stanza.get_root (), cancellable);
Json.Reader reader = new Json.Reader (response);
@@ -247,7 +193,7 @@ namespace Frida {
.add_int_value (uid)
.end_array ();
Json.Node response = yield request (stanza.get_root (), cancellable);
Json.Node response = yield transport.request (stanza.get_root (), cancellable);
var r = new Json.Reader (response);
parse_envelope_or_throw (r);
@@ -317,7 +263,7 @@ namespace Frida {
.add_int_value (uid)
.end_array ();
Json.Node response = yield request (stanza.get_root (), cancellable);
Json.Node response = yield transport.request (stanza.get_root (), cancellable);
var r = new Json.Reader (response);
parse_envelope_or_throw (r);
@@ -331,7 +277,7 @@ namespace Frida {
.add_int_value ((int) pid)
.end_array ();
Json.Node response = yield request (stanza.get_root (), cancellable);
Json.Node response = yield transport.request (stanza.get_root (), cancellable);
var r = new Json.Reader (response);
parse_envelope_or_throw (r);
@@ -343,6 +289,13 @@ namespace Frida {
return r.get_boolean_value ();
}
private async void request_ok (Json.Builder stanza, Cancellable? cancellable) throws Error, IOError {
Json.Node response = yield transport.request (stanza.get_root (), cancellable);
var r = new Json.Reader (response);
parse_envelope_or_throw (r);
}
private void parse_envelope_or_throw (Json.Reader r) throws Error {
r.read_element (0);
string? kind = r.get_string_value ();
@@ -452,6 +405,76 @@ namespace Frida {
throw new Error.PROTOCOL ("Unexpected JSON type: %s", type.name ());
}
}
public interface AndroidHelperTransport : Object {
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;
}
private BufferedInputStream input;
private OutputStream output;
private Cancellable io_cancellable = new Cancellable ();
private State state = CLOSED;
private Gee.Queue<Request> pending_requests = new Gee.ArrayQueue<Request> ();
private ByteArray pending_output = new ByteArray ();
private bool writing = false;
private enum State {
CLOSED,
OPEN
}
private const uint32 MAX_RESPONSE_SIZE = 100 * 1024 * 1024;
public AndroidHelperStreamTransport (IOStream stream) {
Object (stream: stream);
}
construct {
input = (BufferedInputStream) Object.new (typeof (BufferedInputStream),
"base-stream", stream.get_input_stream (),
"close-base-stream", false,
"buffer-size", 128 * 1024);
output = stream.get_output_stream ();
state = OPEN;
process_incoming_responses.begin ();
}
public async void close (Cancellable? cancellable) throws IOError {
io_cancellable.cancel ();
var source = new IdleSource ();
source.set_callback (close.callback);
source.attach (MainContext.get_thread_default ());
yield;
try {
yield stream.close_async (Priority.DEFAULT, cancellable);
} catch (IOError e) {
}
ensure_closed ();
}
private void ensure_closed () {
if (state == CLOSED)
return;
state = CLOSED;
closed ();
}
public async Json.Node request (Json.Node stanza, Cancellable? cancellable) throws Error, IOError {
if (state == CLOSED)
@@ -487,13 +510,6 @@ namespace Frida {
return r.response;
}
private async void request_ok (Json.Builder stanza, Cancellable? cancellable) throws Error, IOError {
Json.Node response = yield request (stanza.get_root (), cancellable);
var r = new Json.Reader (response);
parse_envelope_or_throw (r);
}
private void write_request (Json.Node request) {
string request_str = Json.to_string (request, false);
uint8[] request_data = request_str.data;
Binary file not shown.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2
View File
@@ -519,6 +519,8 @@ def function_is_public(name):
"check_kernel_version",
"get_syscall_signatures",
"get_compat32_syscall_signatures",
"get_xnu_mach_traps",
"get_xnu_bsd_syscalls",
"make_stdio_pipes",
"make_stdio_pipe",
}
-271
View File
@@ -1,98 +1,11 @@
package main
/*
#include <stdint.h>
typedef enum {
FRIDA_OUTPUT_UNESCAPED,
FRIDA_OUTPUT_HEX_BYTES,
FRIDA_OUTPUT_C_STRING,
} FridaOutputFormat;
typedef enum {
FRIDA_BUNDLE_ESM,
FRIDA_BUNDLE_IIFE,
} FridaBundleFormat;
typedef void (* FridaBuildCompleteFunc) (char * bundle, char * error_message, void * user_data);
typedef void (* FridaWatchReadyFunc) (uintptr_t session_handle, char * error_message, void * user_data);
typedef void (* FridaStartingFunc) (void * user_data);
typedef void (* FridaFinishedFunc) (void * user_data);
typedef void (* FridaOutputFunc) (char * bundle, void * user_data);
typedef void (* FridaDiagnosticFunc) (char * category, int code, char * path, int line, int character, char * text,
void * user_data);
typedef void (* FridaDestroyFunc) (void * user_data);
static inline void
invoke_build_complete_func (FridaBuildCompleteFunc fn,
char * bundle,
char * error_message,
void * user_data)
{
fn (bundle, error_message, user_data);
}
static inline void
invoke_watch_ready_func (FridaWatchReadyFunc fn,
uintptr_t session_handle,
char * error_message,
void * user_data)
{
fn (session_handle, error_message, user_data);
}
static inline void
invoke_starting_func (FridaStartingFunc fn,
void * user_data)
{
fn (user_data);
}
static inline void
invoke_finished_func (FridaFinishedFunc fn,
void * user_data)
{
fn (user_data);
}
static inline void
invoke_output_func (FridaOutputFunc fn,
char * bundle,
void * user_data)
{
fn (bundle, user_data);
}
static inline void
invoke_diagnostic_func (FridaDiagnosticFunc fn,
char * category,
int code,
char * path,
int line,
int character,
char * text,
void * user_data)
{
fn (category, code, path, line, character, text, user_data);
}
static inline void
invoke_destroy_func (FridaDestroyFunc fn,
void * user_data)
{
fn (user_data);
}
*/
import "C"
import (
"fmt"
"path"
"path/filepath"
"runtime/cgo"
"strings"
"sync"
"unsafe"
esbuild "github.com/evanw/esbuild/pkg/api"
tsscanner "github.com/frida/typescript-go/pkg/scanner"
@@ -110,21 +23,6 @@ type BuildOptions struct {
Externals []string
}
type OutputFormat C.FridaOutputFormat
const (
OutputFormatUnescaped OutputFormat = OutputFormat(C.FRIDA_OUTPUT_UNESCAPED)
OutputFormatHexBytes OutputFormat = OutputFormat(C.FRIDA_OUTPUT_HEX_BYTES)
OutputFormatCString OutputFormat = OutputFormat(C.FRIDA_OUTPUT_C_STRING)
)
type BundleFormat C.FridaBundleFormat
const (
BundleFormatESM BundleFormat = BundleFormat(C.FRIDA_BUNDLE_ESM)
BundleFormatIIFE BundleFormat = BundleFormat(C.FRIDA_BUNDLE_IIFE)
)
type Diagnostic struct {
category string
code int
@@ -146,153 +44,6 @@ type BuildEndCallback func()
type BuildOutputCallback func(bundle string)
type BuildDiagnosticCallback func(d Diagnostic)
//export _frida_compiler_backend_build
func _frida_compiler_backend_build(cProjectRoot, cEntrypoint *C.char, outputFormat C.FridaOutputFormat, bundleFormat C.FridaBundleFormat,
disableTypeCheck, sourceMap, compress uintptr, cPlatform *C.char, cExternals **C.char, numExternals C.int,
onCompleteFn C.FridaBuildCompleteFunc, onCompleteData unsafe.Pointer, onCompleteDataDestroy C.FridaDestroyFunc,
onDiagnosticFn C.FridaDiagnosticFunc, onDiagnosticData unsafe.Pointer) {
options := BuildOptions{
ProjectRoot: C.GoString(cProjectRoot),
Entrypoint: C.GoString(cEntrypoint),
OutputFormat: OutputFormat(outputFormat),
BundleFormat: BundleFormat(bundleFormat),
DisableTypeCheck: disableTypeCheck != 0,
SourceMap: sourceMap != 0,
Compress: compress != 0,
Platform: platformFromFrida(C.GoString(cPlatform)),
Externals: parseCExternals(cExternals, numExternals),
}
onComplete := NewCDelegate(onCompleteFn, onCompleteData, onCompleteDataDestroy)
onDiagnostic := NewCDelegate(onDiagnosticFn, onDiagnosticData, nil)
go func() {
defer onComplete.Dispose()
defer onDiagnostic.Dispose()
onDiagnostic := makeCBuildDiagnosticCallback(onDiagnostic)
bundle, err := build(options, onDiagnostic)
var cBundle, cErrorMessage *C.char
if err == nil {
cBundle = C.CString(bundle)
} else {
cErrorMessage = C.CString(err.Error())
}
C.invoke_build_complete_func(onComplete.Func, cBundle, cErrorMessage, onComplete.Data)
}()
}
//export _frida_compiler_backend_watch
func _frida_compiler_backend_watch(cProjectRoot, cEntrypoint *C.char, outputFormat C.FridaOutputFormat, bundleFormat C.FridaBundleFormat,
disableTypeCheck, sourceMap, compress uintptr, cPlatform *C.char, cExternals **C.char, numExternals C.int,
onReadyFn C.FridaWatchReadyFunc, onReadyData unsafe.Pointer, onReadyDataDestroy C.FridaDestroyFunc,
onStartingFn C.FridaStartingFunc, onStartingData unsafe.Pointer,
onFinishedFn C.FridaFinishedFunc, onFinishedData unsafe.Pointer,
onOutputFn C.FridaOutputFunc, onOutputData unsafe.Pointer,
onDiagnosticFn C.FridaDiagnosticFunc, onDiagnosticData unsafe.Pointer) {
options := BuildOptions{
ProjectRoot: C.GoString(cProjectRoot),
Entrypoint: C.GoString(cEntrypoint),
OutputFormat: OutputFormat(outputFormat),
BundleFormat: BundleFormat(bundleFormat),
DisableTypeCheck: disableTypeCheck != 0,
SourceMap: sourceMap != 0,
Compress: compress != 0,
Platform: platformFromFrida(C.GoString(cPlatform)),
Externals: parseCExternals(cExternals, numExternals),
}
onReady := NewCDelegate(onReadyFn, onReadyData, onReadyDataDestroy)
onStarting := NewCDelegate(onStartingFn, onStartingData, nil)
onFinished := NewCDelegate(onFinishedFn, onFinishedData, nil)
onOutput := NewCDelegate(onOutputFn, onOutputData, nil)
onDiagnostic := NewCDelegate(onDiagnosticFn, onDiagnosticData, nil)
go func() {
defer onReady.Dispose()
onDispose := func() {
onStarting.Dispose()
onFinished.Dispose()
onOutput.Dispose()
onDiagnostic.Dispose()
}
callbacks := BuildEventCallbacks{
OnStart: func() {
C.invoke_starting_func(onStarting.Func, onStarting.Data)
},
OnEnd: func() {
C.invoke_starting_func(onFinished.Func, onFinished.Data)
},
OnOutput: func(bundle string) {
C.invoke_output_func(onOutput.Func, C.CString(bundle), onOutput.Data)
},
OnDiagnostic: makeCBuildDiagnosticCallback(onDiagnostic),
}
session, err := NewWatchSession(options, onDispose, callbacks)
var cSession C.uintptr_t
var cErrorMessage *C.char
if err == nil {
cSession = C.uintptr_t(cgo.NewHandle(session))
} else {
cErrorMessage = C.CString(err.Error())
}
C.invoke_watch_ready_func(onReady.Func, cSession, cErrorMessage, onReady.Data)
}()
}
//export _frida_compiler_backend_watch_session_dispose
func _frida_compiler_backend_watch_session_dispose(h uintptr) {
handle := cgo.Handle(h)
session := handle.Value().(*WatchSession)
session.Dispose()
handle.Delete()
}
func platformFromFrida(s string) esbuild.Platform {
switch s {
case "gum":
return esbuild.PlatformNode
case "browser":
return esbuild.PlatformBrowser
case "neutral":
return esbuild.PlatformNeutral
default:
panic(fmt.Sprintf("Unknown platform: %q", s))
}
}
func parseCExternals(cExternals **C.char, numExternals C.int) []string {
if numExternals == 0 {
return nil
}
n := int(numExternals)
cArray := (*[1 << 20]*C.char)(unsafe.Pointer(cExternals))[:n:n]
externals := make([]string, n)
for i := 0; i < n; i++ {
externals[i] = C.GoString(cArray[i])
}
return externals
}
func makeCBuildDiagnosticCallback(onDiagnostic *CDelegate[C.FridaDiagnosticFunc]) BuildDiagnosticCallback {
return func(d Diagnostic) {
var cPath *C.char
if d.path != "" {
cPath = C.CString(d.path)
}
C.invoke_diagnostic_func(onDiagnostic.Func, C.CString(d.category), C.int(d.code), cPath, C.int(d.line),
C.int(d.character), C.CString(d.text), onDiagnostic.Data)
}
}
func build(options BuildOptions, onDiagnostic BuildDiagnosticCallback) (bundle string, err error) {
callbacks := BuildEventCallbacks{
OnOutput: func(b string) {
@@ -828,25 +579,3 @@ func makeTypeScriptPlugin(compiler *TSCompiler) esbuild.Plugin {
},
}
}
type CDelegate[F any] struct {
Func F
null F
Data unsafe.Pointer
dataDestroy C.FridaDestroyFunc
}
func NewCDelegate[F any](function F, data unsafe.Pointer, dataDestroy C.FridaDestroyFunc) *CDelegate[F] {
return &CDelegate[F]{Func: function, Data: data, dataDestroy: dataDestroy}
}
func (d *CDelegate[F]) Dispose() {
if d.dataDestroy != nil {
C.invoke_destroy_func(d.dataDestroy, d.Data)
}
d.Func = d.null
d.Data = nil
d.dataDestroy = nil
}
func main() {}
+15 -12
View File
@@ -60,11 +60,15 @@ def build_backend(
mode = config["mode"]
backend_stem = "frida-compiler-backend"
if mode == "c-shared":
if mode != "c-archive":
backend_stem += "-raw"
backend_a = priv_dir / f"{backend_stem}.a"
backend_shlib = priv_dir / (f"{backend_stem}" + config["shlib_suffix"])
if mode == "c-archive":
backend_binary = priv_dir / f"{backend_stem}.a"
elif mode == "c-shared":
backend_binary = priv_dir / (f"{backend_stem}" + config["shlib_suffix"])
else:
backend_binary = priv_dir / (f"{backend_stem}" + config["exe_suffix"])
backend_h = priv_dir / f"{backend_stem}.h"
extra_go_args = config["extra_go_args"].copy()
@@ -78,10 +82,10 @@ def build_backend(
"build",
f"-buildmode={mode}",
"-o",
backend_a.name if mode == "c-archive" else backend_shlib.name,
backend_binary.name,
"-buildvcs=false",
*extra_go_args,
*go_sources,
".",
)
if mode == "c-archive":
@@ -109,7 +113,7 @@ def build_backend(
)
run(priv_dir / "symbol-replacer" / symbol_replacer_name,
backend_a.name, *config["nm"], *config["ranlib"], config["env"]["CC"])
backend_binary.name, *config["nm"], *config["ranlib"], config["env"]["CC"])
if (mingw := config.get("mingw")) is not None and (abi := config["abi"]) in {
"x86",
@@ -143,17 +147,16 @@ def build_backend(
extra_objects = []
if abi == "x86_64":
run(*ar, "x", backend_a.name, "go.o")
run(*ar, "x", backend_binary.name, "go.o")
sort_pdata_in_object(Path(priv_dir) / "go.o")
extra_objects.append("go.o")
run(*ar, "rs", backend_a.name, *libgcc_objects, *gwex_objects, *extra_objects)
run(*ar, "rs", backend_binary.name, *libgcc_objects, *gwex_objects, *extra_objects)
shutil.copy(priv_dir / backend_a.name, output_dir / backend_a.name)
else:
shutil.copy(priv_dir / backend_shlib.name, output_dir / backend_shlib.name)
shutil.copy(priv_dir / backend_binary.name, output_dir / backend_binary.name)
shutil.copy(priv_dir / backend_h.name, output_dir / backend_h.name)
if mode in {"c-archive", "c-shared"}:
shutil.copy(priv_dir / backend_h.name, output_dir / backend_h.name)
# Work around the Go toolchain's almost-MSVC-compatible object files
+618 -13
View File
@@ -47,7 +47,7 @@ namespace Frida {
CompilerBackend.build (project_root, entrypoint, opts.output_format, opts.bundle_format,
(size_t) (opts.type_check == NONE), (size_t) (opts.source_maps == INCLUDED),
(size_t) (opts.compression == TERSER), opts.platform.to_nick (),
opts.externals.to_array (), (owned) on_complete, on_diagnostic);
opts.externals.to_array (), on_diagnostic, (owned) on_complete);
yield;
if (error_message != null)
@@ -98,8 +98,8 @@ namespace Frida {
CompilerBackend.watch (project_root, entrypoint, opts.output_format, opts.bundle_format,
(size_t) (opts.type_check == NONE), (size_t) (opts.source_maps == INCLUDED),
(size_t) (opts.compression == TERSER), opts.platform.to_nick (),
opts.externals.to_array (), (owned) on_ready, on_starting, on_finished,
on_output, on_diagnostic);
opts.externals.to_array (), on_starting, on_finished, on_output, on_diagnostic,
(owned) on_ready);
yield;
if (error_message != null)
@@ -235,12 +235,12 @@ namespace Frida {
namespace CompilerBackend {
private void init () {
#if HAVE_COMPILER_BACKEND
#if COMPILER_BACKEND_STATIC_COMPILATION
#if COMPILER_BACKEND_EMBEDDED
_init_go_runtime ();
build = (BuildFunc) _build;
watch = (WatchFunc) _watch;
WatchSession.dispose = (WatchSession.DisposeFunc) WatchSession._dispose;
#else
#elif COMPILER_BACKEND_SHARED
unowned uint8[] backend_so = Frida.Data.Compiler.get_frida_compiler_backend_so_blob ().data;
Module? backend = null;
@@ -276,6 +276,12 @@ namespace Frida {
build = resolve_symbol (backend, "_frida_compiler_backend_build");
watch = resolve_symbol (backend, "_frida_compiler_backend_watch");
WatchSession.dispose = resolve_symbol (backend, "_frida_compiler_backend_watch_session_dispose");
#elif COMPILER_BACKEND_EXECUTABLE
backend_process = new BackendProcess ();
build = executable_build;
watch = executable_watch;
WatchSession.dispose = executable_watch_session_dispose;
#endif
#endif
}
@@ -291,16 +297,15 @@ namespace Frida {
[CCode (has_target = false)]
private delegate void BuildFunc (string project_root, string entrypoint, OutputFormat output_format,
BundleFormat bundle_format, size_t disable_type_check, size_t source_map, size_t compress,
string platform, string[] externals, owned BuildCompleteFunc on_complete,
DiagnosticFunc on_diagnostic);
string platform, string[] externals, DiagnosticFunc on_diagnostic, owned BuildCompleteFunc on_complete);
[CCode (has_target = false)]
private delegate void WatchFunc (string project_root, string entrypoint, OutputFormat output_format,
BundleFormat bundle_format, size_t disable_type_check, size_t source_map, size_t compress,
string platform, string[] externals, owned WatchReadyFunc on_ready, StartingFunc on_starting,
FinishedFunc on_finished, OutputFunc on_output, DiagnosticFunc on_diagnostic);
string platform, string[] externals, StartingFunc on_starting, FinishedFunc on_finished,
OutputFunc on_output, DiagnosticFunc on_diagnostic, owned WatchReadyFunc on_ready);
#if COMPILER_BACKEND_STATIC_COMPILATION
#if COMPILER_BACKEND_EMBEDDED
private extern void _init_go_runtime ();
private extern void _build ();
private extern void _watch ();
@@ -312,7 +317,7 @@ namespace Frida {
private DisposeFunc? dispose;
#if COMPILER_BACKEND_STATIC_COMPILATION
#if COMPILER_BACKEND_EMBEDDED
private extern void _dispose ();
#endif
}
@@ -325,14 +330,614 @@ namespace Frida {
private delegate void DiagnosticFunc (owned string category, int code, owned string? path, int line, int character,
owned string text);
#if HAVE_COMPILER_BACKEND && !COMPILER_BACKEND_STATIC_COMPILATION
private static T resolve_symbol<T> (Module m, string name) {
#if HAVE_COMPILER_BACKEND && COMPILER_BACKEND_SHARED
private T resolve_symbol<T> (Module m, string name) {
void * address;
if (!m.symbol (name, out address))
assert_not_reached ();
return (T) address;
}
#endif
#if COMPILER_BACKEND_EXECUTABLE
private BackendProcess? backend_process;
private static void executable_build (string project_root, string entrypoint, OutputFormat output_format,
BundleFormat bundle_format, size_t disable_type_check, size_t source_map, size_t compress,
string platform, string[] externals, DiagnosticFunc on_diagnostic, owned BuildCompleteFunc on_complete) {
backend_process.build (project_root, entrypoint, output_format, bundle_format, disable_type_check, source_map,
compress, platform, externals, on_diagnostic, (owned) on_complete);
}
private static void executable_watch (string project_root, string entrypoint, OutputFormat output_format,
BundleFormat bundle_format, size_t disable_type_check, size_t source_map, size_t compress,
string platform, string[] externals, StartingFunc on_starting, FinishedFunc on_finished,
OutputFunc on_output, DiagnosticFunc on_diagnostic, owned WatchReadyFunc on_ready) {
backend_process.watch (project_root, entrypoint, output_format, bundle_format, disable_type_check, source_map,
compress, platform, externals, on_starting, on_finished, on_output, on_diagnostic, (owned) on_ready);
}
private static void executable_watch_session_dispose (size_t handle) {
backend_process.dispose_watch_session (handle);
}
private class BackendProcess : Object {
private Subprocess? process;
private BufferedInputStream? input;
private OutputStream? output;
private DataInputStream? errput;
private ByteArray pending_output = new ByteArray ();
private bool writing = false;
private uint next_request_id = 1;
private uint next_session_id = 1;
private Gee.Map<uint, PendingBuild> pending_builds = new Gee.HashMap<uint, PendingBuild> ();
private Gee.Map<uint, WatchEntry> watches = new Gee.HashMap<uint, WatchEntry> ();
private Cancellable io_cancellable = new Cancellable ();
construct {
try_start ();
}
private void try_start () {
try {
ensure_started ();
} catch (GLib.Error e) {
}
}
private void ensure_started () throws GLib.Error {
if (process != null)
return;
string path = extract_backend_executable ();
try {
var p = new Subprocess (STDIN_PIPE | STDOUT_PIPE | STDERR_PIPE, path);
process = p;
input = (BufferedInputStream) Object.new (typeof (BufferedInputStream),
"base-stream", p.get_stdout_pipe (),
"close-base-stream", false,
"buffer-size", 128 * 1024);
output = p.get_stdin_pipe ();
errput = new DataInputStream (p.get_stderr_pipe ());
process_incoming_messages.begin ();
process_stderr_stream.begin (errput);
} finally {
FileUtils.unlink (path);
}
}
private static string extract_backend_executable () throws GLib.Error {
unowned uint8[] blob = Frida.Data.Compiler.get_frida_compiler_backend_blob ().data;
string path;
{
var fd = new FileDescriptor (FileUtils.open_tmp ("frida-compiler-backend-XXXXXX", out path));
fd.pwrite_all (blob, 0);
}
FileUtils.chmod (path, 0700);
return path;
}
private void handle_process_failure (string message) {
io_cancellable.cancel ();
io_cancellable = new Cancellable ();
if (process != null) {
if (!process.get_if_exited ())
process.force_exit ();
}
process = null;
input = null;
output = null;
errput = null;
foreach (var e in pending_builds.entries)
e.value.on_complete (null, message);
pending_builds.clear ();
foreach (var e in watches.entries) {
var entry = e.value;
if (entry.on_ready != null)
entry.on_ready (0, message);
}
watches.clear ();
pending_output = new ByteArray ();
writing = false;
}
public void build (string project_root, string entrypoint, OutputFormat output_format, BundleFormat bundle_format,
size_t disable_type_check, size_t source_map, size_t compress, string platform, string[] externals,
DiagnosticFunc on_diagnostic, owned BuildCompleteFunc on_complete) {
try {
ensure_started ();
} catch (GLib.Error e) {
on_complete (null, e.message);
return;
}
uint request_id = allocate_request_id ();
pending_builds[request_id] = new PendingBuild ((owned) on_complete, on_diagnostic);
post_message (make_build_request (
request_id,
project_root,
entrypoint,
output_format,
bundle_format,
disable_type_check != 0,
source_map != 0,
compress != 0,
platform,
externals
));
}
private class PendingBuild {
public BuildCompleteFunc on_complete;
public unowned DiagnosticFunc on_diagnostic;
public PendingBuild (owned BuildCompleteFunc on_complete, DiagnosticFunc on_diagnostic) {
this.on_complete = (owned) on_complete;
this.on_diagnostic = on_diagnostic;
}
}
public void watch (string project_root, string entrypoint, OutputFormat output_format, BundleFormat bundle_format,
size_t disable_type_check, size_t source_map, size_t compress, string platform, string[] externals,
StartingFunc on_starting, FinishedFunc on_finished, OutputFunc on_output,
DiagnosticFunc on_diagnostic, owned WatchReadyFunc on_ready) {
try {
ensure_started ();
} catch (GLib.Error e) {
on_ready (0, e.message);
return;
}
uint session_id = allocate_session_id ();
watches[session_id] = new WatchEntry ((owned) on_ready, on_starting, on_finished, on_output, on_diagnostic);
post_message (make_watch_request (
session_id,
project_root,
entrypoint,
output_format,
bundle_format,
disable_type_check != 0,
source_map != 0,
compress != 0,
platform,
externals
));
}
private class WatchEntry {
public WatchReadyFunc? on_ready;
public unowned StartingFunc on_starting;
public unowned FinishedFunc on_finished;
public unowned OutputFunc on_output;
public unowned DiagnosticFunc on_diagnostic;
public WatchEntry (owned WatchReadyFunc on_ready, StartingFunc on_starting, FinishedFunc on_finished,
OutputFunc on_output, DiagnosticFunc on_diagnostic) {
this.on_ready = (owned) on_ready;
this.on_starting = on_starting;
this.on_finished = on_finished;
this.on_output = on_output;
this.on_diagnostic = on_diagnostic;
}
}
public void dispose_watch_session (size_t handle) {
uint session_id = (uint) handle;
WatchEntry entry;
if (!watches.unset (session_id, out entry))
return;
if (process != null)
post_message (make_dispose_request (session_id));
}
private static string make_build_request (uint id, string project_root, string entrypoint,
OutputFormat output_format, BundleFormat bundle_format, bool disable_type_check,
bool source_map, bool compress, string platform, string[] externals) {
return make_request ("build", "id", id, project_root, entrypoint, output_format, bundle_format,
disable_type_check, source_map, compress, platform, externals);
}
private static string make_watch_request (uint session_id, string project_root, string entrypoint,
OutputFormat output_format, BundleFormat bundle_format, bool disable_type_check,
bool source_map, bool compress, string platform, string[] externals) {
return make_request ("watch", "session_id", session_id, project_root, entrypoint, output_format,
bundle_format, disable_type_check, source_map, compress, platform, externals);
}
private static string make_request (string type, string id_name, uint id, string project_root, string entrypoint,
OutputFormat output_format, BundleFormat bundle_format, bool disable_type_check,
bool source_map, bool compress, string platform, string[] externals) {
var builder = new Json.Builder ();
builder
.begin_object ()
.set_member_name ("type")
.add_string_value (type)
.set_member_name (id_name)
.add_int_value (id)
.set_member_name ("project_root")
.add_string_value (project_root)
.set_member_name ("entrypoint")
.add_string_value (entrypoint)
.set_member_name ("output_format")
.add_string_value (output_format.to_nick ())
.set_member_name ("bundle_format")
.add_string_value (bundle_format.to_nick ())
.set_member_name ("disable_type_check")
.add_boolean_value (disable_type_check)
.set_member_name ("source_map")
.add_boolean_value (source_map)
.set_member_name ("compress")
.add_boolean_value (compress)
.set_member_name ("platform")
.add_string_value (platform)
.set_member_name ("externals")
.begin_array ();
foreach (unowned string e in externals)
builder.add_string_value (e);
builder
.end_array ()
.end_object ();
return Json.to_string (builder.get_root (), false);
}
private static string make_dispose_request (uint session_id) {
var builder = new Json.Builder ();
builder
.begin_object ()
.set_member_name ("type")
.add_string_value ("dispose")
.set_member_name ("session_id")
.add_int_value (session_id)
.end_object ();
return Json.to_string (builder.get_root (), false);
}
private uint allocate_request_id () {
uint start = next_request_id;
do {
uint id = next_request_id++;
if (next_request_id == 0)
next_request_id = 1;
if (!pending_builds.has_key (id))
return id;
} while (next_request_id != start);
assert_not_reached ();
}
private uint allocate_session_id () {
uint start = next_session_id;
do {
uint id = next_session_id++;
if (next_session_id == 0)
next_session_id = 1;
if (!watches.has_key (id))
return id;
} while (next_session_id != start);
assert_not_reached ();
}
private void post_message (string json) {
unowned uint8[] raw_json = json.data;
uint32 size = ((uint32) raw_json.length).to_big_endian ();
pending_output.append ((uint8[]) &size);
pending_output.append (raw_json);
if (!writing) {
writing = true;
var source = new IdleSource ();
source.set_callback (() => {
process_pending_output.begin ();
return false;
});
source.attach (MainContext.get_thread_default ());
}
}
private async void process_pending_output () {
while (pending_output.len > 0) {
uint8[] batch = pending_output.steal ();
size_t bytes_written;
try {
yield output.write_all_async (batch, Priority.DEFAULT, io_cancellable, out bytes_written);
} catch (GLib.Error e) {
handle_process_failure ("Compiler backend process terminated unexpectedly");
return;
}
}
writing = false;
}
private async void process_incoming_messages () {
try {
while (true) {
size_t header_size = 4;
if (input.get_available () < header_size)
yield fill_until_n_bytes_available (header_size);
uint32 body_size = 0;
unowned uint8[] size_buf = ((uint8[]) &body_size)[:4];
input.peek (size_buf);
body_size = uint32.from_big_endian (body_size);
size_t full_size = header_size + body_size;
if (input.get_available () < full_size)
yield fill_until_n_bytes_available (full_size);
var raw_json = new uint8[body_size + 1];
input.peek (raw_json[:body_size], header_size);
unowned string json = (string) raw_json;
handle_message (json);
input.skip (full_size, io_cancellable);
}
} catch (GLib.Error e) {
handle_process_failure (e.message);
}
}
private void handle_message (string json) throws Error {
Json.Node root;
try {
root = Json.from_string (json);
} catch (GLib.Error e) {
throw new Error.PROTOCOL ("%s", e.message);
}
var reader = new Json.Reader (root);
reader.read_member ("type");
unowned string? type = reader.get_string_value ();
if (type == null)
throw new Error.PROTOCOL ("Missing or invalid 'type' value");
reader.end_member ();
var tokens = type.split (":", 2);
if (tokens.length != 2)
throw new Error.PROTOCOL ("Invalid 'type' value");
unowned string scope = tokens[0];
unowned string subtype = tokens[1];
if (scope == "build")
handle_build_message (subtype, reader);
else if (scope == "watch")
handle_watch_message (subtype, reader);
else
throw new Error.PROTOCOL ("Unknown 'type' scope");
}
private void handle_build_message (string type, Json.Reader reader) throws Error {
if (type == "complete")
handle_build_complete_message (reader);
else if (type == "diagnostic")
handle_build_diagnostic_message (reader);
else
throw new Error.PROTOCOL ("Unknown build message type: %s", type);
}
private void handle_watch_message (string type, Json.Reader reader) throws Error {
if (type == "ready")
handle_watch_ready_message (reader);
else if (type == "starting" || type == "finished" || type == "output" || type == "diagnostic")
handle_watch_event_message (reader, type);
else
throw new Error.PROTOCOL ("Unknown watch message type: %s", type);
}
private void handle_build_complete_message (Json.Reader reader) throws Error {
reader.read_member ("id");
uint id = (uint) reader.get_int_value ();
reader.end_member ();
PendingBuild pending;
if (!pending_builds.unset (id, out pending))
throw new Error.PROTOCOL ("Invalid pending build ID: %u", id);
if (reader.read_member ("error")) {
unowned string? error = reader.get_string_value ();
if (error == null)
throw new Error.PROTOCOL ("Missing or invalid 'error' value");
reader.end_member ();
pending.on_complete (null, error);
return;
}
reader.end_member ();
reader.read_member ("bundle");
unowned string? bundle = reader.get_string_value ();
if (bundle == null)
throw new Error.PROTOCOL ("Missing or invalid 'bundle' value");
reader.end_member ();
pending.on_complete (bundle, null);
}
private void handle_build_diagnostic_message (Json.Reader reader) throws Error {
reader.read_member ("id");
uint id = (uint) reader.get_int_value ();
reader.end_member ();
var pending = pending_builds[id];
if (pending == null)
throw new Error.PROTOCOL ("Invalid pending build ID: %u", id);
emit_diagnostic_from_json (reader, pending.on_diagnostic);
}
private void handle_watch_ready_message (Json.Reader reader) throws Error {
reader.read_member ("session_id");
uint session_id = (uint) reader.get_int_value ();
reader.end_member ();
var watch = watches[session_id];
if (watch == null)
throw new Error.PROTOCOL ("Invalid watch session ID: %u", session_id);
if (reader.read_member ("error")) {
unowned string? error = reader.get_string_value ();
if (error == null)
throw new Error.PROTOCOL ("Missing or invalid 'error' value");
reader.end_member ();
watches.unset (session_id);
watch.on_ready (0, error);
return;
}
reader.end_member ();
var on_ready = (owned) watch.on_ready;
if (on_ready == null)
throw new Error.PROTOCOL ("Duplicate watch:ready for session ID: %u", session_id);
watch.on_ready = null;
on_ready (session_id, null);
}
private void handle_watch_event_message (Json.Reader reader, string type) throws Error {
reader.read_member ("session_id");
var session_id = (uint) reader.get_int_value ();
reader.end_member ();
var watch = watches[session_id];
if (watch == null)
throw new Error.PROTOCOL ("Invalid watch session ID: %u", session_id);
if (type == "starting") {
watch.on_starting ();
return;
}
if (type == "finished") {
watch.on_finished ();
return;
}
if (type == "output") {
reader.read_member ("bundle");
unowned string? bundle = reader.get_string_value ();
if (bundle == null)
throw new Error.PROTOCOL ("Missing or invalid 'bundle' value");
reader.end_member ();
watch.on_output (bundle);
return;
}
emit_diagnostic_from_json (reader, watch.on_diagnostic);
}
private static void emit_diagnostic_from_json (Json.Reader reader, DiagnosticFunc on_diagnostic) throws Error {
reader.read_member ("category");
unowned string? category = reader.get_string_value ();
if (category == null)
throw new Error.PROTOCOL ("Missing or invalid 'category' value");
reader.end_member ();
reader.read_member ("code");
int code = (int) reader.get_int_value ();
reader.end_member ();
string? path = null;
int line = 0;
int character = 0;
if (reader.read_member ("path")) {
path = reader.get_string_value ();
reader.end_member ();
reader.read_member ("line");
line = (int) reader.get_int_value ();
reader.end_member ();
reader.read_member ("character");
character = (int) reader.get_int_value ();
reader.end_member ();
} else {
reader.end_member ();
}
reader.read_member ("text");
unowned string? text = reader.get_string_value ();
if (text == null)
throw new Error.PROTOCOL ("Missing or invalid 'text' value");
reader.end_member ();
on_diagnostic (category, code, path, line, character, text);
}
private async void process_stderr_stream (DataInputStream stream) {
try {
while (true) {
string? line = yield stream.read_line_utf8_async (Priority.DEFAULT, io_cancellable);
if (line == null)
break;
printerr ("[frida-compiler-backend stderr] %s\n", line);
}
} catch (GLib.Error e) {
}
}
private async void fill_until_n_bytes_available (size_t minimum) throws Error, IOError {
size_t available = input.get_available ();
while (available < minimum) {
if (input.get_buffer_size () < minimum)
input.set_buffer_size (minimum);
ssize_t n;
try {
n = yield input.fill_async ((ssize_t) (input.get_buffer_size () - available),
Priority.DEFAULT, io_cancellable);
} catch (GLib.Error e) {
throw new Error.TRANSPORT ("Compiler backend process terminated unexpectedly");
}
if (n == 0)
throw new Error.TRANSPORT ("Compiler backend process terminated unexpectedly");
available += n;
}
}
}
#endif
}
private string compute_project_root (string entrypoint, CompilerOptions options) {
+249
View File
@@ -0,0 +1,249 @@
//go:build !frida_compiler_backend_executable
package main
/*
#include <stdint.h>
typedef enum {
FRIDA_OUTPUT_UNESCAPED,
FRIDA_OUTPUT_HEX_BYTES,
FRIDA_OUTPUT_C_STRING,
} FridaOutputFormat;
typedef enum {
FRIDA_BUNDLE_ESM,
FRIDA_BUNDLE_IIFE,
} FridaBundleFormat;
typedef void (* FridaBuildCompleteFunc) (char * bundle, char * error_message, void * user_data);
typedef void (* FridaWatchReadyFunc) (uintptr_t session_handle, char * error_message, void * user_data);
typedef void (* FridaStartingFunc) (void * user_data);
typedef void (* FridaFinishedFunc) (void * user_data);
typedef void (* FridaOutputFunc) (char * bundle, void * user_data);
typedef void (* FridaDiagnosticFunc) (char * category, int code, char * path, int line, int character, char * text,
void * user_data);
typedef void (* FridaDestroyFunc) (void * user_data);
static inline void
invoke_build_complete_func (FridaBuildCompleteFunc fn,
char * bundle,
char * error_message,
void * user_data)
{
fn (bundle, error_message, user_data);
}
static inline void
invoke_watch_ready_func (FridaWatchReadyFunc fn,
uintptr_t session_handle,
char * error_message,
void * user_data)
{
fn (session_handle, error_message, user_data);
}
static inline void
invoke_starting_func (FridaStartingFunc fn,
void * user_data)
{
fn (user_data);
}
static inline void
invoke_finished_func (FridaFinishedFunc fn,
void * user_data)
{
fn (user_data);
}
static inline void
invoke_output_func (FridaOutputFunc fn,
char * bundle,
void * user_data)
{
fn (bundle, user_data);
}
static inline void
invoke_diagnostic_func (FridaDiagnosticFunc fn,
char * category,
int code,
char * path,
int line,
int character,
char * text,
void * user_data)
{
fn (category, code, path, line, character, text, user_data);
}
static inline void
invoke_destroy_func (FridaDestroyFunc fn,
void * user_data)
{
fn (user_data);
}
*/
import "C"
import (
"runtime/cgo"
"unsafe"
)
//export _frida_compiler_backend_build
func _frida_compiler_backend_build(cProjectRoot, cEntrypoint *C.char, outputFormat C.FridaOutputFormat, bundleFormat C.FridaBundleFormat,
disableTypeCheck, sourceMap, compress uintptr, cPlatform *C.char, cExternals **C.char, numExternals C.int,
onDiagnosticFn C.FridaDiagnosticFunc, onDiagnosticData unsafe.Pointer, onCompleteFn C.FridaBuildCompleteFunc,
onCompleteData unsafe.Pointer, onCompleteDataDestroy C.FridaDestroyFunc) {
options := BuildOptions{
ProjectRoot: C.GoString(cProjectRoot),
Entrypoint: C.GoString(cEntrypoint),
OutputFormat: OutputFormat(outputFormat),
BundleFormat: BundleFormat(bundleFormat),
DisableTypeCheck: disableTypeCheck != 0,
SourceMap: sourceMap != 0,
Compress: compress != 0,
Platform: platformFromFrida(C.GoString(cPlatform)),
Externals: parseCExternals(cExternals, numExternals),
}
onDiagnostic := NewCDelegate(onDiagnosticFn, onDiagnosticData, nil)
onComplete := NewCDelegate(onCompleteFn, onCompleteData, onCompleteDataDestroy)
go func() {
defer onComplete.Dispose()
defer onDiagnostic.Dispose()
onDiagnostic := makeCBuildDiagnosticCallback(onDiagnostic)
bundle, err := build(options, onDiagnostic)
var cBundle, cErrorMessage *C.char
if err == nil {
cBundle = C.CString(bundle)
} else {
cErrorMessage = C.CString(err.Error())
}
C.invoke_build_complete_func(onComplete.Func, cBundle, cErrorMessage, onComplete.Data)
}()
}
//export _frida_compiler_backend_watch
func _frida_compiler_backend_watch(cProjectRoot, cEntrypoint *C.char, outputFormat C.FridaOutputFormat, bundleFormat C.FridaBundleFormat,
disableTypeCheck, sourceMap, compress uintptr, cPlatform *C.char, cExternals **C.char, numExternals C.int,
onStartingFn C.FridaStartingFunc, onStartingData unsafe.Pointer,
onFinishedFn C.FridaFinishedFunc, onFinishedData unsafe.Pointer,
onOutputFn C.FridaOutputFunc, onOutputData unsafe.Pointer,
onDiagnosticFn C.FridaDiagnosticFunc, onDiagnosticData unsafe.Pointer,
onReadyFn C.FridaWatchReadyFunc, onReadyData unsafe.Pointer, onReadyDataDestroy C.FridaDestroyFunc) {
options := BuildOptions{
ProjectRoot: C.GoString(cProjectRoot),
Entrypoint: C.GoString(cEntrypoint),
OutputFormat: OutputFormat(outputFormat),
BundleFormat: BundleFormat(bundleFormat),
DisableTypeCheck: disableTypeCheck != 0,
SourceMap: sourceMap != 0,
Compress: compress != 0,
Platform: platformFromFrida(C.GoString(cPlatform)),
Externals: parseCExternals(cExternals, numExternals),
}
onStarting := NewCDelegate(onStartingFn, onStartingData, nil)
onFinished := NewCDelegate(onFinishedFn, onFinishedData, nil)
onOutput := NewCDelegate(onOutputFn, onOutputData, nil)
onDiagnostic := NewCDelegate(onDiagnosticFn, onDiagnosticData, nil)
onReady := NewCDelegate(onReadyFn, onReadyData, onReadyDataDestroy)
go func() {
defer onReady.Dispose()
onDispose := func() {
onStarting.Dispose()
onFinished.Dispose()
onOutput.Dispose()
onDiagnostic.Dispose()
}
callbacks := BuildEventCallbacks{
OnStart: func() {
C.invoke_starting_func(onStarting.Func, onStarting.Data)
},
OnEnd: func() {
C.invoke_finished_func(onFinished.Func, onFinished.Data)
},
OnOutput: func(bundle string) {
C.invoke_output_func(onOutput.Func, C.CString(bundle), onOutput.Data)
},
OnDiagnostic: makeCBuildDiagnosticCallback(onDiagnostic),
}
session, err := NewWatchSession(options, onDispose, callbacks)
var cSession C.uintptr_t
var cErrorMessage *C.char
if err == nil {
cSession = C.uintptr_t(cgo.NewHandle(session))
} else {
cErrorMessage = C.CString(err.Error())
}
C.invoke_watch_ready_func(onReady.Func, cSession, cErrorMessage, onReady.Data)
}()
}
//export _frida_compiler_backend_watch_session_dispose
func _frida_compiler_backend_watch_session_dispose(h uintptr) {
handle := cgo.Handle(h)
session := handle.Value().(*WatchSession)
session.Dispose()
handle.Delete()
}
func parseCExternals(cExternals **C.char, numExternals C.int) []string {
if numExternals == 0 {
return nil
}
n := int(numExternals)
cArray := (*[1 << 20]*C.char)(unsafe.Pointer(cExternals))[:n:n]
externals := make([]string, n)
for i := 0; i < n; i++ {
externals[i] = C.GoString(cArray[i])
}
return externals
}
func makeCBuildDiagnosticCallback(onDiagnostic *CDelegate[C.FridaDiagnosticFunc]) BuildDiagnosticCallback {
return func(d Diagnostic) {
var cPath *C.char
if d.path != "" {
cPath = C.CString(d.path)
}
C.invoke_diagnostic_func(onDiagnostic.Func, C.CString(d.category), C.int(d.code), cPath, C.int(d.line),
C.int(d.character), C.CString(d.text), onDiagnostic.Data)
}
}
type CDelegate[F any] struct {
Func F
null F
Data unsafe.Pointer
dataDestroy C.FridaDestroyFunc
}
func NewCDelegate[F any](function F, data unsafe.Pointer, dataDestroy C.FridaDestroyFunc) *CDelegate[F] {
return &CDelegate[F]{Func: function, Data: data, dataDestroy: dataDestroy}
}
func (d *CDelegate[F]) Dispose() {
if d.dataDestroy != nil {
C.invoke_destroy_func(d.dataDestroy, d.Data)
}
d.Func = d.null
d.Data = nil
d.dataDestroy = nil
}
func main() {}
+263
View File
@@ -0,0 +1,263 @@
//go:build frida_compiler_backend_executable
package main
import (
"bufio"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"sync"
)
type BackendRequest struct {
Type string `json:"type"`
ID uint `json:"id,omitempty"`
SessionID uint `json:"session_id,omitempty"`
ProjectRoot string `json:"project_root,omitempty"`
Entrypoint string `json:"entrypoint,omitempty"`
OutputFormat string `json:"output_format,omitempty"`
BundleFormat string `json:"bundle_format,omitempty"`
DisableTypeCheck bool `json:"disable_type_check,omitempty"`
SourceMap bool `json:"source_map,omitempty"`
Compress bool `json:"compress,omitempty"`
Platform string `json:"platform,omitempty"`
Externals []string `json:"externals,omitempty"`
}
type BackendEvent struct {
Type string `json:"type"`
ID uint `json:"id,omitempty"`
SessionID uint `json:"session_id,omitempty"`
Bundle string `json:"bundle,omitempty"`
Error string `json:"error,omitempty"`
Category string `json:"category,omitempty"`
Code int `json:"code,omitempty"`
Path string `json:"path,omitempty"`
Line int `json:"line,omitempty"`
Character int `json:"character,omitempty"`
Text string `json:"text,omitempty"`
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
}
func run() error {
reader := bufio.NewReaderSize(os.Stdin, 128*1024)
writer := bufio.NewWriterSize(os.Stdout, 128*1024)
var outputMu sync.Mutex
var sessionsMu sync.Mutex
sessions := make(map[uint]*WatchSession)
emit := func(ev BackendEvent) {
outputMu.Lock()
defer outputMu.Unlock()
if err := writeMessage(writer, ev); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
}
}
for {
var req BackendRequest
if err := readMessage(reader, &req); err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
switch req.Type {
case "build":
go func(req BackendRequest) {
options, err := buildOptionsFromRequest(req)
if err != nil {
emit(BackendEvent{
Type: "build:complete",
ID: req.ID,
Error: err.Error(),
})
return
}
onDiagnostic := func(d Diagnostic) {
ev := BackendEvent{
Type: "build:diagnostic",
ID: req.ID,
Category: d.category,
Code: d.code,
Path: d.path,
Line: d.line,
Character: d.character,
Text: d.text,
}
emit(ev)
}
bundle, err := build(options, onDiagnostic)
ev := BackendEvent{
Type: "build:complete",
ID: req.ID,
}
if err != nil {
ev.Error = err.Error()
} else {
ev.Bundle = bundle
}
emit(ev)
}(req)
case "watch":
go func(req BackendRequest) {
options, err := buildOptionsFromRequest(req)
if err != nil {
emit(BackendEvent{
Type: "watch:ready",
SessionID: req.SessionID,
Error: err.Error(),
})
return
}
callbacks := BuildEventCallbacks{
OnStart: func() {
emit(BackendEvent{
Type: "watch:starting",
SessionID: req.SessionID,
})
},
OnEnd: func() {
emit(BackendEvent{
Type: "watch:finished",
SessionID: req.SessionID,
})
},
OnOutput: func(bundle string) {
emit(BackendEvent{
Type: "watch:output",
SessionID: req.SessionID,
Bundle: bundle,
})
},
OnDiagnostic: func(d Diagnostic) {
emit(BackendEvent{
Type: "watch:diagnostic",
SessionID: req.SessionID,
Category: d.category,
Code: d.code,
Path: d.path,
Line: d.line,
Character: d.character,
Text: d.text,
})
},
}
var session *WatchSession
onDispose := func() {
sessionsMu.Lock()
delete(sessions, req.SessionID)
sessionsMu.Unlock()
}
session, err = NewWatchSession(options, onDispose, callbacks)
if err != nil {
emit(BackendEvent{
Type: "watch:ready",
SessionID: req.SessionID,
Error: err.Error(),
})
return
}
sessionsMu.Lock()
sessions[req.SessionID] = session
sessionsMu.Unlock()
emit(BackendEvent{
Type: "watch:ready",
SessionID: req.SessionID,
})
}(req)
case "dispose":
sessionsMu.Lock()
session := sessions[req.SessionID]
delete(sessions, req.SessionID)
sessionsMu.Unlock()
if session != nil {
session.Dispose()
}
default:
return fmt.Errorf("unsupported request type: %q", req.Type)
}
}
}
func buildOptionsFromRequest(req BackendRequest) (BuildOptions, error) {
outputFormat, err := outputFormatFromNick(req.OutputFormat)
if err != nil {
return BuildOptions{}, err
}
bundleFormat, err := bundleFormatFromNick(req.BundleFormat)
if err != nil {
return BuildOptions{}, err
}
return BuildOptions{
ProjectRoot: req.ProjectRoot,
Entrypoint: req.Entrypoint,
OutputFormat: outputFormat,
BundleFormat: bundleFormat,
DisableTypeCheck: req.DisableTypeCheck,
SourceMap: req.SourceMap,
Compress: req.Compress,
Platform: platformFromFrida(req.Platform),
Externals: req.Externals,
}, nil
}
func readMessage(r io.Reader, out any) error {
var size uint32
if err := binary.Read(r, binary.BigEndian, &size); err != nil {
return err
}
buf := make([]byte, size)
if _, err := io.ReadFull(r, buf); err != nil {
return err
}
return json.Unmarshal(buf, out)
}
func writeMessage(w *bufio.Writer, msg any) error {
buf, err := json.Marshal(msg)
if err != nil {
return err
}
if err := binary.Write(w, binary.BigEndian, uint32(len(buf))); err != nil {
return err
}
if _, err := w.Write(buf); err != nil {
return err
}
return w.Flush()
}
+39 -14
View File
@@ -4,12 +4,30 @@ compiler_sources = files(
)
if have_compiler_backend
output_suffix = compiler_backend_static_compilation ? '' : '-raw'
if compiler_backend_mode == 'c-archive'
output_files = [
'frida-compiler-backend.a',
'frida-compiler-backend.h',
]
elif compiler_backend_mode == 'c-shared'
output_files = [
'frida-compiler-backend-raw' + shlib_suffix,
'frida-compiler-backend-raw.h',
]
elif compiler_backend_mode == 'pie'
output_files = [
'frida-compiler-backend-raw' + exe_suffix,
]
endif
compiler_backend = custom_target('frida-compiler-backend',
input: [
'go.mod',
'go.sum',
'frontend_capi.go',
'frontend_stdio.go',
'backend.go',
'protocol_types.go',
'backend.version',
'tscompiler.go',
'tsconfig.go',
@@ -17,10 +35,7 @@ if have_compiler_backend
'package.json',
'package-lock.json',
],
output: [
'frida-compiler-backend' + output_suffix + (compiler_backend_static_compilation ? '.a' : shlib_suffix),
'frida-compiler-backend' + output_suffix + '.h',
],
output: output_files,
command: [
python,
files('build-backend.py'),
@@ -32,21 +47,31 @@ if have_compiler_backend
'@INPUT@',
],
)
if compiler_backend_static_compilation
if compiler_backend_mode == 'c-archive'
backend_libs += compiler_backend[0]
else
filename = 'frida-compiler-backend' + shlib_suffix
identity = (host_os_family == 'darwin') ? 'FridaCompilerBackend' : filename
compiler_backend_shlib = custom_target('frida-compiler-backend-shlib',
input: compiler_backend[0],
output: filename,
command: post_process + ['shared-library', identity, 'elf-cleaner:off'],
)
if compiler_backend_mode == 'c-shared'
processed_filename = 'frida-compiler-backend' + shlib_suffix
identity = (host_os_family == 'darwin') ? 'FridaCompilerBackend' : processed_filename
compiler_backend_binary = custom_target('frida-compiler-backend-binary',
input: compiler_backend[0],
output: processed_filename,
command: post_process + ['shared-library', identity, 'elf-cleaner:off'],
)
elif compiler_backend_mode == 'pie'
processed_filename = 'frida-compiler-backend' + exe_suffix
compiler_backend_binary = custom_target('frida-compiler-backend-binary',
input: compiler_backend[0],
output: processed_filename,
command: post_process + ['executable', processed_filename],
)
endif
compiler_data = custom_target('frida-data-compiler',
input: [
'compiler.resources',
compiler_backend_shlib,
compiler_backend_binary,
],
output: [
'frida-data-compiler.vapi',
+4 -4
View File
@@ -33,7 +33,7 @@
"@frida/url": "^1.0.2",
"@frida/util": "^1.0.3",
"@frida/vm": "^2.0.0",
"@types/frida-gum": "19.0.1",
"@types/frida-gum": "19.0.2",
"@types/node": "18.19.103",
"frida-fs": "7.0.0"
}
@@ -248,9 +248,9 @@
"license": "MIT"
},
"node_modules/@types/frida-gum": {
"version": "19.0.1",
"resolved": "https://registry.npmjs.org/@types/frida-gum/-/frida-gum-19.0.1.tgz",
"integrity": "sha512-mp8BpWWkQFJH86ZN5uXZuDiA7KY/+jDknrw0a06x0/+F5ucPwctHrCuV6iT+LLCp/GyICc36ssedF33B1WoLsw==",
"version": "19.0.2",
"resolved": "https://registry.npmjs.org/@types/frida-gum/-/frida-gum-19.0.2.tgz",
"integrity": "sha512-oh/f1r8dIMDWBoziXP3geIJ8ga/siU32MuifBztGsDglOKbHrhS0E3z0Dab0MIe3UFzC4Bvz/GRHfin2LDE8BQ==",
"license": "MIT"
},
"node_modules/@types/node": {
+1 -1
View File
@@ -29,7 +29,7 @@
"@frida/url": "^1.0.2",
"@frida/util": "^1.0.3",
"@frida/vm": "^2.0.0",
"@types/frida-gum": "19.0.1",
"@types/frida-gum": "19.0.2",
"@types/node": "18.19.103",
"frida-fs": "7.0.0"
}
+59
View File
@@ -0,0 +1,59 @@
package main
import (
"fmt"
esbuild "github.com/evanw/esbuild/pkg/api"
)
type OutputFormat int
const (
OutputFormatUnescaped OutputFormat = iota
OutputFormatHexBytes
OutputFormatCString
)
func outputFormatFromNick(s string) (OutputFormat, error) {
switch s {
case "unescaped":
return OutputFormatUnescaped, nil
case "hex-bytes":
return OutputFormatHexBytes, nil
case "c-string":
return OutputFormatCString, nil
default:
return 0, fmt.Errorf("unknown output format: %q", s)
}
}
type BundleFormat int
const (
BundleFormatESM BundleFormat = iota
BundleFormatIIFE
)
func bundleFormatFromNick(s string) (BundleFormat, error) {
switch s {
case "esm":
return BundleFormatESM, nil
case "iife":
return BundleFormatIIFE, nil
default:
return 0, fmt.Errorf("unknown bundle format: %q", s)
}
}
func platformFromFrida(s string) esbuild.Platform {
switch s {
case "gum":
return esbuild.PlatformNode
case "browser":
return esbuild.PlatformBrowser
case "neutral":
return esbuild.PlatformNeutral
default:
panic(fmt.Sprintf("Unknown platform: %q", s))
}
}
+16 -12
View File
@@ -444,6 +444,7 @@ static void frida_set_nth_hardware_breakpoint (gpointer state, guint n, GumAddre
static void frida_set_hardware_single_step (gpointer debug_state, GumDarwinUnifiedThreadState * thread_state, gboolean enabled, GumCpuType cpu_type);
static gboolean frida_is_hardware_breakpoint_support_working (void);
static gboolean frida_find_restart_with_dyld_in_cache (const GumDarwinSymbolDetails * details, gpointer user_data);
static GumAddress frida_find_run_initializers_call (mach_port_t task, GumCpuType cpu_type, GumAddress start);
static GHashTable * frida_find_modinit_strcmp_checks (mach_port_t task, GumDarwinModule * dyld);
static GumAddress frida_find_function_end (mach_port_t task, GumCpuType cpu_type, GumAddress start, gsize max_size);
@@ -2107,18 +2108,8 @@ _frida_darwin_helper_backend_prepare_spawn_instance_for_injection (FridaDarwinHe
frida_spawn_instance_set_nth_breakpoint (instance, i++, sim_notify_address, FRIDA_BREAKPOINT_REPEAT_ALWAYS);
if (instance->dyld_flavor == FRIDA_DYLD_V4_PLUS)
{
GumAddress restart_with_dyld_in_cache = gum_darwin_module_resolve_symbol_address (dyld,
"__ZN5dyld422restartWithDyldInCacheEPKNS_10KernelArgsEPKN6mach_o6HeaderEPK15DyldSharedCachePv");
if (restart_with_dyld_in_cache == 0)
{
restart_with_dyld_in_cache = gum_darwin_module_resolve_symbol_address (dyld,
"__ZN5dyld422restartWithDyldInCacheEPKNS_10KernelArgsEPKN5dyld39MachOFileEPK15DyldSharedCachePv");
}
if (restart_with_dyld_in_cache == 0)
{
restart_with_dyld_in_cache = gum_darwin_module_resolve_symbol_address (dyld,
"__ZN5dyld422restartWithDyldInCacheEPKNS_10KernelArgsEPKN5dyld39MachOFileEPv");
}
GumAddress restart_with_dyld_in_cache = 0;
gum_darwin_module_enumerate_symbols (dyld, frida_find_restart_with_dyld_in_cache, &restart_with_dyld_in_cache);
if (restart_with_dyld_in_cache != 0)
frida_spawn_instance_set_nth_breakpoint (instance, i++, restart_with_dyld_in_cache, FRIDA_BREAKPOINT_REPEAT_NEVER);
}
@@ -5442,6 +5433,19 @@ frida_is_hardware_breakpoint_support_working (void)
#endif
}
static gboolean
frida_find_restart_with_dyld_in_cache (const GumDarwinSymbolDetails * details, gpointer user_data)
{
if (strstr (details->name, "restartWithDyldInCache") != NULL)
{
GumAddress * restart_with_dyld_in_cache = user_data;
*restart_with_dyld_in_cache = details->address;
return FALSE;
}
return TRUE;
}
static GumAddress
frida_find_run_initializers_call (mach_port_t task, GumCpuType cpu_type, GumAddress start)
{
+31 -12
View File
@@ -135,7 +135,18 @@ namespace Frida {
if (host_session != null)
throw new Error.INVALID_ARGUMENT ("Already created");
host_session = new DroidyHostSession (device_details, this);
string control_endpoint = ("tcp:%" + uint16.FORMAT_MODIFIER + "u").printf (DEFAULT_CONTROL_PORT);
if (options != null) {
Value? control_endpoint_val = options.map["control-endpoint"];
if (control_endpoint_val != null) {
if (!control_endpoint_val.holds (typeof (string)))
throw new Error.INVALID_ARGUMENT ("The control-endpoint option must be a string");
control_endpoint = control_endpoint_val.get_string ();
}
}
host_session = new DroidyHostSession (device_details, this, control_endpoint);
host_session.agent_session_detached.connect (on_agent_session_detached);
return host_session;
@@ -231,6 +242,11 @@ namespace Frida {
construct;
}
public string control_endpoint {
get;
construct;
}
private Promise<AndroidHelperClient>? helper_client_request;
private Droidy.ShellSession? helper_shell;
@@ -258,10 +274,12 @@ namespace Frida {
private const double MIN_SERVER_CHECK_INTERVAL = 5.0;
private const string GADGET_APP_ID = "re.frida.Gadget";
public DroidyHostSession (Droidy.DeviceDetails device_details, HostChannelProvider channel_provider) {
public DroidyHostSession (Droidy.DeviceDetails device_details, HostChannelProvider channel_provider,
string control_endpoint) {
Object (
device_details: device_details,
channel_provider: channel_provider
channel_provider: channel_provider,
control_endpoint: control_endpoint
);
}
@@ -290,8 +308,9 @@ namespace Frida {
if (helper_client_request != null) {
AndroidHelperClient? helper = yield try_get_helper_client (cancellable);
if (helper != null) {
on_helper_client_closed (helper);
yield helper.close (cancellable);
var transport = (AndroidHelperStreamTransport) helper.transport;
on_helper_stream_transport_closed (transport);
yield transport.close (cancellable);
}
}
@@ -837,9 +856,7 @@ namespace Frida {
DBusConnection? connection = null;
try {
var stream = yield channel_provider.open_channel (
("tcp:%" + uint16.FORMAT_MODIFIER + "u").printf (DEFAULT_CONTROL_PORT),
cancellable);
var stream = yield channel_provider.open_channel (control_endpoint, cancellable);
WebServiceTransport transport = PLAIN;
string? origin = null;
@@ -1060,8 +1077,10 @@ namespace Frida {
throw e;
}
var helper = new AndroidHelperClient (client.stream);
helper.closed.connect (on_helper_client_closed);
var transport = new AndroidHelperStreamTransport (client.stream);
transport.closed.connect (on_helper_stream_transport_closed);
var helper = new AndroidHelperClient (transport);
helper_shell = shell;
@@ -1080,8 +1099,8 @@ namespace Frida {
}
}
private void on_helper_client_closed (AndroidHelperClient helper) {
helper.closed.disconnect (on_helper_client_closed);
private void on_helper_stream_transport_closed (AndroidHelperStreamTransport transport) {
transport.closed.disconnect (on_helper_stream_transport_closed);
helper_client_request = null;
if (helper_shell != null) {
+39 -1
View File
@@ -581,6 +581,40 @@ namespace Frida {
return close_request != null;
}
public void override_option (string name, Variant val) throws Error {
Value v;
switch (val.classify ()) {
case BOOLEAN:
v = Value (typeof (bool));
v.set_boolean (val.get_boolean ());
break;
case INT64:
v = Value (typeof (int64));
v.set_int64 (val.get_int64 ());
break;
case UINT64:
v = Value (typeof (uint64));
v.set_uint64 (val.get_uint64 ());
break;
case DOUBLE:
v = Value (typeof (double));
v.set_double (val.get_double ());
break;
case STRING:
v = Value (typeof (string));
v.set_string (val.get_string ());
break;
default:
throw new Error.INVALID_ARGUMENT ("Unsupported option type");
}
lock (host_session_options) {
if (host_session_options == null)
host_session_options = new HostSessionOptions ();
host_session_options.map[name] = v;
}
}
public async HashTable<string, Variant> query_system_parameters (Cancellable? cancellable = null) throws Error, IOError {
check_open ();
@@ -1332,7 +1366,11 @@ namespace Frida {
host_session_request = new Promise<HostSession> ();
try {
var session = yield provider.create (manager, host_session_options, cancellable);
HostSessionOptions? opts;
lock (host_session_options)
opts = (host_session_options != null) ? host_session_options.copy () : null;
var session = yield provider.create (manager, opts, cancellable);
attach_host_session (session);
current_host_session = session;
+401
View File
@@ -0,0 +1,401 @@
[CCode (gir_namespace = "FridaFruity", gir_version = "1.0")]
namespace Frida.Fruity {
public class CsSignature : Object {
public uint32 version;
public uint32 pid;
public uint32 stuff;
public uint32 flags;
public Gee.List<CsSigOwner> owners = new Gee.ArrayList<CsSigOwner> ();
private CsSegIndexEntry[]? seg_index = null;
private uint32 seg_index_gen = 0;
private struct CsSegIndexEntry {
public uint64 start;
public uint64 end;
public unowned CsSigOwner owner;
}
public void apply_refresh (CsSignature fresh, uint32 gen) {
foreach (var cur in owners) {
if (cur.mapped_gen_end != 0)
continue;
bool still_present = false;
foreach (var f in fresh.owners) {
if (cur.uuid.compare (f.uuid) == 0) {
still_present = true;
break;
}
}
if (!still_present)
cur.mapped_gen_end = gen;
}
foreach (var f in fresh.owners) {
CsSigOwner? cur = null;
foreach (var existing in owners) {
if (existing.uuid.compare (f.uuid) == 0) {
cur = existing;
break;
}
}
if (cur == null) {
f.mapped_gen_start = gen;
f.mapped_gen_end = 0;
owners.add (f);
} else {
uint32 start = cur.mapped_gen_start;
uint32 end = cur.mapped_gen_end;
cur.path = f.path;
cur.image_base = f.image_base;
cur.image_end = f.image_end;
cur.segments = f.segments;
cur.version = f.version;
cur.mapped_gen_start = start;
cur.mapped_gen_end = end;
}
}
invalidate_index ();
}
public void note_unmapped_uuid (Bytes uuid, uint32 gen) {
foreach (var o in owners) {
if (o.mapped_gen_end != 0)
continue;
if (o.uuid.compare (uuid) == 0) {
o.mapped_gen_end = gen;
invalidate_index ();
return;
}
}
}
public void resolve_addresses (uint32 gen, uint64[] addrs, AddressResolved on_symbol, ModulesReady on_modules) {
ensure_index (gen);
var used_owner_to_mod = new Gee.HashMap<CsSigOwner, uint32> ();
var module_list = new Gee.ArrayList<CsSigOwner> ();
foreach (var addr in addrs) {
CsSigOwner? owner;
uint32 rel;
if (!try_resolve (addr, out owner, out rel)) {
on_symbol (addr, uint32.MAX, 0);
continue;
}
uint32 mod_idx;
if (!used_owner_to_mod.has_key (owner)) {
mod_idx = (uint32) module_list.size;
used_owner_to_mod[owner] = mod_idx;
module_list.add (owner);
} else {
mod_idx = used_owner_to_mod[owner];
}
on_symbol (addr, mod_idx, rel);
}
on_modules (module_list);
}
public delegate void AddressResolved (uint64 addr, uint32 module_index, uint32 rel);
public delegate void ModulesReady (Gee.List<CsSigOwner> modules);
private void ensure_index (uint32 gen) {
if (seg_index != null && seg_index_gen == gen)
return;
var tmp = new Array<CsSegIndexEntry> (false, false);
foreach (var owner in owners) {
if (!owner_is_mapped_at (owner, gen))
continue;
foreach (var seg in owner.segments) {
if (seg.name == "__PAGEZERO")
continue;
tmp.append_val (CsSegIndexEntry () {
start = seg.vmaddr,
end = seg.vmaddr + seg.vmsize,
owner = owner,
});
}
}
tmp.sort ((a, b) => {
if (a.start < b.start)
return -1;
if (a.start > b.start)
return 1;
return 0;
});
seg_index = tmp.steal ();
seg_index_gen = gen;
}
private void invalidate_index () {
seg_index = null;
seg_index_gen = 0;
}
private bool try_resolve (uint64 addr, out CsSigOwner? owner, out uint32 rel) {
owner = null;
rel = 0;
int n = seg_index.length;
if (n == 0)
return false;
int lo = 0;
int hi = n - 1;
int best = -1;
while (lo <= hi) {
int mid = lo + ((hi - lo) / 2);
if (seg_index[mid].start <= addr) {
best = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (best == -1)
return false;
for (int i = best; i >= 0; i--) {
var e = seg_index[i];
if (e.start > addr)
continue;
if (addr < e.end) {
owner = e.owner;
rel = (uint32) (addr - owner.image_base);
return true;
}
}
return false;
}
private static bool owner_is_mapped_at (CsSigOwner owner, uint32 gen) {
if (gen < owner.mapped_gen_start)
return false;
uint32 end = owner.mapped_gen_end;
if (end == 0)
return true;
return gen < end;
}
}
public class CsSigOwner : Object {
public Bytes uuid;
public uint32 a;
public uint32 flags;
public uint64 load_timestamp;
public uint64 unload_timestamp;
public uint32 cpu_type;
public uint32 cpu_subtype;
public string path;
public uint64 image_base;
public uint64 image_end;
public Gee.List<CsSigSegment> segments = new Gee.ArrayList<CsSigSegment> ();
public string? version;
public uint32 mapped_gen_start = 1;
public uint32 mapped_gen_end = 0;
}
public class CsSigSegment {
public string name;
public uint64 vmaddr;
public uint64 vmsize;
}
public sealed class CsSignatureParser : Object {
private Buffer buf;
private BufferReader r;
public CsSignatureParser (Bytes blob) {
buf = new Buffer (blob, LITTLE_ENDIAN, 8);
r = new BufferReader (buf);
}
public CsSignature parse () throws Error {
uint32 magic = r.read_uint32 ();
uint32 version = r.read_uint32 ();
uint32 pid = r.read_uint32 ();
uint32 stuff = r.read_uint32 ();
uint32 flags = r.read_uint32 ();
uint32 owner_count = r.read_uint32 ();
if (magic != 0xff01ff02u)
throw new Error.PROTOCOL ("Bad signature magic 0x%08x", magic);
var sig = new CsSignature ();
sig.version = version;
sig.pid = pid;
sig.stuff = stuff;
sig.flags = flags;
for (uint32 i = 0; i != owner_count; i++)
sig.owners.add (parse_owner ());
decode_optional_data (sig);
return sig;
}
private CsSigOwner parse_owner () throws Error {
var o = new CsSigOwner ();
o.uuid = r.read_bytes (16);
o.a = r.read_uint32 ();
o.flags = r.read_uint32 () & 0x7fffffff;
o.load_timestamp = r.read_uint64 ();
o.unload_timestamp = r.read_uint64 ();
o.cpu_type = r.read_uint32 ();
o.cpu_subtype = r.read_uint32 ();
uint32 nsegs = r.read_uint32 ();
uint32 str_len = r.read_uint32 ();
o.path = r.read_fixed_string (str_len);
for (uint32 i = 0; i != nsegs; i++) {
var s = new CsSigSegment ();
s.name = r.read_fixed_string (16);
s.vmaddr = r.read_uint64 ();
s.vmsize = r.read_uint64 ();
o.segments.add (s);
}
o.segments.sort ((a, b) => {
if (a.vmaddr < b.vmaddr)
return -1;
if (a.vmaddr > b.vmaddr)
return 1;
return 0;
});
uint64 image_base = uint64.MAX;
uint64 image_end = 0;
foreach (var seg in o.segments) {
if (seg.name != "__PAGEZERO" && seg.vmaddr < image_base)
image_base = seg.vmaddr;
uint64 seg_end = seg.vmaddr + seg.vmsize;
if (seg_end > image_end)
image_end = seg_end;
}
o.image_base = image_base;
o.image_end = image_end;
return o;
}
private void decode_optional_data (CsSignature sig) throws Error {
if (r.available < 8)
return;
size_t start = r.offset;
uint64 hdr = r.read_uint64 ();
uint32 magic = (uint32) (hdr & 0xffffffffu);
uint32 sel = (uint32) (hdr >> 32);
if (magic != 0x00c0ffeeu) {
r.seek (start);
return;
}
if (sel == 2) {
if (r.available < 0x18)
throw new Error.PROTOCOL ("Optional v2 truncated");
r.skip (0x18);
return;
}
if (sel == 3) {
skip_optional_v3 ();
return;
}
if (sel != 4)
return;
size_t v3_start = r.offset;
uint32 count = skip_optional_v3 ();
size_t table_end = v3_start + 0x38 + (size_t) count * 0x60;
if (table_end + 4 > buf.size)
throw new Error.PROTOCOL ("Optional v4 truncated");
r.seek (table_end);
uint32 strings_size = r.read_uint32 ();
size_t strings_start = r.offset;
size_t strings_end = strings_start + (size_t) strings_size;
if (strings_end > buf.size)
throw new Error.PROTOCOL ("Optional v4 strings overrun");
r.seek (strings_start);
for (int i = 0; i < sig.owners.size; i++) {
if (r.offset >= strings_end)
throw new Error.PROTOCOL ("Optional v4 strings truncated");
sig.owners[i].version = r.read_string ();
}
r.seek (v3_start + 0x3c + (size_t) count * 0x60 + (size_t) strings_size);
}
private uint32 skip_optional_v3 () throws Error {
if (r.available < 0x38)
throw new Error.PROTOCOL ("Optional v3 truncated");
size_t base_offset = r.offset;
r.skip (0x30);
r.read_uint8 ();
r.skip (3);
uint32 count = r.read_uint32 ();
size_t total = 0x38 + (size_t) count * 0x60;
if (base_offset + total > buf.size)
throw new Error.PROTOCOL ("Optional v3 overrun");
r.seek (base_offset + total);
return count;
}
}
}
+15 -3
View File
@@ -396,7 +396,17 @@ namespace Frida.Fruity {
}
private static int compare_transports (Transport a, Transport b) {
return score_transport (b) - score_transport (a);
int res = score_transport (b) - score_transport (a);
if (res != 0)
return res;
if (a == b)
return 0;
uintptr ap = (uintptr) (void *) a;
uintptr bp = (uintptr) (void *) b;
return (ap < bp) ? -1 : 1;
}
private static int score_transport (Transport t) {
@@ -783,7 +793,8 @@ namespace Frida.Fruity {
}
private void on_tunnel_lost () {
tunnel_request = null;
if (tunnel_request.future.ready)
tunnel_request = null;
}
public async IOStream open_lockdown_service (string service_name, Cancellable? cancellable) throws Error, IOError {
@@ -1672,7 +1683,8 @@ namespace Frida.Fruity {
}
private void on_tunnel_lost () {
tunnel_request = null;
if (tunnel_request.future.ready)
tunnel_request = null;
}
}
+2 -2
View File
@@ -50,8 +50,8 @@ namespace Frida.Fruity {
if (rr.key.klass != IN)
throw new Error.PROTOCOL ("Expected an AAAA record of class IN");
var subreader = new DnsPacketReader (rr.data);
var raw_address = subreader.reader.read_bytes (16);
var address = new InetAddress.from_bytes (raw_address.get_data (), IPV6);
unowned uint8[] raw_address = subreader.reader.read_data (16);
var address = new InetAddress.from_bytes (raw_address, IPV6);
return new DnsAaaaRecord () {
key = rr.key,
ttl = rr.ttl,
+787 -30
View File
@@ -69,6 +69,20 @@ namespace Frida.Fruity {
return result;
}
public async CsSignature query_symbolicator_signature (uint pid, Cancellable? cancellable = null) throws Error, IOError {
var args = new DTXArgumentListBuilder ()
.append_object (new NSNumber.from_integer (pid))
.append_object (new NSString (""));
var response = yield channel.invoke ("symbolicatorSignatureForPid:trackingSelector:", args, cancellable);
NSData? data = response as NSData;
if (data == null)
throw new Error.PROTOCOL ("Malformed response");
var parser = new CsSignatureParser (data.bytes);
return parser.parse ();
}
private static string resolve_real_app_name (string name) {
if (name.has_prefix ("/var/"))
return "/private" + name;
@@ -307,6 +321,8 @@ namespace Frida.Fruity {
}
public sealed class ProcessControlService : Object, AsyncInitable {
public signal void process_terminated (uint pid, int exit_code, int crashing_signal);
public HostChannelProvider channel_provider {
get;
construct;
@@ -335,15 +351,746 @@ namespace Frida.Fruity {
var connection = yield DTXConnection.obtain (channel_provider, cancellable);
channel = connection.make_channel ("com.apple.instruments.server.services.processcontrol");
channel.invocation.connect (on_invocation);
return true;
}
public async uint process_identifier_for_bundle_identifier (string bundle_id, Cancellable? cancellable = null)
throws Error, IOError {
var args = new DTXArgumentListBuilder ()
.append_object (new NSString (bundle_id));
var response = yield channel.invoke ("processIdentifierForBundleIdentifier:", args, cancellable);
NSNumber? pid = response as NSNumber;
if (pid == null)
throw new Error.PROTOCOL ("Malformed response");
return (uint) pid.integer;
}
public async bool is_pid_debuggable (uint pid, Cancellable? cancellable = null) throws Error, IOError {
var args = new DTXArgumentListBuilder ()
.append_object (new NSNumber.from_integer (pid));
var response = yield channel.invoke ("isPidDebuggable:", args, cancellable);
NSNumber? is_debuggable = response as NSNumber;
if (is_debuggable == null)
throw new Error.PROTOCOL ("Malformed response");
return is_debuggable.boolean;
}
public async void start_observing_pid (uint pid, Cancellable? cancellable = null) throws Error, IOError {
var args = new DTXArgumentListBuilder ()
.append_object (new NSNumber.from_integer (pid));
yield channel.invoke ("startObservingPid:", args, cancellable);
}
public async void stop_observing_pid (uint pid, Cancellable? cancellable = null) throws Error, IOError {
var args = new DTXArgumentListBuilder ()
.append_object (new NSNumber.from_integer (pid));
yield channel.invoke ("stopObservingPid:", args, cancellable);
}
public async uint launch (string bundle_id, LaunchOptions? options = null, Cancellable? cancellable = null)
throws Error, IOError {
var opts = options;
if (opts == null)
opts = new LaunchOptions ();
var args_val = new NSArray ();
foreach (unowned string arg in opts.arguments)
args_val.add_object (new NSString (arg));
var env_val = new NSDictionary ();
foreach (unowned string entry in opts.environment) {
string[] tokens = entry.split ("=", 2);
if (tokens.length != 2)
throw new Error.INVALID_ARGUMENT ("Invalid environment variable entry: %s", entry);
env_val.set_value (tokens[0], new NSString (tokens[1]));
}
var opts_val = new NSDictionary ();
opts_val.set_value ("StartSuspendedKey", new NSNumber.from_boolean (opts.launch_mode == SUSPENDED));
opts_val.set_value ("KillExisting", new NSNumber.from_boolean (opts.existing_instance_policy == KILL));
// TODO: Support CaptureOutput + iODestinationKey
var dtx_args = new DTXArgumentListBuilder ()
.append_object (new NSString (""))
.append_object (new NSString (bundle_id))
.append_object (env_val)
.append_object (args_val)
.append_object (opts_val);
var response = yield channel.invoke (
"launchSuspendedProcessWithDevicePath:bundleIdentifier:environment:arguments:options:",
dtx_args, cancellable);
NSNumber? pid = response as NSNumber;
if (pid == null)
throw new Error.PROTOCOL ("Malformed response");
return (uint) pid.integer;
}
public async void kill (uint pid, Cancellable? cancellable = null) throws Error, IOError {
var args = new DTXArgumentListBuilder ()
.append_object (new NSNumber.from_integer (pid));
yield channel.invoke ("killPid:", args, cancellable);
}
public async void send_signal (uint pid, uint sig, Cancellable? cancellable = null) throws Error, IOError {
var args = new DTXArgumentListBuilder ()
.append_object (new NSNumber.from_integer (sig))
.append_object (new NSNumber.from_integer (pid));
yield channel.invoke ("sendSignal:toPid:", args, cancellable);
}
private void on_invocation (string method_name, DTXArgumentList args, DTXMessageTransportFlags transport_flags) {
if (method_name == "processWithPID:terminatedWithExitCode:orCrashingSignal:") {
if (args.elements.length != 3)
return;
uint pid;
if (!try_parse_int (args.elements[0], out pid))
return;
int exit_code = -1;
int crashing_signal = -1;
if (!try_parse_int (args.elements[1], out exit_code)) {
if (!try_parse_int (args.elements[2], out crashing_signal))
return;
}
process_terminated (pid, exit_code, crashing_signal);
}
}
private bool try_parse_int (Value v, out int i) {
i = -1;
if (!v.holds (typeof (NSNumber)))
return false;
i = (int) ((NSNumber) v.get_object ()).integer;
return true;
}
}
public sealed class LaunchOptions : Object {
public string[] arguments {
get;
set;
default = {};
}
public string[] environment {
get;
set;
default = {};
}
public LaunchMode launch_mode {
get;
set;
default = LaunchMode.NORMAL;
}
public ExistingInstancePolicy existing_instance_policy {
get;
set;
default = ExistingInstancePolicy.KEEP;
}
}
public enum LaunchMode {
NORMAL,
SUSPENDED
}
public enum ExistingInstancePolicy {
KEEP,
KILL
}
public sealed class CoreProfileService : Object, AsyncInitable {
public signal void stackshot (Bytes blob);
public signal void kperfdata (Bytes blob);
public HostChannelProvider channel_provider {
get;
construct;
}
private DTXChannel channel;
private CoreProfileService (HostChannelProvider channel_provider) {
Object (channel_provider: channel_provider);
}
public static async CoreProfileService open (HostChannelProvider channel_provider, Cancellable? cancellable = null)
throws Error, IOError {
var service = new CoreProfileService (channel_provider);
try {
yield service.init_async (Priority.DEFAULT, cancellable);
} catch (GLib.Error e) {
throw_api_error (e);
}
return service;
}
private async bool init_async (int io_priority, Cancellable? cancellable) throws Error, IOError {
var connection = yield DTXConnection.obtain (channel_provider, cancellable);
channel = connection.make_channel ("com.apple.instruments.server.services.coreprofilesessiontap");
channel.notification.connect (on_notification);
channel.data.connect (on_data);
return true;
}
public async void set_config (KtraceConfig config, Cancellable? cancellable = null) throws Error, IOError {
var args = new DTXArgumentListBuilder ()
.append_object (config.encode ());
yield channel.invoke ("setConfig:", args, cancellable);
}
public async void start (Cancellable? cancellable = null) throws Error, IOError {
yield channel.invoke ("start", null, cancellable);
}
public async void stop (Cancellable? cancellable = null) throws Error, IOError {
yield channel.invoke ("stop", null, cancellable);
}
private void on_notification (NSObject obj) {
// printerr ("on_notification(): %s\n", obj.to_string ());
}
private void on_data (Bytes blob) {
if (Kcdata.is_stackshot (blob))
stackshot (blob);
else
kperfdata (blob);
}
}
public abstract class TapConfig : Object {
public TapRecordingMode buffer_mode {
get {
return _buffer_mode;
}
set {
_buffer_mode = value;
if (value != POLLED)
_polling_interval = 0;
}
}
public uint64 polling_interval {
get;
set;
default = 500;
}
public uint64 window_size {
get;
set;
default = 0;
}
public bool spool_to_disk_when_possible {
get;
set;
default = false;
}
public bool discard_heartbeats_when_possible {
get;
set;
default = false;
}
private TapRecordingMode _buffer_mode = POLLED;
internal virtual NSDictionary encode () {
var dict = new NSDictionary ();
dict.set_value ("bm", new NSNumber.from_integer (_buffer_mode));
if (_polling_interval != 0)
dict.set_value ("ur", new NSNumber.from_integer ((int64) _polling_interval));
if (_window_size != 0)
dict.set_value ("ws", new NSNumber.from_integer ((int64) _window_size));
if (_spool_to_disk_when_possible)
dict.set_value ("s2d", new NSNumber.from_boolean (true));
if (_discard_heartbeats_when_possible)
dict.set_value ("nohb", new NSNumber.from_boolean (true));
return dict;
}
}
public enum TapRecordingMode {
POLLED,
IMMEDIATE,
WINDOWED,
}
public sealed class KtraceConfig : TapConfig {
public bool can_use_raw_ktrace_file {
get;
set;
default = false;
}
public KtraceRecordingPriority recording_priority {
get;
set;
default = FOREGROUND;
}
public uint collection_interval {
get;
set;
default = 0;
}
public uint64 buffer_size_override {
get;
set;
default = 0;
}
public uint64 buffer_size_override_clamping {
get;
set;
default = 0;
}
public NSDictionary? provider_options {
get;
set;
default = null;
}
private Gee.List<KtraceTapTriggerConfig> trigger_configs = new Gee.ArrayList<KtraceTapTriggerConfig> ();
public void add_trigger_config (KtraceTapTriggerConfig tc) {
trigger_configs.add (tc);
}
internal override NSDictionary encode () {
var dict = base.encode ();
if (can_use_raw_ktrace_file)
dict.set_value ("curkt", new NSNumber.from_boolean (true));
dict.set_value ("rp", new NSNumber.from_integer (_recording_priority));
if (_collection_interval != 0)
dict.set_value ("kco", new NSNumber.from_integer (_collection_interval));
if (_buffer_size_override != 0)
dict.set_value ("bso", new NSNumber.from_integer ((int64) _buffer_size_override));
if (_buffer_size_override_clamping != 0)
dict.set_value ("bsoc", new NSNumber.from_integer ((int64) _buffer_size_override_clamping));
if (_provider_options != null)
dict.set_value ("po", _provider_options);
var tc = new NSArray ();
foreach (var cfg in trigger_configs)
tc.add_object (cfg.encode ());
dict.set_value ("tc", tc);
return dict;
}
}
public enum KtraceRecordingPriority {
BACKGROUND = 10,
FOREGROUND = 100,
}
public sealed class KtraceTapTriggerConfig : Object {
public KtraceTapTriggerKind kind {
get;
construct;
}
public KdebugCodeSet? filter {
get;
set;
}
public bool is_all_processes {
get {
return included_pids == null;
}
set {
if (value)
included_pids = null;
else
ensure_included_pids ();
}
}
public uint callstack_frame_depth {
get;
set;
default = 0;
}
public KtraceTapActions actions {
get;
default = new KtraceTapActions ();
}
private Gee.Set<uint>? included_pids = null;
public KtraceTapTriggerConfig (KtraceTapTriggerKind kind) {
Object (kind: kind);
}
public void include_pid (uint pid) {
ensure_included_pids ().add (pid);
}
private unowned Gee.Set<uint> ensure_included_pids () {
if (included_pids == null)
included_pids = new Gee.HashSet<uint> ();
return included_pids;
}
internal NSDictionary encode () {
var dict = new NSDictionary ();
dict.set_value ("uuid", new NSString (Uuid.string_random ().up ()));
dict.set_value ("tk", new NSNumber.from_integer (_kind));
if (_filter != null) {
dict.set_value ("kdf", new NSString (_filter.legacy_xml));
dict.set_value ("kdf2", _filter.kdebug_codes);
}
if (included_pids != null) {
var pf = new NSArray ();
foreach (var pid in included_pids)
pf.add_object (new NSNumber.from_integer (pid));
dict.set_value ("pf", pf);
}
if (_callstack_frame_depth != 0)
dict.set_value ("csd", new NSNumber.from_integer (_callstack_frame_depth));
var actions = _actions.items;
if (!actions.is_empty) {
var arr = new NSArray ();
foreach (var action in actions)
arr.add_object (action.encode ());
dict.set_value ("ta", arr);
}
return dict;
}
}
public enum KtraceTapTriggerKind {
TIME = 1,
PMI,
KDEBUG,
}
public sealed class KtraceTapActions : Object {
internal Gee.List<KtraceTapAction> items = new Gee.ArrayList<KtraceTapAction> ();
public unowned KtraceTapActions add (KtraceTapAction action) {
items.add (action);
return this;
}
public unowned KtraceTapActions add_stack_collection (KtraceTapStackCollectionMode mode) {
items.add (new KtraceTapStackCollectionAction (mode));
return this;
}
public unowned KtraceTapActions add_baseline () {
items.add (new KtraceTapAction0 ());
items.add (new KtraceTapAction2 ());
return this;
}
public unowned KtraceTapActions add_pmc_event (string event_name, string counter_name, uint32 extra = 0) {
items.add (new KtraceTapAddPmcEventAction (event_name, counter_name, extra));
return this;
}
public unowned KtraceTapActions add_kdebug_codeset (KdebugCodeSet codeset) {
items.add (new KtraceTapAddKdebugCodeSetAction (codeset.kdebug_codes));
return this;
}
public unowned KtraceTapActions add_kdebug_legacy_backtrace_filter () {
items.add (new KtraceTapKdebugBacktraceFilterAction ());
return this;
}
}
public enum KtraceTapActionKind {
ACTION0,
STACK_COLLECTION,
ACTION2,
KDEBUG_BACKTRACE_FILTER,
ADD_PMC_EVENT,
ADD_KDEBUG_CODESET,
}
public abstract class KtraceTapAction : Object {
public abstract KtraceTapActionKind kind {
get;
}
internal abstract NSArray encode ();
}
public sealed class KtraceTapAction0 : KtraceTapAction {
public override KtraceTapActionKind kind {
get {
return ACTION0;
}
}
internal override NSArray encode () {
var a = new NSArray ();
a.add_object (new NSNumber.from_integer (kind));
return a;
}
}
public sealed class KtraceTapAction2 : KtraceTapAction {
public override KtraceTapActionKind kind {
get {
return ACTION2;
}
}
internal override NSArray encode () {
var a = new NSArray ();
a.add_object (new NSNumber.from_integer (kind));
return a;
}
}
public sealed class KtraceTapStackCollectionAction : KtraceTapAction {
public KtraceTapStackCollectionMode mode {
get {
return _mode;
}
set {
_mode = value;
}
}
private KtraceTapStackCollectionMode _mode;
public KtraceTapStackCollectionAction (KtraceTapStackCollectionMode mode) {
_mode = mode;
}
public override KtraceTapActionKind kind {
get {
return STACK_COLLECTION;
}
}
internal override NSArray encode () {
var a = new NSArray ();
a.add_object (new NSNumber.from_integer (kind));
a.add_object (new NSNumber.from_boolean ((_mode & KtraceTapStackCollectionMode.USER) != 0));
a.add_object (new NSNumber.from_boolean ((_mode & KtraceTapStackCollectionMode.KERNEL) != 0));
return a;
}
}
[Flags]
public enum KtraceTapStackCollectionMode {
NONE = 0,
USER = (1 << 0),
KERNEL = (1 << 1),
}
public sealed class KtraceTapKdebugBacktraceFilterAction : KtraceTapAction {
public override KtraceTapActionKind kind {
get {
return KDEBUG_BACKTRACE_FILTER;
}
}
internal override NSArray encode () {
var a = new NSArray ();
a.add_object (new NSNumber.from_integer (kind));
return a;
}
}
public sealed class KtraceTapAddPmcEventAction : KtraceTapAction {
public string event_name {
get {
return _event_name;
}
set {
_event_name = value;
}
}
public string counter_name {
get {
return _counter_name;
}
set {
_counter_name = value;
}
}
public uint32 extra {
get {
return _extra;
}
set {
_extra = value;
}
}
private string _event_name;
private string _counter_name;
private uint32 _extra;
public KtraceTapAddPmcEventAction (string event_name, string counter_name, uint32 extra = 0) {
_event_name = event_name;
_counter_name = counter_name;
_extra = extra;
}
public override KtraceTapActionKind kind {
get {
return ADD_PMC_EVENT;
}
}
internal override NSArray encode () {
var a = new NSArray ();
a.add_object (new NSNumber.from_integer (kind));
a.add_object (new NSString (_event_name));
a.add_object (new NSString (_counter_name));
a.add_object (new NSNumber.from_integer (_extra));
return a;
}
}
public sealed class KtraceTapAddKdebugCodeSetAction : KtraceTapAction {
public NSSet codes {
get {
return _codes;
}
set {
_codes = value;
}
}
private NSSet _codes;
public KtraceTapAddKdebugCodeSetAction (NSSet codes) {
_codes = codes;
}
public override KtraceTapActionKind kind {
get {
return ADD_KDEBUG_CODESET;
}
}
internal override NSArray encode () {
var a = new NSArray ();
a.add_object (new NSNumber.from_integer (kind));
a.add_object (_codes);
return a;
}
}
public sealed class KdebugCodeSet : Object {
public string legacy_xml {
owned get {
var xml = new StringBuilder.sized (256);
xml.append ("<events>");
foreach (var c in codes) {
var kc = KdebugCode (c);
xml.append ("<event type=\"KDebug\" class=\"");
var klass = kc.klass;
if (klass == ANY)
xml.append_c ('*');
else
xml.append_printf ("%u", klass);
xml.append ("\" subclass=\"");
var subclass = kc.subclass;
if (subclass == KDEBUG_SUBCLASS_ANY)
xml.append_c ('*');
else
xml.append_printf ("%u", subclass);
xml.append ("\" code=\"");
uint code = kc.code;
if (code == KDEBUG_CODE_ANY)
xml.append_c ('*');
else
xml.append_printf ("%u", code);
xml.append ("\"/>");
}
xml.append ("</events>");
return xml.str;
}
}
public NSSet kdebug_codes {
get {
if (_kdebug_codes == null) {
_kdebug_codes = new NSSet ();
foreach (var c in codes)
_kdebug_codes.add_object (new NSNumber.from_integer (c));
}
return _kdebug_codes;
}
}
private Gee.Set<uint> codes = new Gee.HashSet<uint> ();
private NSSet _kdebug_codes = null;
public KdebugCodeSet copy () {
var s = new KdebugCodeSet ();
s.codes.add_all (codes);
s._kdebug_codes = _kdebug_codes;
return s;
}
public unowned KdebugCodeSet add (KdebugCode code) {
codes.add (code.raw);
_kdebug_codes = null;
return this;
}
}
public sealed class DTXConnection : Object, DTXTransport {
@@ -373,7 +1120,6 @@ namespace Frida.Fruity {
private Gee.HashMap<uint32, Gee.ArrayList<Fragment>> fragments = new Gee.HashMap<uint32, Gee.ArrayList<Fragment>> ();
private uint32 next_fragment_identifier = 1;
private size_t total_buffered = 0;
private Gee.ArrayQueue<Bytes> pending_writes = new Gee.ArrayQueue<Bytes> ();
private DTXControlChannel control_channel;
@@ -381,8 +1127,6 @@ namespace Frida.Fruity {
private int32 next_channel_code = 1;
private const uint32 DTX_FRAGMENT_MAGIC = 0x1f3d5b79U;
private const uint MAX_BUFFERED_COUNT = 100;
private const size_t MAX_BUFFERED_SIZE = 30 * 1024 * 1024;
private const size_t MAX_MESSAGE_SIZE = 128 * 1024 * 1024;
private const size_t MAX_FRAGMENT_SIZE = 128 * 1024;
private const string REMOTESERVER_ENDPOINT_17PLUS = "lockdown:com.apple.instruments.dtservicehub";
@@ -566,8 +1310,6 @@ namespace Frida.Fruity {
Gee.ArrayList<Fragment> entries = fragments[fragment.identifier];
if (entries == null) {
if (fragments.size == MAX_BUFFERED_COUNT)
throw new Error.PROTOCOL ("Total buffered count exceeds maximum");
if (fragment.index != 0)
throw new Error.PROTOCOL ("Expected first fragment to have index of zero");
fragment.data_size = 0;
@@ -585,10 +1327,6 @@ namespace Frida.Fruity {
first_fragment.data_size += (uint32) size;
if (first_fragment.data_size > MAX_MESSAGE_SIZE)
throw new Error.PROTOCOL ("Message size exceeds maximum");
total_buffered += size;
if (total_buffered > MAX_BUFFERED_SIZE)
throw new Error.PROTOCOL ("Total buffered size exceeds maximum");
}
if (entries.size == fragment.count) {
@@ -614,7 +1352,6 @@ namespace Frida.Fruity {
}
fragments.unset (fragment.identifier);
total_buffered -= message.length;
process_message (message, first_fragment);
}
@@ -714,33 +1451,37 @@ namespace Frida.Fruity {
message.payload_data = raw_message[payload_start_offset:payload_end_offset];
int32 channel_code = message.channel_code;
bool is_notification = false;
if (message.type == INVOKE) {
if ((message.conversation_index % 2) == 0)
channel_code = -channel_code;
} else if (message.type == RESULT && channel_code < 0) {
channel_code = -channel_code;
is_notification = true;
}
bool is_notification = message.conversation_index == 0;
var channel = channels[channel_code];
if (channel == null)
return;
switch (message.type) {
case INVOKE:
channel.handle_invoke (message);
case DISPATCH:
channel.handle_dispatch (message);
break;
case OK:
case RESULT:
case OBJECT:
case ERROR:
if (is_notification)
channel.handle_notification (message);
else
channel.handle_response (message);
break;
case DATA:
channel.handle_data (message);
break;
case BARRIER:
channel.handle_barrier (message);
break;
case PRIMITIVE:
case COMPRESSED:
case PROXIED_MESSAGE:
throw new Error.PROTOCOL ("Unsupported message type: %s", message.type.to_string ());
}
}
@@ -855,7 +1596,8 @@ namespace Frida.Fruity {
public void notify_of_published_capabilities () throws Error {
var capabilities = new NSDictionary ();
capabilities.set_value ("com.apple.private.DTXConnection", new NSNumber.from_integer (1));
capabilities.set_value ("com.apple.private.DTXBlockCompression", new NSNumber.from_integer (2));
capabilities.set_value ("com.apple.instruments.client.processcontrol.capability.terminationCallback",
new NSNumber.from_integer (1));
var args = new DTXArgumentListBuilder ()
.append_object (capabilities);
@@ -879,6 +1621,7 @@ namespace Frida.Fruity {
public class DTXChannel : Object {
public signal void invocation (string method_name, DTXArgumentList args, DTXMessageTransportFlags transport_flags);
public signal void notification (NSObject obj);
public signal void data (Bytes blob);
public signal void barrier ();
public int32 code {
@@ -935,7 +1678,7 @@ namespace Frida.Fruity {
check_open ();
var message = DTXMessage ();
message.type = INVOKE;
message.type = DISPATCH;
message.channel_code = code;
message.transport_flags = EXPECTS_REPLY;
@@ -965,7 +1708,7 @@ namespace Frida.Fruity {
check_open ();
var message = DTXMessage ();
message.type = INVOKE;
message.type = DISPATCH;
message.channel_code = code;
message.transport_flags = NONE;
@@ -982,10 +1725,10 @@ namespace Frida.Fruity {
transport.send_message (message, out identifier);
}
internal void handle_invoke (DTXMessage message) throws Error {
internal void handle_dispatch (DTXMessage message) throws Error {
NSString? method_name = NSKeyedArchive.decode (message.payload_data) as NSString;
if (method_name == null)
throw new Error.PROTOCOL ("Malformed invocation payload");
throw new Error.PROTOCOL ("Malformed dispatch payload");
var args = DTXArgumentList.parse (message.aux_data);
@@ -999,7 +1742,7 @@ namespace Frida.Fruity {
case OK:
request.resolve (null);
break;
case RESULT:
case OBJECT:
request.resolve (NSKeyedArchive.decode (message.payload_data));
break;
case ERROR: {
@@ -1037,6 +1780,10 @@ namespace Frida.Fruity {
notification (payload);
}
internal void handle_data (DTXMessage message) throws Error {
data (new Bytes (message.payload_data));
}
internal void handle_barrier (DTXMessage message) throws Error {
barrier ();
}
@@ -1053,11 +1800,15 @@ namespace Frida.Fruity {
}
public enum DTXMessageType {
OK = 0,
INVOKE = 2,
RESULT = 3,
ERROR = 4,
BARRIER = 5
OK,
DATA,
DISPATCH,
OBJECT,
ERROR,
BARRIER,
PRIMITIVE,
COMPRESSED,
PROXIED_MESSAGE,
}
public struct DTXMessage {
@@ -1111,6 +1862,12 @@ namespace Frida.Fruity {
}
case BUFFER: {
size_t size = reader.read_uint32 ();
if (size == 0) {
var gval = Value (typeof (NSObject));
elements += (owned) gval;
break;
}
unowned uint8[] buf = reader.read_byte_array (size);
NSObject? obj = NSKeyedArchive.decode (buf);
File diff suppressed because it is too large. Load diff
+22 -9
View File
@@ -186,8 +186,14 @@ namespace Frida.Fruity.Injector {
}
private async void teardown (Cancellable? cancellable) throws GLib.Error {
yield lldb.deallocate (scratch_page, cancellable);
yield lldb.deallocate (jit_page, cancellable);
try {
yield lldb.deallocate (scratch_page, cancellable);
} catch (Error e) {
}
try {
yield lldb.deallocate (jit_page, cancellable);
} catch (Error e) {
}
yield restore_main_thread_state (cancellable);
}
@@ -893,11 +899,14 @@ namespace Frida.Fruity.Injector {
uint64 initializer = (notify_objc_init != null) ? notify_objc_init : libdyld_initialize;
GDB.Breakpoint init_breakpoint = yield lldb.add_breakpoint (SOFT, initializer, 4, cancellable);
GDB.Breakpoint? restart_breakpoint = null;
uint64? restart_with_dyld_in_cache = dyld_symbols["__ZN5dyld422restartWithDyldInCacheEPKNS_10KernelArgsEPKN6mach_o6HeaderEPK15DyldSharedCachePv"];
if (restart_with_dyld_in_cache == null)
restart_with_dyld_in_cache = dyld_symbols["__ZN5dyld422restartWithDyldInCacheEPKNS_10KernelArgsEPKN5dyld39MachOFileEPK15DyldSharedCachePv"];
if (restart_with_dyld_in_cache == null)
restart_with_dyld_in_cache = dyld_symbols["__ZN5dyld422restartWithDyldInCacheEPKNS_10KernelArgsEPKN5dyld39MachOFileEPv"];
uint64? restart_with_dyld_in_cache = null;
foreach (var e in dyld_symbols.entries) {
if (e.key.contains ("restartWithDyldInCache")) {
restart_with_dyld_in_cache = e.value;
break;
}
}
if (restart_with_dyld_in_cache != null)
restart_breakpoint = yield lldb.add_breakpoint (SOFT, restart_with_dyld_in_cache, 4, cancellable);
@@ -1374,8 +1383,12 @@ namespace Frida.Fruity.Injector {
}
}
if (state != scratch_page)
yield lldb.deallocate (state, cancellable);
if (state != scratch_page) {
try {
yield lldb.deallocate (state, cancellable);
} catch (Error e) {
}
}
return new SymbolSet (symbols);
}
+558
View File
@@ -0,0 +1,558 @@
[CCode (gir_namespace = "FridaFruity", gir_version = "1.0")]
namespace Frida.Fruity.Kcdata {
public struct ItemHeader {
public ItemType type;
public uint32 size;
public uint64 flags;
}
public enum ItemType {
INVALID = 0x000u,
STRING_DESC = 0x001u,
UINT32_DESC = 0x002u,
UINT64_DESC = 0x003u,
INT32_DESC = 0x004u,
INT64_DESC = 0x005u,
BINDATA_DESC = 0x006u,
ARRAY = 0x011u,
TYPEDEFINTION = 0x012u,
CONTAINER_BEGIN = 0x013u,
CONTAINER_END = 0x014u,
ARRAY_PAD0 = 0x020u,
ARRAY_PAD1 = 0x021u,
ARRAY_PAD2 = 0x022u,
ARRAY_PAD3 = 0x023u,
ARRAY_PAD4 = 0x024u,
ARRAY_PAD5 = 0x025u,
ARRAY_PAD6 = 0x026u,
ARRAY_PAD7 = 0x027u,
ARRAY_PAD8 = 0x028u,
ARRAY_PAD9 = 0x029u,
ARRAY_PADa = 0x02au,
ARRAY_PADb = 0x02bu,
ARRAY_PADc = 0x02cu,
ARRAY_PADd = 0x02du,
ARRAY_PADe = 0x02eu,
ARRAY_PADf = 0x02fu,
LIBRARY_LOADINFO = 0x030u,
LIBRARY_LOADINFO64 = 0x031u,
TIMEBASE = 0x032u,
MACH_ABSOLUTE_TIME = 0x033u,
TIMEVAL = 0x034u,
USECS_SINCE_EPOCH = 0x035u,
PID = 0x036u,
PROCNAME = 0x037u,
NESTED_KCDATA = 0x038u,
LIBRARY_AOTINFO = 0x039u,
TASK_CRASHINFO_EXTMODINFO = 0x801u,
TASK_CRASHINFO_BSDINFOWITHUNIQID = 0x802u,
TASK_CRASHINFO_TASKDYLD_INFO = 0x803u,
TASK_CRASHINFO_UUID = 0x804u,
TASK_CRASHINFO_PID = 0x805u,
TASK_CRASHINFO_PPID = 0x806u,
TASK_CRASHINFO_RUSAGE = 0x807u,
TASK_CRASHINFO_RUSAGE_INFO = 0x808u,
TASK_CRASHINFO_PROC_NAME = 0x809u,
TASK_CRASHINFO_PROC_STARTTIME = 0x80Bu,
TASK_CRASHINFO_USERSTACK = 0x80Cu,
TASK_CRASHINFO_ARGSLEN = 0x80Du,
TASK_CRASHINFO_EXCEPTION_CODES = 0x80Eu,
TASK_CRASHINFO_PROC_PATH = 0x80Fu,
TASK_CRASHINFO_PROC_CSFLAGS = 0x810u,
TASK_CRASHINFO_PROC_STATUS = 0x811u,
TASK_CRASHINFO_UID = 0x812u,
TASK_CRASHINFO_GID = 0x813u,
TASK_CRASHINFO_PROC_ARGC = 0x814u,
TASK_CRASHINFO_PROC_FLAGS = 0x815u,
TASK_CRASHINFO_CPUTYPE = 0x816u,
TASK_CRASHINFO_WORKQUEUEINFO = 0x817u,
TASK_CRASHINFO_RESPONSIBLE_PID = 0x818u,
TASK_CRASHINFO_DIRTY_FLAGS = 0x819u,
TASK_CRASHINFO_CRASHED_THREADID = 0x81Au,
TASK_CRASHINFO_COALITION_ID = 0x81Bu,
TASK_CRASHINFO_UDATA_PTRS = 0x81Cu,
TASK_CRASHINFO_MEMORY_LIMIT = 0x81Du,
TASK_CRASHINFO_LEDGER_INTERNAL = 0x81Eu,
TASK_CRASHINFO_LEDGER_INTERNAL_COMPRESSED = 0x81Fu,
TASK_CRASHINFO_LEDGER_IOKIT_MAPPED = 0x820u,
TASK_CRASHINFO_LEDGER_ALTERNATE_ACCOUNTING = 0x821u,
TASK_CRASHINFO_LEDGER_ALTERNATE_ACCOUNTING_COMPRESSED = 0x822u,
TASK_CRASHINFO_LEDGER_PURGEABLE_NONVOLATILE = 0x823u,
TASK_CRASHINFO_LEDGER_PURGEABLE_NONVOLATILE_COMPRESSED = 0x824u,
TASK_CRASHINFO_LEDGER_PAGE_TABLE = 0x825u,
TASK_CRASHINFO_LEDGER_PHYS_FOOTPRINT = 0x826u,
TASK_CRASHINFO_LEDGER_PHYS_FOOTPRINT_LIFETIME_MAX = 0x827u,
TASK_CRASHINFO_LEDGER_NETWORK_NONVOLATILE = 0x828u,
TASK_CRASHINFO_LEDGER_NETWORK_NONVOLATILE_COMPRESSED = 0x829u,
TASK_CRASHINFO_LEDGER_WIRED_MEM = 0x82Au,
TASK_CRASHINFO_PROC_PERSONA_ID = 0x82Bu,
TASK_CRASHINFO_MEMORY_LIMIT_INCREASE = 0x82Cu,
TASK_CRASHINFO_LEDGER_TAGGED_FOOTPRINT = 0x82Du,
TASK_CRASHINFO_LEDGER_TAGGED_FOOTPRINT_COMPRESSED = 0x82Eu,
TASK_CRASHINFO_LEDGER_MEDIA_FOOTPRINT = 0x82Fu,
TASK_CRASHINFO_LEDGER_MEDIA_FOOTPRINT_COMPRESSED = 0x830u,
TASK_CRASHINFO_LEDGER_GRAPHICS_FOOTPRINT = 0x831u,
TASK_CRASHINFO_LEDGER_GRAPHICS_FOOTPRINT_COMPRESSED = 0x832u,
TASK_CRASHINFO_LEDGER_NEURAL_FOOTPRINT = 0x833u,
TASK_CRASHINFO_LEDGER_NEURAL_FOOTPRINT_COMPRESSED = 0x834u,
TASK_CRASHINFO_MEMORYSTATUS_EFFECTIVE_PRIORITY = 0x835u,
TASK_CRASHINFO_KERNEL_TRIAGE_INFO_V1 = 0x836u,
TASK_CRASHINFO_TASK_IS_CORPSE_FORK = 0x837u,
TASK_CRASHINFO_EXCEPTION_TYPE = 0x838u,
TASK_CRASHINFO_CRASH_COUNT = 0x839u,
TASK_CRASHINFO_THROTTLE_TIMEOUT = 0x83Au,
TASK_CRASHINFO_CS_SIGNING_ID = 0x83Bu,
TASK_CRASHINFO_CS_TEAM_ID = 0x83Cu,
TASK_CRASHINFO_CS_VALIDATION_CATEGORY = 0x83Du,
TASK_CRASHINFO_CS_TRUST_LEVEL = 0x83Eu,
TASK_CRASHINFO_PROC_CPUTYPE = 0x83Fu,
TASK_CRASHINFO_JIT_ADDRESS_RANGE = 0x840u,
TASK_CRASHINFO_MB = 0x841u,
TASK_CRASHINFO_CS_AUXILIARY_INFO = 0x842u,
TASK_CRASHINFO_RLIM_CORE = 0x843u,
TASK_CRASHINFO_CORE_ALLOWED = 0x844u,
TASK_CRASHINFO_TASK_SECURITY_CONFIG = 0x845u,
STACKSHOT_IOSTATS = 0x901u,
STACKSHOT_GLOBAL_MEM_STATS = 0x902u,
STACKSHOT_CONTAINER_TASK = 0x903u,
STACKSHOT_CONTAINER_THREAD = 0x904u,
STACKSHOT_TASK_SNAPSHOT = 0x905u,
STACKSHOT_THREAD_SNAPSHOT = 0x906u,
STACKSHOT_DONATING_PIDS = 0x907u,
STACKSHOT_SHAREDCACHE_LOADINFO = 0x908u,
STACKSHOT_THREAD_NAME = 0x909u,
STACKSHOT_KERN_STACKFRAME = 0x90Au,
STACKSHOT_KERN_STACKFRAME64 = 0x90Bu,
STACKSHOT_USER_STACKFRAME = 0x90Cu,
STACKSHOT_USER_STACKFRAME64 = 0x90Du,
STACKSHOT_BOOTARGS = 0x90Eu,
STACKSHOT_OSVERSION = 0x90Fu,
STACKSHOT_KERN_PAGE_SIZE = 0x910u,
STACKSHOT_JETSAM_LEVEL = 0x911u,
STACKSHOT_DELTA_SINCE_TIMESTAMP = 0x912u,
STACKSHOT_KERN_STACKLR = 0x913u,
STACKSHOT_KERN_STACKLR64 = 0x914u,
STACKSHOT_USER_STACKLR = 0x915u,
STACKSHOT_USER_STACKLR64 = 0x916u,
STACKSHOT_NONRUNNABLE_TIDS = 0x917u,
STACKSHOT_NONRUNNABLE_TASKS = 0x918u,
STACKSHOT_CPU_TIMES = 0x919u,
STACKSHOT_STACKSHOT_DURATION = 0x91au,
STACKSHOT_STACKSHOT_FAULT_STATS = 0x91bu,
STACKSHOT_KERNELCACHE_LOADINFO = 0x91cu,
STACKSHOT_THREAD_WAITINFO = 0x91du,
STACKSHOT_THREAD_GROUP_SNAPSHOT = 0x91eu,
STACKSHOT_THREAD_GROUP = 0x91fu,
STACKSHOT_JETSAM_COALITION_SNAPSHOT = 0x920u,
STACKSHOT_JETSAM_COALITION = 0x921u,
STACKSHOT_THREAD_POLICY_VERSION = 0x922u,
STACKSHOT_INSTRS_CYCLES = 0x923u,
STACKSHOT_USER_STACKTOP = 0x924u,
STACKSHOT_ASID = 0x925u,
STACKSHOT_PAGE_TABLES = 0x926u,
STACKSHOT_SYS_SHAREDCACHE_LAYOUT = 0x927u,
STACKSHOT_THREAD_DISPATCH_QUEUE_LABEL = 0x928u,
STACKSHOT_THREAD_TURNSTILEINFO = 0x929u,
STACKSHOT_TASK_CPU_ARCHITECTURE = 0x92au,
STACKSHOT_LATENCY_INFO = 0x92bu,
STACKSHOT_LATENCY_INFO_TASK = 0x92cu,
STACKSHOT_LATENCY_INFO_THREAD = 0x92du,
STACKSHOT_LOADINFO64_TEXT_EXEC = 0x92eu,
STACKSHOT_AOTCACHE_LOADINFO = 0x92fu,
STACKSHOT_TRANSITIONING_TASK_SNAPSHOT = 0x930u,
STACKSHOT_CONTAINER_TRANSITIONING_TASK = 0x931u,
STACKSHOT_USER_ASYNC_START_INDEX = 0x932u,
STACKSHOT_USER_ASYNC_STACKLR64 = 0x933u,
STACKSHOT_CONTAINER_PORTLABEL = 0x934u,
STACKSHOT_PORTLABEL = 0x935u,
STACKSHOT_PORTLABEL_NAME = 0x936u,
STACKSHOT_DYLD_COMPACTINFO = 0x937u,
STACKSHOT_SUSPENSION_INFO = 0x938u,
STACKSHOT_SUSPENSION_SOURCE = 0x939u,
STACKSHOT_TASK_DELTA_SNAPSHOT = 0x940u,
STACKSHOT_THREAD_DELTA_SNAPSHOT = 0x941u,
STACKSHOT_CONTAINER_SHAREDCACHE = 0x942u,
STACKSHOT_SHAREDCACHE_INFO = 0x943u,
STACKSHOT_SHAREDCACHE_AOTINFO = 0x944u,
STACKSHOT_SHAREDCACHE_ID = 0x945u,
STACKSHOT_CODESIGNING_INFO = 0x946u,
STACKSHOT_OS_BUILD_VERSION = 0x947u,
STACKSHOT_KERN_EXCLAVES_THREADINFO = 0x948u,
STACKSHOT_CONTAINER_EXCLAVES = 0x949u,
STACKSHOT_CONTAINER_EXCLAVE_SCRESULT = 0x94au,
STACKSHOT_EXCLAVE_SCRESULT_INFO = 0x94bu,
STACKSHOT_CONTAINER_EXCLAVE_IPCSTACKENTRY = 0x94cu,
STACKSHOT_EXCLAVE_IPCSTACKENTRY_INFO = 0x94du,
STACKSHOT_EXCLAVE_IPCSTACKENTRY_ECSTACK = 0x94eu,
STACKSHOT_CONTAINER_EXCLAVE_ADDRESSSPACE = 0x94fu,
STACKSHOT_EXCLAVE_ADDRESSSPACE_INFO = 0x950u,
STACKSHOT_EXCLAVE_ADDRESSSPACE_NAME = 0x951u,
STACKSHOT_CONTAINER_EXCLAVE_TEXTLAYOUT = 0x952u,
STACKSHOT_EXCLAVE_TEXTLAYOUT_INFO = 0x953u,
STACKSHOT_EXCLAVE_TEXTLAYOUT_SEGMENTS = 0x954u,
STACKSHOT_KERN_EXCLAVES_CRASH_THREADINFO = 0x955u,
STACKSHOT_LATENCY_INFO_CPU = 0x956u,
STACKSHOT_TASK_EXEC_META = 0x957u,
STACKSHOT_TASK_MEMORYSTATUS = 0x958u,
STACKSHOT_LATENCY_INFO_BUFFER = 0x95au,
TASK_BTINFO_PID = 0xA01u,
TASK_BTINFO_PPID = 0xA02u,
TASK_BTINFO_PROC_NAME = 0xA03u,
TASK_BTINFO_PROC_PATH = 0xA04u,
TASK_BTINFO_UID = 0xA05u,
TASK_BTINFO_GID = 0xA06u,
TASK_BTINFO_PROC_FLAGS = 0xA07u,
TASK_BTINFO_CPUTYPE = 0xA08u,
TASK_BTINFO_EXCEPTION_CODES = 0xA09u,
TASK_BTINFO_EXCEPTION_TYPE = 0xA0Au,
TASK_BTINFO_RUSAGE_INFO = 0xA0Bu,
TASK_BTINFO_COALITION_ID = 0xA0Cu,
TASK_BTINFO_CRASH_COUNT = 0xA0Du,
TASK_BTINFO_THROTTLE_TIMEOUT = 0xA0Eu,
TASK_BTINFO_THREAD_ID = 0xA20u,
TASK_BTINFO_THREAD_NAME = 0xA21u,
TASK_BTINFO_THREAD_STATE = 0xA22u,
TASK_BTINFO_THREAD_EXCEPTION_STATE = 0xA23u,
TASK_BTINFO_BACKTRACE = 0xA24u,
TASK_BTINFO_BACKTRACE64 = 0xA25u,
TASK_BTINFO_ASYNC_BACKTRACE64 = 0xA26u,
TASK_BTINFO_ASYNC_START_INDEX = 0xA27u,
TASK_BTINFO_PLATFORM = 0xA28u,
TASK_BTINFO_SC_LOADINFO = 0xA29u,
TASK_BTINFO_SC_LOADINFO64 = 0xA2Au,
TASK_BTINFO_FLAGS = 0xAFFu,
BUFFER_BEGIN_XNUPOST_CONFIG = 0x1e21c09fu,
BUFFER_BEGIN_COMPRESSED = 0x434f4d50u,
BUFFER_BEGIN_BTINFO = 0x46414E47u,
BUFFER_BEGIN_STACKSHOT = 0x59a25807u,
BUFFER_BEGIN_OS_REASON = 0x53A20900u,
BUFFER_BEGIN_DELTA_STACKSHOT = 0xDE17A59Au,
BUFFER_BEGIN_CRASHINFO = 0xDEADF157u,
BUFFER_END = 0xF19158EDu;
public string to_nick () {
return Marshal.enum_to_nick<ItemType> (this);
}
}
[Flags]
public enum StackshotFlagsLow {
GET_DQ = (1U << 0),
SAVE_LOADINFO = (1U << 1),
GET_GLOBAL_MEM_STATS = (1U << 2),
SAVE_KEXT_LOADINFO = (1U << 3),
ACTIVE_KERNEL_THREADS_ONLY = (1U << 8),
GET_BOOT_PROFILE = (1U << 9),
DO_COMPRESS = (1U << 10),
SAVE_IMP_DONATION_PIDS = (1U << 13),
SAVE_IN_KERNEL_BUFFER = (1U << 14),
RETRIEVE_EXISTING_BUFFER = (1U << 15),
KCDATA_FORMAT = (1U << 16),
ENABLE_BT_FAULTING = (1U << 17),
COLLECT_DELTA_SNAPSHOT = (1U << 18),
COLLECT_SHAREDCACHE_LAYOUT = (1U << 19),
TRYLOCK = (1U << 20),
ENABLE_UUID_FAULTING = (1U << 21),
FROM_PANIC = (1U << 22),
NO_IO_STATS = (1U << 23),
THREAD_WAITINFO = (1U << 24),
THREAD_GROUP = (1U << 25),
SAVE_JETSAM_COALITIONS = (1U << 26),
INSTRS_CYCLES = (1U << 27),
ASID = (1U << 28),
PAGE_TABLES = (1U << 29),
DISABLE_LATENCY_INFO = (1U << 30),
SAVE_DYLD_COMPACTINFO = (1U << 31)
}
[Flags]
public enum StackshotFlagsHigh {
INCLUDE_DRIVER_THREADS_IN_KERNEL = (1U << 0),
EXCLAVES = (1U << 1),
SKIP_EXCLAVES = (1U << 2),
}
public const size_t TASK_SNAPSHOT_PID_OFFSET = 84;
public static bool is_stackshot (Bytes bytes) {
if (bytes.get_size () < 16)
return false;
var type = (ItemType) uint32.from_little_endian (*((uint32 *) bytes.get_data ()));
switch (type) {
case ItemType.BUFFER_BEGIN_STACKSHOT:
case ItemType.BUFFER_BEGIN_DELTA_STACKSHOT:
case ItemType.BUFFER_BEGIN_COMPRESSED:
return true;
default:
return false;
}
}
public sealed class Reader : Object {
private Buffer buf;
private BufferReader r;
private Buffer payload_buf;
private BufferReader payload_r;
private BufferReader scan_r;
private Array<uint64> scan_container_ids = new Array<uint64> ();
[Compact]
private struct Scope {
public size_t end_item_offset;
public uint64 end_id;
}
private Array<Scope> scopes = new Array<Scope> ();
private size_t current_end_item_offset;
private const size_t HEADER_SIZE = 16;
private const size_t ALIGNMENT_SIZE = 16;
public Reader (Bytes bytes) {
buf = new Buffer (bytes, LITTLE_ENDIAN);
r = new BufferReader (buf);
payload_buf = new Buffer.from_data ((uint8[]) null, buf.byte_order, buf.pointer_size);
payload_r = new BufferReader (payload_buf);
scan_r = new BufferReader (buf);
current_end_item_offset = buf.bytes.get_size ();
}
public enum VisitResult {
CONTINUE,
STOP
}
public VisitResult for_each (ItemVisitor visitor) throws Error {
ItemHeader h;
unowned BufferReader p;
while (read_item (out h, out p)) {
if (visitor (h, p) == VisitResult.STOP)
return VisitResult.STOP;
}
return VisitResult.CONTINUE;
}
public delegate VisitResult ItemVisitor (ItemHeader h, BufferReader payload) throws Error;
public VisitResult for_each_container (ItemType want_container_type, ScopeVisitor visitor) throws Error {
ItemHeader h;
unowned BufferReader p;
while (read_item (out h, out p)) {
if (h.type != ItemType.CONTAINER_BEGIN)
continue;
var ctype = (ItemType) p.read_uint32 ();
var id = h.flags;
if (ctype != want_container_type) {
skip_container_body (id);
continue;
}
enter_container_body (id);
var result = visitor (this);
leave_container ();
if (result == VisitResult.STOP)
return VisitResult.STOP;
}
return VisitResult.CONTINUE;
}
public delegate VisitResult ScopeVisitor (Reader r) throws Error;
public unowned BufferReader get_first (ItemType type) throws Error {
unowned BufferReader result = null;
for_each ((h, p) => {
if (h.type != type)
return VisitResult.CONTINUE;
result = p;
return VisitResult.STOP;
});
if (result == null)
throw new Error.PROTOCOL ("Missing item: %s", type.to_nick ());
return result;
}
private bool read_item (out ItemHeader h, out unowned BufferReader payload) throws Error {
if (r.available == 0 || r.offset == current_end_item_offset) {
h = ItemHeader ();
payload = null;
return false;
}
h = read_header ();
payload = read_payload (h);
return true;
}
private ItemHeader read_header () throws Error {
if (r.available < HEADER_SIZE)
throw new Error.PROTOCOL ("KCDATA truncated at %zu (need header, avail=%zu)", r.offset, r.available);
var item_start = r.offset;
var h = read_item_header_fields (r);
var avail_payload = current_end_item_offset - r.offset;
var avail = size_t.min (r.available, avail_payload);
if (h.size > avail) {
throw new Error.PROTOCOL ("KCDATA truncated at %zu (type=0x%x size=%u avail=%zu)", item_start,
(uint32) h.type, h.size, avail);
}
return h;
}
private unowned BufferReader read_payload (ItemHeader h) throws Error {
unowned uint8[] payload = r.read_data (h.size);
payload_buf.reset_data (payload);
payload_r.reset (payload_buf);
r.align (ALIGNMENT_SIZE);
return payload_r;
}
private void enter_container_body (uint64 id) throws Error {
var body_start = r.offset;
size_t end_item_offset;
find_container_end (body_start, id, out end_item_offset);
var s = Scope ();
s.end_item_offset = end_item_offset;
s.end_id = id;
scopes.append_val (s);
current_end_item_offset = end_item_offset;
}
private void leave_container () throws Error {
var s = scopes.index (scopes.length - 1);
scopes.set_size (scopes.length - 1);
consume_container_end_at (s.end_item_offset, s.end_id);
if (scopes.length == 0)
current_end_item_offset = buf.bytes.get_size ();
else {
var parent = scopes.index (scopes.length - 1);
current_end_item_offset = parent.end_item_offset;
}
}
private void skip_container_body (uint64 id) throws Error {
var body_start = r.offset;
size_t end_item_offset;
find_container_end (body_start, id, out end_item_offset);
consume_container_end_at (end_item_offset, id);
}
private void consume_container_end_at (size_t end_item_offset, uint64 id) throws Error {
if (r.offset != end_item_offset)
r.seek (end_item_offset);
if (r.available < HEADER_SIZE)
throw new Error.PROTOCOL ("KCDATA truncated at %zu (need header, avail=%zu)", r.offset, r.available);
var item_start = r.offset;
var h = read_item_header_fields (r);
if (h.type != ItemType.CONTAINER_END || h.flags != id) {
throw new Error.PROTOCOL ("Malformed container end at %zu (want id=0x%016" + uint64.FORMAT_MODIFIER + "x)",
item_start, id);
}
if (h.size > r.available) {
throw new Error.PROTOCOL ("KCDATA truncated at %zu (type=0x%x size=%u avail=%zu)", item_start,
(uint32) h.type, h.size, r.available);
}
r.skip (h.size);
r.align (ALIGNMENT_SIZE);
}
private void find_container_end (size_t body_start, uint64 id, out size_t end_item_offset) throws Error {
scan_container_ids.set_size (0);
scan_r.seek (body_start);
while (true) {
if (scan_r.available < HEADER_SIZE) {
throw new Error.PROTOCOL ("KCDATA truncated at %zu (need header, avail=%zu)",
scan_r.offset, scan_r.available);
}
var item_start = scan_r.offset;
var h = read_item_header_fields (scan_r);
if (h.size > scan_r.available) {
throw new Error.PROTOCOL ("KCDATA truncated at %zu (type=0x%x size=%u avail=%zu)", item_start,
(uint32) h.type, h.size, scan_r.available);
}
scan_r.skip (h.size);
scan_r.align (ALIGNMENT_SIZE);
if (h.type == ItemType.CONTAINER_BEGIN) {
scan_container_ids.append_val (h.flags);
continue;
}
if (h.type == ItemType.CONTAINER_END) {
if (scan_container_ids.length != 0) {
var top = scan_container_ids.remove_index (scan_container_ids.length - 1);
if (top != h.flags) {
throw new Error.PROTOCOL ("Malformed container nesting at %zu (id=0x%016" +
uint64.FORMAT_MODIFIER + "x)", item_start, h.flags);
}
} else {
if (h.flags != id) {
throw new Error.PROTOCOL ("Malformed container end at %zu (id=0x%016" +
uint64.FORMAT_MODIFIER + "x)", item_start, h.flags);
}
end_item_offset = item_start;
return;
}
}
}
}
private ItemHeader read_item_header_fields (BufferReader r) throws Error {
var h = ItemHeader ();
h.type = (ItemType) r.read_uint32 ();
h.size = r.read_uint32 ();
h.flags = r.read_uint64 ();
return h;
}
}
}
+220
View File
@@ -0,0 +1,220 @@
[CCode (gir_namespace = "FridaFruity", gir_version = "1.0")]
namespace Frida.Fruity {
public enum KdebugClass {
MACH = 1,
FSYSTEM = 3,
BSD = 4,
TRACE = 7,
DYLD = 31,
PERF = 37,
ANY = 0xff;
public string to_nick () {
return Marshal.enum_to_nick<KdebugClass> (this);
}
}
public enum KdebugMachSubclass {
EXCP_SC = 12,
}
public enum KdebugFsystemSubclass {
FSRW = 1,
DKRW,
FSVN,
FSLOOOKUP,
JOURNAL,
IOCTL,
BOOTCACHE,
HFS,
APFS,
SMB,
MOUNT,
EXFAT = 14,
MSDOS,
ACFS,
THROTTLE,
DECMP,
VFS,
LIVEFS,
NFS;
public string to_nick () {
return Marshal.enum_to_nick<KdebugFsystemSubclass> (this);
}
}
public enum KdebugFsystemFsrwEvent {
LOOKUP = 36,
LOOKUP_DONE = 39;
public string to_nick () {
return Marshal.enum_to_nick<KdebugFsystemFsrwEvent> (this);
}
}
public enum KdebugBsdSubclass {
EXCP_SC = 12,
}
public enum KdebugTraceSubclass {
DATA,
STRING,
INFO;
public string to_nick () {
return Marshal.enum_to_nick<KdebugTraceSubclass> (this);
}
}
public enum KdebugTraceDataEvent {
NEWTHREAD = 1,
EXEC,
THREAD_TERMINATE,
THREAD_TERMINATE_PID;
public string to_nick () {
return Marshal.enum_to_nick<KdebugTraceDataEvent> (this);
}
}
public enum KdebugTraceStringEvent {
GLOBAL,
NEWTHREAD,
EXEC,
PROC_EXIT,
THREADNAME,
THREADNAME_PREV;
public string to_nick () {
return Marshal.enum_to_nick<KdebugTraceStringEvent> (this);
}
}
public enum KdebugDyldSubclass {
UUID = 5,
}
public enum KdebugDyldUuidEvent {
MAP_A,
MAP_B,
MAP_32_A,
MAP_32_B,
MAP_32_C,
UNMAP_A,
UNMAP_B,
UNMAP_32_A,
UNMAP_32_B,
UNMAP_32_C,
SHARED_CACHE_A,
SHARED_CACHE_B,
SHARED_CACHE_32_A,
SHARED_CACHE_32_B,
SHARED_CACHE_32_C,
AOT_MAP_A,
AOT_MAP_B;
public string to_nick () {
return Marshal.enum_to_nick<KdebugDyldUuidEvent> (this);
}
}
public enum KdebugPerfSubclass {
GENERIC,
THREADINFO,
CALLSTACK,
TIMER,
PET,
AST,
KPC,
KDBG,
TASK,
LAZY,
MEMINFO;
public string to_nick () {
return Marshal.enum_to_nick<KdebugPerfSubclass> (this);
}
}
public enum KdebugPerfCallstackEvent {
KSAMPLE,
UPEND,
USAMPLE,
KDATA,
UDATA,
KHDR,
UHDR,
ERROR,
BACKTRACE,
LOG,
EXHDR,
EXDATA,
EXSTACKHDR,
EXSTACK,
KEXOFFSET;
public string to_nick () {
return Marshal.enum_to_nick<KdebugPerfCallstackEvent> (this);
}
}
public const uint8 KDEBUG_SUBCLASS_ANY = 0xff;
public const uint16 KDEBUG_CODE_ANY = 0x3fff;
public enum KdebugFunctionQualifier {
NONE,
START,
END;
public string to_nick () {
return Marshal.enum_to_nick<KdebugFunctionQualifier> (this);
}
}
public struct KdebugCode {
public uint32 raw;
public KdebugCode (uint32 raw) {
this.raw = raw;
}
public KdebugCode.from_parts (
KdebugClass klass,
uint8 subclass = KDEBUG_SUBCLASS_ANY,
uint16 code = KDEBUG_CODE_ANY,
KdebugFunctionQualifier func_qual = NONE) {
raw =
(((uint32) klass & 0xff) << 24) |
(((uint32) subclass & 0xff) << 16) |
(((uint32) code & 0x3fff) << 2) |
((uint32) func_qual & 0x3);
}
public KdebugClass klass {
get {
return (KdebugClass) ((raw >> 24) & 0xff);
}
}
public uint8 subclass {
get {
return (uint8) ((raw >> 16) & 0xff);
}
}
public uint16 code {
get {
return (uint16) ((raw >> 2) & 0x3fff);
}
}
public KdebugFunctionQualifier func_qual {
get {
return (KdebugFunctionQualifier) (raw & 0x3);
}
}
}
}
+190 -8
View File
@@ -9,8 +9,20 @@ namespace Frida.Fruity {
return other == this;
}
public virtual string to_string () {
return "NSObject";
public string to_string (uint level = 0) {
var s = new StringBuilder.sized (256);
append_indent (s, level);
append_content (s, level);
return s.str;
}
protected virtual void append_content (StringBuilder s, uint level) {
s.append ("NSObject {}");
}
protected void append_indent (StringBuilder s, uint level) {
for (uint i = 0; i != level; i++)
s.append (" ");
}
public static uint hash_func (NSObject val) {
@@ -103,8 +115,19 @@ namespace Frida.Fruity {
return false;
}
public override string to_string () {
return integer.to_string ();
protected override void append_content (StringBuilder s, uint level) {
switch (kind) {
case BOOLEAN:
s.append (boolean ? "true" : "false");
break;
case INTEGER:
s.append_printf ("%" + int64.FORMAT, integer);
break;
case FLOAT:
case DOUBLE:
s.append_printf ("%f", number);
break;
}
}
}
@@ -129,8 +152,11 @@ namespace Frida.Fruity {
return other_string.str == str;
}
public override string to_string () {
return str;
protected override void append_content (StringBuilder s, uint level) {
s
.append_c ('"')
.append (str.replace ("\"", "\\\""))
.append_c ('"');
}
}
@@ -155,8 +181,8 @@ namespace Frida.Fruity {
return other_data.bytes.compare (bytes) == 0;
}
public override string to_string () {
return "NSData";
protected override void append_content (StringBuilder s, uint level) {
s.append_printf ("NSData { size = %" + size_t.FORMAT + " }", bytes.get_size ());
}
}
@@ -219,6 +245,25 @@ namespace Frida.Fruity {
public void set_value (string key, NSObject val) {
storage[key] = val;
}
protected override void append_content (StringBuilder s, uint level) {
if (storage.size == 0) {
s.append ("{}");
return;
}
s.append ("{\n");
foreach (var e in entries) {
append_indent (s, level + 1);
s
.append (e.key)
.append (": ");
e.value.append_content (s, level + 1);
s.append (",\n");
}
append_indent (s, level);
s.append_c ('}');
}
}
public sealed class NSDictionaryRaw : NSObject {
@@ -253,6 +298,24 @@ namespace Frida.Fruity {
? storage
: new Gee.HashMap<NSObject, NSObject> (NSObject.hash_func, NSObject.equal_func);
}
protected override void append_content (StringBuilder s, uint level) {
if (storage.size == 0) {
s.append ("{}");
return;
}
s.append ("{\n");
foreach (var e in entries) {
append_indent (s, level + 1);
e.key.append_content (s, level + 1);
s.append (": ");
e.value.append_content (s, level + 1);
s.append (",\n");
}
append_indent (s, level);
s.append_c ('}');
}
}
public sealed class NSArray : NSObject {
@@ -277,6 +340,56 @@ namespace Frida.Fruity {
public void add_object (NSObject obj) {
storage.add (obj);
}
protected override void append_content (StringBuilder s, uint level) {
if (storage.size == 0) {
s.append ("[]");
return;
}
s.append ("[\n");
foreach (var e in elements) {
append_indent (s, level + 1);
e.append_content (s, level + 1);
s.append (",\n");
}
append_indent (s, level);
s.append_c (']');
}
}
public sealed class NSSet : NSObject {
public Gee.Iterable<NSObject> items {
owned get {
return storage;
}
}
private Gee.HashSet<NSObject> storage;
public NSSet (Gee.HashSet<NSObject>? storage = null) {
this.storage = (storage != null) ? storage : new Gee.HashSet<NSObject> (NSObject.hash_func);
}
public void add_object (NSObject obj) {
storage.add (obj);
}
protected override void append_content (StringBuilder s, uint level) {
if (storage.size == 0) {
s.append ("{}");
return;
}
s.append ("{\n");
foreach (var e in items) {
append_indent (s, level + 1);
e.append_content (s, level + 1);
s.append (",\n");
}
append_indent (s, level);
s.append_c ('}');
}
}
public sealed class NSDate : NSObject {
@@ -296,6 +409,10 @@ namespace Frida.Fruity {
return new DateTime.from_unix_utc (MAC_EPOCH_DELTA_FROM_UNIX + whole_seconds)
.add_seconds (time - (double) whole_seconds);
}
protected override void append_content (StringBuilder s, uint level) {
s.append_printf ("NSDate { time = %f }", time);
}
}
public sealed class NSError : NSObject {
@@ -319,6 +436,35 @@ namespace Frida.Fruity {
this.code = code;
this.user_info = user_info;
}
protected override void append_content (StringBuilder s, uint level) {
s.append ("NSError { domain = ");
domain.append_content (s, level);
s.append_printf (", code = %" + uint64.FORMAT_MODIFIER + "d, user_info = ", code);
if (user_info.size == 0) {
user_info.append_content (s, level);
s.append (" }");
return;
}
s.append ("{\n");
append_indent (s, level + 1);
s.append ("domain: ");
domain.append_content (s, level + 1);
s.append (",\n");
append_indent (s, level + 1);
s.append_printf ("code: %" + uint64.FORMAT_MODIFIER + "d,\n", code);
append_indent (s, level + 1);
s.append ("user_info: ");
user_info.append_content (s, level + 1);
s.append_c ('\n');
append_indent (s, level);
s.append_c ('}');
}
}
public sealed class DTTapMessage : NSObject {
@@ -330,6 +476,25 @@ namespace Frida.Fruity {
public DTTapMessage (NSDictionary plist) {
this.plist = plist;
}
protected override void append_content (StringBuilder s, uint level) {
if (plist.size == 0) {
s.append ("DTTapMessage { plist: ");
plist.append_content (s, level);
s.append (" }");
return;
}
s.append ("DTTapMessage {\n");
append_indent (s, level + 1);
s.append ("plist: ");
plist.append_content (s, level + 1);
s.append_c ('\n');
append_indent (s, level);
s.append_c ('}');
}
}
namespace NSKeyedArchive {
@@ -338,6 +503,7 @@ namespace Frida.Fruity {
private const string[] DICTIONARY_CLASS = { "NSDictionary", "NSObject" };
private const string[] ARRAY_CLASS = { "NSArray", "NSObject" };
private const string[] SET_CLASS = { "NSSet", "NSObject" };
[CCode (has_target = false)]
private delegate PlistUid EncodeFunc (NSObject instance, EncodingContext ctx);
@@ -455,6 +621,7 @@ namespace Frida.Fruity {
encoders[typeof (NSString)] = encode_string;
encoders[typeof (NSDictionary)] = encode_dictionary;
encoders[typeof (NSArray)] = encode_array;
encoders[typeof (NSSet)] = encode_set;
}
private static void ensure_decoders_registered () {
@@ -619,6 +786,21 @@ namespace Frida.Fruity {
return uid;
}
private static PlistUid encode_set (NSObject instance, EncodingContext ctx) {
NSSet set = (NSSet) instance;
var object = new PlistDict ();
var uid = ctx.add_object (object);
var objs = new PlistArray ();
foreach (var element in set.items)
objs.add_uid (encode_value (element, ctx));
object.set_array ("NS.objects", objs);
object.set_uid ("$class", ctx.get_class (SET_CLASS));
return uid;
}
private static NSObject decode_array (PlistDict instance, DecodingContext ctx) throws Error, PlistError {
var objs = instance.get_array ("NS.objects");
+180
View File
@@ -0,0 +1,180 @@
[CCode (gir_namespace = "FridaFruity", gir_version = "1.0")]
namespace Frida.Fruity {
public delegate void KperfdataRecordVisitor (KdBuf rec) throws Error;
public sealed class KperfdataStreamParser : Object {
private ByteArray stash = new ByteArray ();
private size_t cursor = 0;
private bool have_header = false;
private uint32 thread_count = 0;
private size_t records_offset = 0;
private const uint32 RAW_VERSION2 = 0x55aa0200u;
private const size_t HEADER_FIXED_SIZE = 0x120;
private const size_t THREADMAP_ENTRY_SIZE = 0x20;
private const size_t PAGE_SIZE = 0x1000;
private const size_t KD_BUF_SIZE = 0x40;
public void reset () {
stash.set_size (0);
cursor = 0;
have_header = false;
thread_count = 0;
records_offset = 0;
}
public void push (Bytes chunk, KperfdataRecordVisitor visitor) throws Error {
stash.append (chunk.get_data ());
var stash_bytes = new Bytes.static (stash.data);
parse_bytes (stash_bytes, visitor);
compact ();
}
private void parse_bytes (Bytes bytes, KperfdataRecordVisitor visitor) throws Error {
var buf = new Frida.Buffer (bytes, LITTLE_ENDIAN);
var r = new Frida.BufferReader (buf);
while (true) {
if (!have_header) {
if (r.available < 8)
return;
size_t header_start = r.offset;
uint32 magic = r.read_uint32 ();
if (magic != RAW_VERSION2)
throw new Error.PROTOCOL ("Unknown kperfdata magic 0x%x", magic);
thread_count = r.read_uint32 ();
uint64 threadmaps_size_64 = thread_count * THREADMAP_ENTRY_SIZE;
size_t header_size = (size_t) (HEADER_FIXED_SIZE + threadmaps_size_64);
size_t aligned = align_up (header_size, PAGE_SIZE);
records_offset = aligned;
if ((r.offset - 8) != header_start)
throw new Error.PROTOCOL ("Internal offset bookkeeping error");
if ((stash.len - header_start) < records_offset) {
r.skip (header_start - r.offset);
return;
}
cursor = header_start + records_offset;
have_header = true;
r.skip (cursor - r.offset);
continue;
}
if (r.offset < cursor) {
if ((cursor - r.offset) > r.available)
return;
r.skip (cursor - r.offset);
}
if (r.available < KD_BUF_SIZE)
return;
KdBuf rec = KdBuf ();
rec.timestamp = r.read_uint64 ();
rec.arg1 = r.read_uint64 ();
rec.arg2 = r.read_uint64 ();
rec.arg3 = r.read_uint64 ();
rec.arg4 = r.read_uint64 ();
rec.arg5 = r.read_uint64 ();
rec.debugid = r.read_uint32 ();
rec.cpuid = r.read_uint32 ();
rec.unused = r.read_uint64 ();
visitor (rec);
cursor = r.offset;
}
}
private void compact () {
if (cursor == 0)
return;
if (cursor >= stash.len) {
stash.set_size (0);
cursor = 0;
return;
}
size_t remaining = stash.len - cursor;
Memory.move (stash.data, (uint8 *) stash.data + cursor, remaining);
stash.set_size ((uint) remaining);
cursor = 0;
}
private static size_t align_up (size_t val, size_t alignment) {
size_t mask = alignment - 1;
return (val + mask) & ~mask;
}
}
public struct KdBuf {
public uint64 timestamp;
public uint64 arg1;
public uint64 arg2;
public uint64 arg3;
public uint64 arg4;
public uint64 arg5;
public uint32 debugid;
public uint32 cpuid;
public uint64 unused;
public KdebugCode kcode {
get {
return KdebugCode (debugid);
}
}
public string to_string () {
var kc = kcode;
return (
"ts=0x%" + uint64.FORMAT_MODIFIER + "x "
+ "arg1=0x%" + uint64.FORMAT_MODIFIER + "x "
+ "arg2=0x%" + uint64.FORMAT_MODIFIER + "x "
+ "arg3=0x%" + uint64.FORMAT_MODIFIER + "x "
+ "arg4=0x%" + uint64.FORMAT_MODIFIER + "x "
+ "arg5=0x%" + uint64.FORMAT_MODIFIER + "x "
+ "debugid=0x%08x "
+ "klass=%s subclass=%u code=%u func=%s "
+ "cpuid=%u "
+ "unused=0x%" + uint64.FORMAT_MODIFIER + "x"
).printf (
timestamp,
arg1,
arg2,
arg3,
arg4,
arg5,
debugid,
kc.klass.to_nick (),
kc.subclass,
kc.code,
kc.func_qual.to_nick (),
cpuid,
unused
);
}
}
}
+19 -29
View File
@@ -36,8 +36,6 @@ namespace Frida.Fruity {
private uint16 ndp_fixed_header_size;
private VirtualNetworkStack? _netstack;
private Gee.Queue<Bytes> pending_input = new Gee.ArrayQueue<Bytes> ();
private bool input_flush_scheduled = false;
private Gee.Queue<Bytes> pending_output = new Gee.ArrayQueue<Bytes> ();
private size_t out_in_flight_count = 0;
private size_t out_in_flight_bytes = 0;
@@ -184,8 +182,20 @@ namespace Frida.Fruity {
}
try {
var frame = yield pending.poll ().future.wait_async (io_cancellable);
handle_ncm_frame (frame);
var datagrams = new Gee.ArrayList<Bytes> ();
while (true) {
var request = pending.peek ();
if (request == null)
break;
if (!datagrams.is_empty && !request.future.ready)
break;
var frame = yield pending.poll ().future.wait_async (io_cancellable);
datagrams.add_all (handle_ncm_frame (frame));
}
yield _netstack.handle_incoming_datagrams (datagrams);
} catch (GLib.Error e) {
return;
}
@@ -208,7 +218,7 @@ namespace Frida.Fruity {
}
}
private void handle_ncm_frame (Bytes frame) throws GLib.Error {
private Gee.List<Bytes> handle_ncm_frame (Bytes frame) throws GLib.Error {
var input = new DataInputStream (new MemoryInputStream.from_bytes (frame));
input.byte_order = LITTLE_ENDIAN;
@@ -222,6 +232,8 @@ namespace Frida.Fruity {
input.skip (6);
var ndp_index = input.read_uint16 ();
var datagrams = new Gee.ArrayList<Bytes> ();
do {
input.seek (ndp_index, SET);
input.read_all (raw_signature[:4], out bytes_read);
@@ -250,35 +262,13 @@ namespace Frida.Fruity {
notify_property ("remote-ipv6-address");
}
on_incoming_datagram (datagram);
datagrams.add (datagram);
}
ndp_index = next_ndp_index;
} while (ndp_index != 0);
}
private void on_incoming_datagram (Bytes datagram) {
pending_input.offer (datagram);
if (!input_flush_scheduled) {
var source = new IdleSource ();
source.set_callback (() => {
input_flush_scheduled = false;
flush_pending_input ();
return Source.REMOVE;
});
source.attach (MainContext.get_thread_default ());
input_flush_scheduled = true;
}
}
private void flush_pending_input () {
var datagrams = pending_input;
pending_input = new Gee.ArrayQueue<Bytes> ();
try {
_netstack.handle_incoming_datagrams (datagrams);
} catch (Error e) {
}
return datagrams;
}
private void on_netif_outgoing_datagrams (Gee.Collection<Bytes> datagrams) {
+21 -6
View File
@@ -283,14 +283,14 @@ namespace Frida.Fruity {
return new Ipv6UdpSocket (this);
}
public void handle_incoming_datagrams (Gee.Collection<Bytes> datagrams) throws Error {
public async void handle_incoming_datagrams (Gee.Collection<Bytes> datagrams) throws Error {
LWIP.ErrorCode err = OK;
check_started ();
check (perform_on_lwip_thread (() => {
schedule_on_lwip_thread (() => {
begin_output ();
LWIP.ErrorCode err = OK;
foreach (var d in datagrams) {
var pbuf = LWIP.PacketBuffer.alloc (RAW, (uint16) d.get_size (), POOL);
pbuf.take (d.get_data ());
@@ -304,8 +304,14 @@ namespace Frida.Fruity {
end_output ();
schedule_on_frida_thread (handle_incoming_datagrams.callback);
return err;
}));
});
yield;
check (err);
}
private static LWIP.ErrorCode on_netif_link_output (LWIP.NetworkInterface handle, LWIP.PacketBuffer pbuf) {
@@ -359,6 +365,15 @@ namespace Frida.Fruity {
}
internal LWIP.ErrorCode perform_on_lwip_thread (owned WorkFunc work) {
var req = submit_work ((owned) work);
return req.join ();
}
internal void schedule_on_lwip_thread (owned WorkFunc work) {
submit_work ((owned) work);
}
private Request submit_work (owned WorkFunc work) {
var req = new Request ((owned) work);
if (Thread.self<bool> () == lwip_thread) {
@@ -369,7 +384,7 @@ namespace Frida.Fruity {
LWIP.Runtime.schedule (perform_next_request);
}
return req.join ();
return req;
}
private void perform_next_request () {
+79 -41
View File
@@ -2039,19 +2039,19 @@ namespace Frida.Fruity {
private Promise<bool> close_request = new Promise<bool> ();
private TunnelParameters tunnel_params;
private Bytes flush_trigger_datagram;
private VirtualNetworkStack _tunnel_netstack;
private BufferedInputStream input;
private OutputStream output;
private Gee.Queue<Bytes> pending_input = new Gee.ArrayQueue<Bytes> ();
private bool input_flush_scheduled = false;
private Gee.Queue<Bytes> pending_output = new Gee.ArrayQueue<Bytes> ();
private bool writing = false;
private Cancellable io_cancellable = new Cancellable ();
private const size_t PREFERRED_MTU = 16000;
private const size_t REMOTEPAIRINGDEVICED_DEFER_THRESHOLD = 8192;
private const string PSK_IDENTITY = "com.apple.CoreDevice.TunnelService.Identity";
public static async TcpTunnelConnection open (InetSocketAddress address, NetworkStack netstack, TunnelKey local_keypair,
@@ -2125,6 +2125,7 @@ namespace Frida.Fruity {
post (make_handshake_request (PREFERRED_MTU));
tunnel_params = TunnelParameters.from_json (yield read_message (cancellable));
flush_trigger_datagram = make_minimal_dummy_ipv6_datagram (tunnel_params.address, tunnel_params.server_address);
_tunnel_netstack = new VirtualNetworkStack (null, tunnel_params.address, tunnel_params.mtu);
_tunnel_netstack.outgoing_datagrams.connect (post_batch);
@@ -2147,8 +2148,39 @@ namespace Frida.Fruity {
private async void process_incoming_messages () {
try {
while (true) {
var datagram = yield read_datagram (io_cancellable);
on_incoming_datagram (datagram);
var pending_input = new Gee.ArrayQueue<Bytes> ();
while (true) {
var size = peek_datagram_size ();
if (size == -1)
break;
var datagram = new uint8[size];
input.read (datagram, io_cancellable);
pending_input.offer (new Bytes.take ((owned) datagram));
}
if (pending_input.size != 0) {
try {
yield _tunnel_netstack.handle_incoming_datagrams (pending_input);
} catch (Error e) {
}
var source = new IdleSource ();
source.set_callback (process_incoming_messages.callback);
source.attach (MainContext.get_thread_default ());
yield;
}
ssize_t n;
try {
n = yield input.fill_async (-1, Priority.DEFAULT, io_cancellable);
} catch (GLib.Error e) {
throw new Error.TRANSPORT ("Connection closed");
}
if (n == 0)
throw new Error.TRANSPORT ("Connection closed");
}
} catch (GLib.Error e) {
}
@@ -2173,30 +2205,6 @@ namespace Frida.Fruity {
closed ();
}
private void on_incoming_datagram (Bytes datagram) {
pending_input.offer (datagram);
if (!input_flush_scheduled) {
var source = new IdleSource ();
source.set_callback (() => {
input_flush_scheduled = false;
flush_pending_input ();
return Source.REMOVE;
});
source.attach (MainContext.get_thread_default ());
input_flush_scheduled = true;
}
}
private void flush_pending_input () {
var datagrams = pending_input;
pending_input = new Gee.ArrayQueue<Bytes> ();
try {
_tunnel_netstack.handle_incoming_datagrams (datagrams);
} catch (Error e) {
}
}
private void post (Bytes datagram) {
var batch = new Gee.ArrayList<Bytes> ();
batch.add (datagram);
@@ -2231,6 +2239,14 @@ namespace Frida.Fruity {
} catch (GLib.Error e) {
break;
}
if (pending_output.is_empty && size > REMOTEPAIRINGDEVICED_DEFER_THRESHOLD) {
try {
yield output.write_all_async (flush_trigger_datagram.get_data (), Priority.DEFAULT,
io_cancellable, null);
} catch (GLib.Error e) {
}
}
}
writing = false;
@@ -2269,24 +2285,21 @@ namespace Frida.Fruity {
return new JsonObjectReader (json);
}
private async Bytes read_datagram (Cancellable? cancellable) throws Error, IOError {
size_t header_size = 40;
private ssize_t peek_datagram_size () {
ssize_t header_size = 40;
if (input.get_available () < header_size)
yield fill_until_n_bytes_available (header_size, cancellable);
return -1;
uint16 payload_size = 0;
unowned uint8[] size_buf = ((uint8[]) &payload_size)[:2];
input.peek (size_buf, 4);
payload_size = uint16.from_big_endian (payload_size);
size_t full_size = header_size + payload_size;
ssize_t full_size = header_size + payload_size;
if (input.get_available () < full_size)
yield fill_until_n_bytes_available (full_size, cancellable);
return -1;
var datagram = new uint8[full_size];
input.read (datagram, cancellable);
return new Bytes.take ((owned) datagram);
return full_size;
}
private async void fill_until_n_bytes_available (size_t minimum, Cancellable? cancellable) throws Error, IOError {
@@ -2310,6 +2323,23 @@ namespace Frida.Fruity {
}
}
private static Bytes make_minimal_dummy_ipv6_datagram (InetAddress sender, InetAddress recipient) {
assert (sender.get_native_size () == 16 && recipient.get_native_size () == 16);
uint8 hop_limit = 1;
unowned uint8[] src = sender.to_bytes ();
unowned uint8[] dst = recipient.to_bytes ();
return new BufferBuilder (BIG_ENDIAN)
.append_uint32 (0x60000000)
.append_uint16 (0)
.append_uint8 (59)
.append_uint8 (hop_limit)
.append_data (src[:16])
.append_data (dst[:16])
.build ();
}
[CCode (cname = "g_tls_connection_openssl_get_ssl")]
private extern static unowned SSL get_ssl_handle_from_connection (void * connection);
@@ -2367,6 +2397,7 @@ namespace Frida.Fruity {
private Gee.Map<int64?, Stream> streams = new Gee.HashMap<int64?, Stream> (Numeric.int64_hash, Numeric.int64_equal);
private Gee.Queue<Bytes> pending_input = new Gee.ArrayQueue<Bytes> ();
private bool input_flush_scheduled = false;
private bool input_flush_happening = false;
private Gee.Queue<Bytes> pending_output = new Gee.ArrayQueue<Bytes> ();
private DatagramBasedSource? rx_source;
@@ -2842,7 +2873,7 @@ namespace Frida.Fruity {
var source = new IdleSource ();
source.set_callback (() => {
input_flush_scheduled = false;
flush_pending_input ();
flush_pending_input.begin ();
return Source.REMOVE;
});
source.attach (MainContext.get_thread_default ());
@@ -2852,13 +2883,20 @@ namespace Frida.Fruity {
return 0;
}
private void flush_pending_input () {
private async void flush_pending_input () {
if (input_flush_happening)
return;
input_flush_happening = true;
var datagrams = pending_input;
pending_input = new Gee.ArrayQueue<Bytes> ();
try {
_tunnel_netstack.handle_incoming_datagrams (datagrams);
} catch (Error e) {
yield _tunnel_netstack.handle_incoming_datagrams (datagrams);
} catch (GLib.Error e) {
}
input_flush_happening = false;
}
private static void on_rand (uint8[] dest, NGTcp2.RNGContext rand_ctx) {
+6
View File
@@ -231,6 +231,12 @@ namespace Frida {
set;
default = new Gee.HashMap<string, Value?> ();
}
public HostSessionOptions copy () {
var opts = new HostSessionOptions ();
opts.map.set_all (map);
return opts;
}
}
public interface HostChannelProvider : Object {
+55 -16
View File
@@ -12,6 +12,7 @@ namespace Frida {
private Gee.Map<uint, ExecTransitionSession> exec_transitions = new Gee.HashMap<uint, ExecTransitionSession> ();
private Gee.Map<uint, AwaitExecTransitionTask> exec_waiters = new Gee.HashMap<uint, AwaitExecTransitionTask> ();
private Gee.Map<uint, PausedSyscallSession> paused_syscalls = new Gee.HashMap<uint, PausedSyscallSession> ();
private Gee.Map<uint, InjectSession> suspended_by_inject = new Gee.HashMap<uint, InjectSession> ();
private Gee.Map<uint, RemoteAgent> agents = new Gee.HashMap<uint, RemoteAgent> ();
private Gee.Map<uint, Source> agent_expiries = new Gee.HashMap<uint, Source> ();
private Gee.Map<uint, Gee.Queue<TaskEntry>> task_queues = new Gee.HashMap<uint, Gee.Queue<TaskEntry>> ();
@@ -276,6 +277,12 @@ namespace Frida {
return null;
}
InjectSession inject_session;
if (backend.suspended_by_inject.unset (pid, out inject_session)) {
inject_session.close ();
return null;
}
SpawnedProcess? p = backend.spawned_processes[pid];
if (p != null) {
p.resume ();
@@ -313,7 +320,10 @@ namespace Frida {
yield pss.interrupt (cancellable);
var session = yield InjectSession.open (pid, cancellable);
RemoteAgent agent = yield session.inject (spec, cancellable);
session.close ();
if (session.was_group_stopped)
backend.suspended_by_inject[pid] = session;
else
session.close ();
return agent;
}
}
@@ -813,22 +823,23 @@ namespace Frida {
private const uint64 SOCK_CLOEXEC = 0x80000;
private sealed class InjectSession : SeizeSession {
private static ProcMapsSoEntry local_libc;
private static ProcMapsSnapshot.Mapping local_libc;
private static uint64 mmap_offset;
private static uint64 munmap_offset;
private static string fallback_ld;
private static string fallback_libc;
private static ProcMapsSoEntry? local_android_ld;
private static ProcMapsSnapshot.Mapping? local_android_ld;
static construct {
var libc = Gum.Process.get_libc_module ();
uint local_pid = Posix.getpid ();
local_libc = ProcMapsSoEntry.find_by_path (local_pid, libc.path);
var local_maps = ProcMapsSnapshot.from_pid (local_pid);
local_libc = local_maps.find_module_by_path (libc.path);
assert (local_libc != null);
mmap_offset = (uint64) (uintptr) libc.find_export_by_name ("mmap") - local_libc.base_address;
munmap_offset = (uint64) (uintptr) libc.find_export_by_name ("munmap") - local_libc.base_address;
mmap_offset = (uint64) (uintptr) libc.find_export_by_name ("mmap") - local_libc.start;
munmap_offset = (uint64) (uintptr) libc.find_export_by_name ("munmap") - local_libc.start;
try {
var program = new Gum.ElfModule.from_file ("/proc/self/exe");
@@ -846,7 +857,7 @@ namespace Frida {
}
#if ANDROID
local_android_ld = ProcMapsSoEntry.find_by_path (local_pid, fallback_ld);
local_android_ld = local_maps.find_module_by_path (fallback_ld);
#endif
}
@@ -1051,9 +1062,10 @@ namespace Frida {
uint64 allocation_base = 0;
size_t allocation_size = size_t.max (bootstrapper_size, loader_size) + stack_size;
var remote_maps = ProcMapsSnapshot.from_pid (pid);
var remote_libc = remote_maps.find_module_by_path (local_libc.path);
uint64 remote_mmap = 0;
uint64 remote_munmap = 0;
ProcMapsSoEntry? remote_libc = ProcMapsSoEntry.find_by_path (pid, local_libc.path);
#if ANDROID
bool same_libc = remote_libc != null
&& remote_libc.device.major == local_libc.device.major
@@ -1066,8 +1078,8 @@ namespace Frida {
&& remote_libc.path == local_libc.path;
#endif
if (same_libc) {
remote_mmap = remote_libc.base_address + mmap_offset;
remote_munmap = remote_libc.base_address + munmap_offset;
remote_mmap = remote_libc.start + mmap_offset;
remote_munmap = remote_libc.start + munmap_offset;
}
if (remote_mmap != 0) {
@@ -1165,7 +1177,9 @@ namespace Frida {
result.context.libc = &result.libc;
if (result.context.rtld_flavor == ANDROID && result.libc.dlopen == null) {
ProcMapsSoEntry? remote_ld = ProcMapsSoEntry.find_by_address (pid, (uintptr) result.context.rtld_base);
if (restart_after_libc_load)
remote_maps = ProcMapsSnapshot.from_pid (pid);
var remote_ld = remote_maps.find_mapping ((uintptr) result.context.rtld_base);
bool same_ld = remote_ld != null && local_android_ld != null
&& remote_ld.device.equals (local_android_ld.device)
&& remote_ld.inode == local_android_ld.inode;
@@ -1217,9 +1231,9 @@ namespace Frida {
}
}
private static void * rebase_pointer (uintptr local_ptr, ProcMapsSoEntry local_module, ProcMapsSoEntry remote_module) {
var offset = local_ptr - local_module.base_address;
return (void *) (remote_module.base_address + offset);
private static void * rebase_pointer (uintptr local_ptr, ProcMapsSnapshot.Mapping local, ProcMapsSnapshot.Mapping remote) {
var offset = local_ptr - local.start;
return (void *) (remote.start + offset);
}
private static string make_fallback_address () {
@@ -1815,6 +1829,11 @@ namespace Frida {
}
}
public bool was_group_stopped {
get;
private set;
}
public enum InitBehavior {
INTERRUPT,
CONTINUE
@@ -1861,6 +1880,8 @@ namespace Frida {
private async bool init_async (int io_priority, Cancellable? cancellable) throws Error, IOError {
PtraceOptions options = PtraceOptions.TRACESYSGOOD | PtraceOptions.TRACEEXEC;
bool was_stopped = seize_supported && query_process_state (tid) == 'T';
PtraceRequest req;
long res;
if (seize_supported) {
@@ -1886,8 +1907,14 @@ namespace Frida {
attach_state = ATTACHED;
if (seize_supported) {
ptrace (INTERRUPT, tid);
yield wait_for_signal (TRAP, cancellable);
if (was_stopped) {
was_group_stopped = true;
yield wait_for_next_stop (cancellable);
Posix.kill ((Posix.pid_t) pid, Posix.Signal.CONT);
} else {
ptrace (INTERRUPT, tid);
yield wait_for_signal (TRAP, cancellable);
}
} else {
yield wait_for_signal (STOP, cancellable);
ptrace (SETOPTIONS, tid, null, (void *) options);
@@ -1916,6 +1943,18 @@ namespace Frida {
return true;
}
private static char query_process_state (uint tid) {
try {
string stat;
FileUtils.get_contents ("/proc/%u/stat".printf (tid), out stat);
int paren_end = stat.last_index_of_char (')');
if (paren_end != -1 && paren_end + 2 < stat.length)
return stat[paren_end + 2];
} catch (FileError e) {
}
return '?';
}
public void close () throws Error {
if (attach_state == ATTACHED) {
ptrace (DETACH, tid);
+16
View File
@@ -36,6 +36,18 @@ namespace Frida {
_resource_store = null;
}
public async void preload (Cancellable? cancellable) throws IOError {
try {
yield obtain_for_64bit (cancellable);
} catch (Error e) {
}
try {
yield obtain_for_32bit (cancellable);
} catch (Error e) {
}
}
private ResourceStore get_resource_store () throws Error {
if (_resource_store == null)
_resource_store = new ResourceStore (tempdir);
@@ -189,6 +201,10 @@ namespace Frida {
private async LinuxHelper obtain_for_32bit (Cancellable? cancellable) throws Error, IOError {
if (factory32 == null) {
#if ANDROID
if (sizeof (void *) == 8 && _query_android_system_property ("ro.product.cpu.abilist32") == "")
throw new Error.NOT_SUPPORTED ("Android system does not support 32-bit processes");
#endif
var store = get_resource_store ();
if (sizeof (void *) != 4 && store.helper32 == null)
throw new Error.NOT_SUPPORTED ("Unable to handle 32-bit processes due to build configuration");
+12 -9
View File
@@ -19,7 +19,7 @@ endif
ifdef FRIDA_HOST
host_machine := $(FRIDA_HOST)
else
host_machine := $(shell basename $$(ls -1 $(BUILDDIR)/frida-linux-*.txt | tail -1) | cut -d"." -f1 | cut -d"-" -f2-)
host_machine := $(shell basename $$(ls -1 $(BUILDDIR)/*/frida-linux-*.txt | tail -1) | cut -d"." -f1 | cut -d"-" -f2-)
endif
host_arch := $(shell echo $(host_machine) | cut -d"-" -f2)
@@ -34,9 +34,9 @@ native_outdir := $(artifacts_dir)/native/$(host_arch)
bpf_outdir := $(artifacts_dir)/bpf
bpf_noarch_progs := \
activity-sampler \
softwall \
$(NULL)
bpf_arch_progs := \
spawn-gater \
syscall-tracer \
$(NULL)
bpf_noarch_pairs := \
@@ -50,11 +50,11 @@ bpf_arch_pairs := \
build-native: ext/linux/tools/include/nolibc/nolibc.h
rm -rf build
$(MESON) setup --cross-file $(crossfile) -Db_lto=true build
$(MESON) compile -C build
install -m644 build/bootstrapper.bin $(native_outdir)/bootstrapper.bin
install -m644 build/loader.bin $(native_outdir)/loader.bin
[ -f build/zymbiote.bin ] && install -m644 build/zymbiote.bin $(native_outdir)/zymbiote.bin || true
$(MESON) setup --prefix /usr --cross-file $(crossfile) -Db_lto=true build
DESTDIR=$(abspath build/dist) $(MESON) install -C build
for f in build/dist/usr/share/frida-helpers/*; do \
install -m644 $$f $(native_outdir)/; \
done
bpf_targets :=
bpf_obj := $(build_dir)/module.o
@@ -67,6 +67,8 @@ linux_uapi_arch = $(strip \
$(if $(filter arm armbe,$1),arm, \
$(if $(filter arm64 arm64be,$1),arm64, \
$(if $(filter mips mipsel mips64 mips64el,$1),mips,unknown)))))
has_compat32 = $(strip \
$(if $(filter x86_64 arm64 arm64be,$(1)),1,))
kernel_headers_stamp = $(kernel_headers_dir)/$(1)/.stamp
kernel_headers_for = $(call kernel_headers_stamp,$(call linux_uapi_arch,$(1)))
@@ -96,6 +98,7 @@ define bpf_compile
$(BPF_CLANG) \
-target $(1) \
-D__TARGET_ARCH_$(2) \
$(if $(call has_compat32,$(3)),-DFRIDA_HAS_COMPAT32=1,) \
-O2 -g \
-I$(build_dir) \
-I$(libbpf_devel_dir) \
@@ -114,7 +117,7 @@ bpf_targets += $(foreach p,$(bpf_noarch_progs),$(bpf_outdir)/noarch-$(1)/$(p).el
$(bpf_outdir)/noarch-$(1)/%.elf: %.bpf.c $(call kernel_headers_stamp,$(noarch_uapi_arch)) $(libbpf_devel_dir)
$$(call recreate_build_dir)
$$(call bpf_compile,$(2),$(noarch_uapi_arch))
$$(call bpf_compile,$(2),$(noarch_uapi_arch),noarch)
endef
define declare_bpf_arch
@@ -140,7 +143,7 @@ $(bpf_outdir)/$(1)/%.elf: %.bpf.c $(call kernel_headers_for,$(1)) $(libbpf_devel
{ print } \
' frida-linux-syscalls.h > frida-linux-syscalls.h.tmp && \
mv frida-linux-syscalls.h.tmp frida-linux-syscalls.h
$$(call bpf_compile,$(2),$$(call linux_uapi_arch,$(1)))
$$(call bpf_compile,$(2),$$(call linux_uapi_arch,$(1)),$(1))
endef
pair_abi = $(word 1,$(subst :, ,$1))
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -6,6 +6,7 @@ SECTIONS {
KEEP(*(.text.entrypoint))
*(.text*)
*(.rodata*)
*(.data*)
}
.dynstr : { *(.dynstr) }
+5 -1
View File
@@ -2,11 +2,15 @@
#define __FRIDA_INJECT_CONTEXT_H__
#ifdef NOLIBC
# ifdef __ANDROID__
typedef long pthread_t;
# else
typedef void * pthread_t;
typedef struct _pthread_attr_t pthread_attr_t;
typedef unsigned int socklen_t;
# endif
struct msghdr;
struct sockaddr;
typedef unsigned int socklen_t;
#else
# include <dlfcn.h>
# include <pthread.h>
+1 -5
View File
@@ -94,14 +94,10 @@ if host_machine.system() == 'android'
endif
zymbiote = shared_module('zymbiote', ['zymbiote.c'],
name_prefix: '',
name_suffix: 'elf',
c_args: zymbiote_flags + extra_flags,
link_args: extra_link_args,
link_depends: [helper_lds],
)
custom_target('zymbiote-bin',
input: [zymbiote],
output: ['zymbiote.bin'],
command: [objcopy, objcopy_flags, '@INPUT0@', '@OUTPUT0@'],
install_dir: 'share' / 'frida-helpers',
install: true,
)
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff. Show more