Compare commits

...
603 Commits
Author SHA1 Message Date
Ole André Vadla Ravnås 4dcce299d0 subprojects: Prepare for release 2025-07-02 00:09:13 +02:00
Ole André Vadla Ravnås 474199c1e7 subprojects: Bump outdated 2025-07-02 00:08:31 +02:00
Ole André Vadla Ravnås 6ff8d931e0 package-manager: Fix broken #if on Windows 2025-07-02 00:07:44 +02:00
Ole André Vadla Ravnås 4b25d3b987 subprojects: Prepare for release 2025-07-01 23:40:01 +02:00
Ole André Vadla Ravnås 0f98678051 subprojects: Bump outdated 2025-07-01 23:38:55 +02:00
Henrik Grimler 52948f6c4f meson: Clarify Vala build system gotcha (#1182)
The Vala README only mentions autotools instructions, and when Vala is
compiled that way the -frida suffix is not added to the version string,
and the frida-core check for Vala fails.

Therefore, clarify that Vala needs to be built from source with Meson.
2025-07-01 21:33:05 +02:00
Ole André Vadla Ravnås ae7a3725d3 meson: Add missing libc Vala defines
Needed by the latest PackageManager.
2025-07-01 21:15:39 +02:00
Ole André Vadla Ravnås 62234b16ae package-manager: Refactor the installation logic 2025-07-01 21:07:35 +02:00
Ole André Vadla Ravnås 1000cba56b package-manager: Fix the has_install_script logic
Should also take `preinstall` and `postinstall` into account.
2025-07-01 21:07:35 +02:00
Ole André Vadla Ravnås 40004affdb package-manager: Improve optional package handling 2025-07-01 21:07:35 +02:00
Ole André Vadla Ravnås a836182ac9 package-manager: Add install() option for role
To achieve the equivalent of npm install's --save-* switches.
2025-07-01 21:07:35 +02:00
Ole André Vadla Ravnås 600d2bf948 package-manager: Add install() option for omits
To achieve the equivalent of npm install's --omit=x switch.
2025-07-01 21:07:35 +02:00
Ole André Vadla Ravnås 466705f0da package-manager: Handle file mode when extracting
On non-Windows systems.
2025-07-01 21:07:35 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 18ad19554a package-manager: Improve resolution and hoisting
To mimic npm's behavior more closely.

Co-authored-by: Håvard Sørbø <[email protected]>
2025-07-01 21:07:35 +02:00
Ole André Vadla Ravnås 58c8062f93 subprojects: Prepare for release 2025-06-27 15:59:50 +02:00
Kyle Bouchard a6be95d8ae agent: Disable Exceptor for the emulated realm
Exceptor needs to hook signal() and sigaction(), but they are in libc,
leading to gum_mprotect() aborting because it cannot change libc's
'r--' mapping.

I tested it on AVDs with Android 14 and 15 and it prevents the crash
observed in the upstream version when using frida-server or
frida-inject.
2025-06-27 15:58:12 +02:00
Ole André Vadla Ravnås db258f0d35 subprojects: Bump outdated 2025-06-27 15:50:28 +02:00
Francesco Tamagni bea95d0045 buffer: Fix max_length in read_fixed_string
So it is constrained both within the requested size and the buffer's
size.
2025-06-26 12:25:01 +02:00
Ole André Vadla Ravnås 57d2a83548 subprojects: Prepare for release 2025-06-23 18:44:25 +02:00
Ole André Vadla Ravnås 4474490f9b subprojects: Bump outdated 2025-06-23 18:41:09 +02:00
Ole André Vadla Ravnås a9ba854aa7 package-manager: Fix the dev logic 2025-06-22 10:22:42 +02:00
Ole André Vadla Ravnås 47c265b3df package-manager: Only bump if explicitly requested 2025-06-20 21:37:31 +02:00
Ole André Vadla Ravnås 36200d4c17 subprojects: Prepare for release 2025-06-20 15:45:32 +02:00
Ole André Vadla Ravnås bd1f855f4a subprojects: Bump outdated 2025-06-20 15:44:10 +02:00
Ole André Vadla RavnåsandHåvard Sørbø d752b63d3f package-manager: Improve manifest handling
To get us closer to npm's behavior.

Co-authored-by: Håvard Sørbø <[email protected]>
2025-06-20 15:43:29 +02:00
Ole André Vadla Ravnås a66e35d457 package-manager: Improve progress reporting 2025-06-20 11:46:30 +02:00
Ole André Vadla Ravnås 931270de32 package-manager: Refactor a little bit 2025-06-20 11:45:50 +02:00
Ole André Vadla Ravnås 90d54afbf4 promise: Add Future.then() and Future.get_result() 2025-06-20 10:58:00 +02:00
Ole André Vadla Ravnås 0a75b51e7b package-manager: Fix dependency install deadlock
A deadlock could occur when a package's sub-dependency was also a
dependency of another package higher up in the installation stack.
The sub-dependency would wait for the higher-level package to be
physically installed, but that package would not complete its own
installation until its sub-dependencies were resolved, creating a
circular wait.

Refactor the installation logic to first perform the physical
installation of a package. Once the package is on disk, a promise
tracking its physical presence is resolved. Only then does the process
recurse to install the package's own dependencies. This ensures that
any other part of the installation process waiting for this specific
package can proceed, breaking the cycle.
2025-06-20 10:17:38 +02:00
Ole André Vadla Ravnås 20d5d121b7 subprojects: Prepare for release 2025-06-20 01:13:54 +02:00
Ole André Vadla Ravnås dc71534220 subprojects: Bump outdated 2025-06-20 01:12:26 +02:00
Ole André Vadla Ravnås 35afee9b4a package-manager: Handle tarballs with root entries
Like if there's a directory entry for "package/", or somehow any files
at the root level.
2025-06-20 01:11:39 +02:00
Ole André Vadla Ravnås 7b130e6eba package-manager: Fix handling of scoped specs 2025-06-20 01:11:39 +02:00
Ole André Vadla Ravnås d28c46c332 package-manager: Fix a stylistic inconsistency 2025-06-20 01:11:39 +02:00
Ole André Vadla Ravnås ab103a73ca package-manager: Simplify substring logic 2025-06-20 01:11:39 +02:00
Ole André Vadla Ravnås 7b7d9acf8c subprojects: Prepare for release 2025-06-19 23:25:44 +02:00
Ole André Vadla Ravnås 215076a0fa subprojects: Bump outdated 2025-06-19 23:23:46 +02:00
Ole André Vadla Ravnås 3d47bf73b4 package-manager: Only report installed packages
The toplevel packages that were left untouched should not be included.

Also simplify the install() logic while at it.
2025-06-19 23:22:22 +02:00
Ole André Vadla Ravnås 7d84a44c7f package-manager: Fix the lockfile up-to-date path 2025-06-19 22:55:19 +02:00
Ole André Vadla Ravnås ef7e0a88e0 package-manager: Fix two stylistic inconsistencies 2025-06-19 22:53:09 +02:00
Ole André Vadla Ravnås 1f95416a77 subprojects: Prepare for release 2025-06-19 21:03:42 +02:00
Ole André Vadla Ravnås 80c7ec2dce meson: Fix build when libsoup is a subproject 2025-06-19 20:23:30 +02:00
Ole André Vadla Ravnås 69c68fdf7f subprojects: Bump outdated 2025-06-19 20:18:51 +02:00
Ole André Vadla Ravnås 7070042128 compiler: Make backend a shared library on Android
To avoid dynamic linking issues due to thread-local storage. This was
caused by our previous hack where we pretended Android was GOOS=linux
to work around the Go toolchain refusing `-buildmode=c-archive` for
GOOS=android.
2025-06-19 20:17:06 +02:00
Ole André Vadla Ravnås 9a4ce30be5 post-process: Support skipping ELF-cleaner step
It seems to corrupt shared library ELFs generated by the Go toolchain.
2025-06-19 20:08:47 +02:00
Ole André Vadla Ravnås 7731aea6f7 linux: Split out useful primitives into base
- check_kernel_version()
- FileDescriptor
- PidFileDescriptor
- MemoryFileDescriptor
2025-06-19 20:08:47 +02:00
Ole André Vadla Ravnås 3f8ace5f7b subprojects: Prepare for release 2025-06-18 23:34:57 +02:00
Ole André Vadla Ravnås d1e8aaa8e6 subprojects: Bump outdated 2025-06-18 23:33:44 +02:00
Ole André Vadla Ravnås 28a1084e7d compiler: Bump @frida/net to 5.0.0 2025-06-18 23:16:34 +02:00
Ole André Vadla Ravnås ac62e5d96d package-manager: Fix manifest progress
It should not have details, so it ends up in the toplevel progress
group, as far as UIs are concerned.
2025-06-18 22:56:43 +02:00
Ole André Vadla Ravnås 05bdfde104 package-manager: Add url property to Package
Only present in search results.
2025-06-18 19:49:44 +02:00
Ole André Vadla Ravnås 938e724f2d package-manager: Fix a stylistic inconsistency 2025-06-18 19:48:05 +02:00
Ole André Vadla Ravnås bf1d417445 Add PackageManager
To aid in discovering and installing Frida-specific packages without the
need for Node.js + npm. Power users and package maintainers will still
typically be using npm though. The goal is to streamline the consumption
of bridges and other Frida-specific packages.
2025-06-17 12:40:37 +02:00
Ole André Vadla Ravnås d9317e6265 base: Add FS namespace with filesystem helpers 2025-06-17 10:28:26 +02:00
Ole André Vadla Ravnås 01fd21f004 buffer: Add BufferReader.skip() 2025-06-17 10:28:26 +02:00
Ole André Vadla Ravnås e576f36f05 buffer: Allow trailing NULs in read_fixed_string() 2025-06-17 10:28:26 +02:00
He Li 9a7623a448 compiler: Fix missing shim assets (#1176)
Previously, the embeddedShims glob only matched files up to two directory
levels deep. This caused imports like:

    open node_modules/@frida/assert/internal/util/comparisons.js:
    file does not exist

This change adds an extra glob pattern that matches one more directory
level, allowing shim assets located one level deeper to be found correctly.
2025-06-17 10:27:49 +02:00
Ole André Vadla Ravnås 7dc0b5e4ee subprojects: Prepare for release 2025-06-13 16:28:17 +02:00
Ole André Vadla Ravnås a18eab4afa subprojects: Bump outdated 2025-06-13 16:27:21 +02:00
WorksButNotTested 8a30f241d1 ci: Fix builds of helpers and labrats 2025-06-13 16:25:05 +02:00
WorksButNotTested 78fbe5a20b tests: Disable slow test on armbe8 2025-06-13 16:25:05 +02:00
Ole André Vadla Ravnås e667582d54 android: Bump frida-java-bridge in system-server 2025-06-13 16:22:25 +02:00
Ole André Vadla Ravnås f5dd273c8c subprojects: Prepare for release 2025-06-10 22:09:49 +02:00
Ole André Vadla Ravnås 5438597c19 subprojects: Bump outdated 2025-06-10 22:05:53 +02:00
WorksButNotTested bb1f944f43 ci: Fix emulator error propagation 2025-06-10 22:05:07 +02:00
Ole André Vadla Ravnås 294df78147 darwin: Bump frida-objc-bridge in internal agents 2025-06-10 22:04:16 +02:00
Ole André Vadla Ravnås 2f1d24f96f android: Bump frida-java-bridge in system-server 2025-06-10 22:02:29 +02:00
Ole André Vadla Ravnås 918c83d25c compiler: Update package-lock.json 2025-06-10 21:07:51 +02:00
Ole André Vadla Ravnås a580d22bb6 agents: Switch esbuild platform to node
Internal agent bundles were still built with `--platform=neutral`, so
esbuild ignored each package’s package.json metadata. Modules that
rely on Node-style resolution could therefore fail to bundle.
2025-06-10 21:04:44 +02:00
Ole André Vadla Ravnås 238b81c26d compiler: Switch esbuild platform to node
Neutral mode ignores package.json, so modules that rely on "main" or
"exports" fields were left unresolved. Setting PlatformNode lets esbuild
read package.json and resolve such modules correctly.

No functional change for code that was already valid under Neutral; it
just unbreaks packages that expect Node semantics.

Kudos to @hsorbo for helping track this one down.
2025-06-10 20:59:21 +02:00
Ole André Vadla Ravnås 413ba51568 plist: Fix XML output of empty dicts/arrays
Apple’s encoder emits <dict/> and <array/> for empty collections; we were
producing <dict></dict> and <array></array>. The stricter form makes it
harder to compare plists byte-for-byte.

Our to_xml() now emits the self-closing tags so its XML output matches
Apple’s encoder.
2025-06-10 20:48:55 +02:00
Ole André Vadla Ravnås 3767957065 plist: Fix offsetIntSize for binary output
When to_binary() builds a bplist, the trailer’s offset-size field must
encode the offset of the offset table itself. We were deriving
offsetIntSize from the last object’s offset, so a plist whose table began
at 0x100 or beyond could still advertise size = 1 and be rejected by
Core Foundation as corrupt.

Size is now chosen from offset_table_offset. The XML path (to_xml())
is unaffected.

Kudos to @mrmacete for helping track this one down.
2025-06-10 20:41:36 +02:00
Ole André Vadla Ravnås ec3b864007 subprojects: Prepare for release 2025-06-07 13:32:23 +02:00
Ole André Vadla Ravnås 93fc48d20e subprojects: Bump outdated 2025-06-07 13:30:19 +02:00
Ole André Vadla Ravnås 4f120d9e46 meson: Simplify the Vala flags logic 2025-06-07 13:29:46 +02:00
Ole André Vadla Ravnås f9ee24038b gadget: Correct QuickJS big-endian bytecode check 2025-06-07 13:27:49 +02:00
Ole André Vadla Ravnås 5692298b03 subprojects: Bump outdated 2025-06-07 11:23:12 +02:00
Ole André Vadla Ravnås 375be6181a compiler: Rename conflictful Go symbols in backend
To avoid conflicts when we're linked into a Go binary.
2025-06-07 11:22:36 +02:00
Ole André Vadla Ravnås e5fa1b1fab api: Add version defines and macros 2025-06-07 11:20:23 +02:00
Ole André Vadla Ravnås 8e76c7257b subprojects: Prepare for release 2025-06-06 22:11:36 +02:00
Ole André Vadla Ravnås 282927b5b6 subprojects: Bump outdated 2025-06-06 22:10:29 +02:00
Ole André Vadla Ravnås fe235491a5 compiler: Make the DeviceManager optional
It is no longer used, but we cannot drop the constructor argument
without breaking API.
2025-06-06 22:09:40 +02:00
Ole André Vadla Ravnås 46d4d1223a subprojects: Prepare for release 2025-06-06 14:11:13 +02:00
Ole André Vadla Ravnås 6f8d8cba28 linux: Fix the system-server.js build system logic 2025-06-06 13:26:51 +02:00
Ole André Vadla Ravnås 2ee3926912 subprojects: Bump outdated 2025-06-06 12:38:22 +02:00
Ole André Vadla Ravnås 11f93e20b8 compile-js-agent: Remove commented “npm link” example
As it is no longer relevant.
2025-06-06 12:37:32 +02:00
Ole André Vadla Ravnås ad15eb2b01 darwin: Switch reportcrash.js bundling to ESBuild 2025-06-06 12:36:27 +02:00
Ole André Vadla Ravnås 26c9cf3cc5 darwin: Switch osanalytics.js bundling to ESBuild 2025-06-06 12:34:21 +02:00
Ole André Vadla Ravnås 8176ea1361 linux: Switch system-server.js bundling to ESBuild 2025-06-06 12:29:35 +02:00
Ole André Vadla Ravnås ecc63e5591 barebone: Simplify the ESBuild invocation 2025-06-06 12:27:23 +02:00
Ole André Vadla Ravnås ac5898a547 barebone: Fix ESM-handling
Where we failed to await the returned Promise, so any errors would end
up being swallowed.
2025-06-06 11:38:16 +02:00
Ole André Vadla Ravnås 055360cbb6 barebone: Remove bridge globals 2025-06-06 11:37:07 +02:00
Ole André Vadla Ravnås c9b18a5f4b barebone: Switch runtime bundling to ESBuild 2025-06-06 11:36:28 +02:00
Ole André Vadla Ravnås eb55aef18e subprojects: Prepare for release 2025-06-05 22:05:20 +02:00
Ole André Vadla Ravnås 11ba9175d0 subprojects: Bump outdated 2025-06-05 21:11:15 +02:00
Ole André Vadla Ravnås 6dd7e203bf ci: Fix a stylistic inconsistency 2025-06-05 20:07:22 +02:00
Ole André Vadla Ravnås 3a312faa1e ci: Fix the Windows build step 2025-06-05 19:27:22 +02:00
Ole André Vadla Ravnås 6f97782eff meson: Warn when Compiler backend is auto-disabled 2025-06-05 19:21:48 +02:00
Ole André Vadla Ravnås 412e525210 cgo: Fix path logic when consumed as a subproject 2025-06-05 19:21:16 +02:00
Ole André Vadla Ravnås c6e8ef5a29 ci: Clean up and fix Compiler backend enable logic 2025-06-05 19:14:45 +02:00
Ole André Vadla Ravnås 0df0eefdc9 cgo: Treat arm64e as unsupported
As cgo does not yet support it.
2025-06-05 19:08:26 +02:00
Ole André Vadla Ravnås dc60f8bf10 ci: Simplify the Compiler backend enable logic 2025-06-05 19:01:31 +02:00
Ole André Vadla Ravnås 2b9f3764c5 ci: Disable Compiler backend for the emulator job 2025-06-05 18:55:35 +02:00
Ole André Vadla Ravnås 89e01be599 ci: Skip tests on macOS for now
So we can get back to a green baseline.
2025-06-05 18:49:26 +02:00
Ole André Vadla Ravnås 228a37fabf ci: Fix the compiler backend option passed in 2025-06-05 18:36:03 +02:00
Ole André Vadla Ravnås 40ec5e03cc subprojects: Bump outdated 2025-06-05 17:02:16 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 6acb6da386 ci: Explicitly enable compiler
So it's not silently disabled in cases where cgo should be available.

Co-authored-by: Håvard Sørbø <[email protected]>
2025-06-05 17:00:49 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 9b9c91c1f2 ci: Improve naming of the Go toolchain steps
Co-authored-by: Håvard Sørbø <[email protected]>
2025-06-05 17:00:49 +02:00
Ole André Vadla Ravnås c5809da386 ci: Temporarily remove the FreeBSD/arm64 job
Until we have a working runner for it.
2025-06-05 17:00:49 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 6b76a1b2d4 ci: Fix the native Windows/x86 job
Which was building for x86_64 instead of x86.

Co-authored-by: Håvard Sørbø <[email protected]>
2025-06-05 17:00:49 +02:00
Ole André Vadla Ravnås 3da7b8bbd0 submodules: Bump releng 2025-06-05 17:00:49 +02:00
Ole André Vadla Ravnås adc93c3bf8 ci: Add native job for Windows/arm64 2025-06-05 17:00:49 +02:00
Ole André Vadla Ravnås b85397b690 ci: Install MinGW in the Windows native jobs 2025-06-05 17:00:49 +02:00
Ole André Vadla Ravnås b22326f233 ci: Add Go to the build jobs 2025-06-05 17:00:49 +02:00
Ole André Vadla Ravnås 531cfb17c0 ci: Remove trailing whitespace 2025-06-05 17:00:49 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 0a4bb7aed5 compiler: Normalize paths passed to typescript-go
So it also works on Windows.

Co-authored-by: Håvard Sørbø <[email protected]>
2025-06-05 17:00:49 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 274898d39c compiler: Fix handling of TypeScript diagnostics
Where ESBuild Message entries without notes were incorrectly handled.

Co-authored-by: Håvard Sørbø <[email protected]>
2025-06-05 17:00:49 +02:00
Ole André Vadla RavnåsandHåvard Sørbø c6c30833c8 compiler: Avoid Go alignment bug on Windows/x86_64
Where C arguments passed on the stack that are smaller than 8 bytes are
incorrectly laid out when calling into the Go runtime.

Co-authored-by: Håvard Sørbø <[email protected]>
2025-06-05 17:00:49 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 7b30a9c516 compiler: Fix cross-platform build issues
Co-authored-by: Håvard Sørbø <[email protected]>
2025-06-05 17:00:49 +02:00
Ole André Vadla Ravnås 32220057a8 meson: Allow compiler backend w/o local backend
Now that it no longer needs it for script execution.
2025-06-02 09:39:34 +02:00
Ole André Vadla RavnåsandHåvard Sørbø b7284691ca compiler: Move to ESBuild and typescript-go
For massively improved performance, and to reduce our maintenance burden
by no longer having to maintain a bundler.

Also add options to configure the output and bundle format, and support
disabling type checks.

Co-authored-by: Håvard Sørbø <[email protected]>
2025-06-01 23:46:10 +02:00
Ole André Vadla Ravnås 71a1b0f800 subprojects: Bump outdated 2025-06-01 11:04:52 +02:00
Ole André Vadla Ravnås b8b42a904b submodules: Bump releng 2025-06-01 11:04:51 +02:00
WorksButNotTested fdb4c5107c ci: Add jobs that test on armbe8 and arm64be (#1162) 2025-05-29 21:30:35 +02:00
Francesco Tamagni 8108d4d954 Plug Interceptor singleton leaks (#1167) 2025-05-29 21:29:15 +02:00
Ole André Vadla Ravnås 44a9757589 subprojects: Prepare for release 2025-05-29 17:32:06 +02:00
Ole André Vadla Ravnås 8c939d4954 subprojects: Bump outdated 2025-05-29 17:30:09 +02:00
Francesco Tamagni 8bb0dd14a4 device: Allow agent sessions to detach before release (#1164)
To be robust against scenarios where an out-of-order detach could lead
to indefinite hang at release time.
2025-05-29 17:22:57 +02:00
Ole André Vadla Ravnås 59619f57ca subprojects: Prepare for release 2025-05-28 23:17:01 +02:00
Ole André Vadla Ravnås 5ed7378bb0 subprojects: Bump outdated 2025-05-28 23:16:07 +02:00
londek 4d2bba4b2a darwin: Fix the launchd agent (#1166)
Which was still using an old GumJS API that is now gone.
2025-05-28 23:11:27 +02:00
Ole André Vadla Ravnås e2e2eaab82 subprojects: Prepare for release 2025-05-24 21:03:20 +02:00
Ole André Vadla Ravnås d286cbb09c subprojects: Bump outdated 2025-05-24 21:01:59 +02:00
Ole André Vadla Ravnås c910622a6a compile-js-agent: Explicitly run the build script
To ensure incremental compilation works consistently, as `npm install`
will not always run the `prepare` script.
2025-05-24 21:00:59 +02:00
Ole André Vadla Ravnås 7599500a3b compile-js-agent: Add commented “npm link” example 2025-05-24 20:59:14 +02:00
Ole André Vadla Ravnås fe4db7e37f compile-js-agent: Improve error-reporting
By capturing both stdout and stderr.
2025-05-24 20:58:33 +02:00
Ole André Vadla Ravnås 6064d0c084 Fix agents generated by latest frida-compile
We need to explicitly declare internal agents as ESM now that the
TypeScript compiler is more conformant and ends up generating CommonJS
glue code.

This fixes our Darwin and Android agents, as well as the Barebone
backend's script runtime.
2025-05-24 20:50:43 +02:00
Ole André Vadla Ravnås f970529e08 subprojects: Prepare for release 2025-05-22 21:39:32 +02:00
Ole André Vadla Ravnås 031614ddc2 compiler: Fix asset bundling logic on Windows
Where virtual paths were stored with the wrong path separator.
2025-05-22 21:20:34 +02:00
Ole André Vadla Ravnås 71d82bcebc subprojects: Bump outdated 2025-05-22 18:22:36 +02:00
Ole André Vadla Ravnås 9c7759cb53 tests: Adjust profile-compiler.sh to new layout 2025-05-22 18:20:21 +02:00
Ole André Vadla Ravnås 11b3e1415f Upgrade to frida-compile 18
Now with TypeScript 5.8.3, latest frida-fs, etc.
2025-05-22 18:17:44 +02:00
Ole André Vadla Ravnås 420370257e subprojects: Prepare for release 2025-05-20 23:12:10 +02:00
Ole André Vadla Ravnås 36948a3f22 subprojects: Bump outdated 2025-05-20 23:10:16 +02:00
Ole André Vadla Ravnås 9fd3a7e104 compiler: Bump @frida/rollup-plugin-node-polyfills
Which was depending on the old frida-fs.
2025-05-20 23:08:11 +02:00
Ole André Vadla Ravnås cf1766d199 subprojects: Prepare for release 2025-05-20 22:40:50 +02:00
Ole André Vadla Ravnås 67fa4db816 Bump frida-compile and frida-fs 2025-05-20 22:39:22 +02:00
Ole André Vadla Ravnås 8e9363cfb5 subprojects: Bump outdated 2025-05-20 22:06:37 +02:00
Ole André Vadla Ravnås 710de8f174 submodules: Bump releng 2025-05-20 22:06:36 +02:00
Ole André Vadla Ravnås 350cfb2d30 subprojects: Prepare for release 2025-05-17 23:48:11 +02:00
Ole André Vadla Ravnås 95ca3422ce subprojects: Bump outdated 2025-05-17 23:46:48 +02:00
Ole André Vadla Ravnås 01cc4d15ac android: Bump frida-java-bridge to 7.0.1 2025-05-17 23:41:13 +02:00
Ole André Vadla Ravnås f8943edf87 darwin: Bump frida-objc-bridge to 8.0.4 2025-05-17 23:40:27 +02:00
Ole André Vadla Ravnås 80ff031073 base: Bump interface versions to match major version 2025-05-17 22:53:42 +02:00
Ole André Vadla Ravnås d133485443 subprojects: Prepare for release 2025-05-17 19:45:33 +02:00
Ole André Vadla Ravnås 56be2c35ad subprojects: Bump outdated 2025-05-17 19:10:44 +02:00
Ole André Vadla Ravnås 9c70e82545 meson: Require Node.js for Darwin and Android too
Now that these have agents built using frida-compile.
2025-05-17 19:07:58 +02:00
Ole André Vadla Ravnås a51fe412c2 subprojects: Bump outdated 2025-05-17 11:46:33 +02:00
Ole André Vadla Ravnås 87916f44b6 Move off deprecated GumJS APIs
Which are now gone.
2025-05-17 11:44:20 +02:00
Ole André Vadla Ravnås e58274b2a0 barebone: Upgrade Module API implementation 2025-05-17 11:43:11 +02:00
Ole André Vadla Ravnås f920aec415 git: Ignore Barebone's script-runtime.js 2025-05-17 11:42:35 +02:00
Ole André Vadla Ravnås f310cd876d Bump @types/frida-gum in internal agents 2025-05-17 11:41:49 +02:00
Ole André Vadla Ravnås dfce66b4b2 compiler: Bump @types/frida-gum 2025-05-17 11:03:37 +02:00
Ole André Vadla Ravnås cc554570f0 ios: Add frida-objc-bridge to agents
Now that the bridges are no longer baked into GumJS.
2025-05-17 09:55:14 +02:00
Ole André Vadla Ravnås 8311484510 android: Add frida-java-bridge to agent
Now that the bridges are no longer baked into GumJS.
2025-05-17 09:55:10 +02:00
Ole André Vadla Ravnås d1b3cb273c barebone: Factor out JS agent build logic 2025-05-17 09:27:33 +02:00
Ole André Vadla Ravnås 4f05cb60ce subprojects: Prepare for release 2025-05-14 15:26:46 +02:00
Ole André Vadla Ravnås 58b8a29938 subprojects: Bump outdated 2025-05-14 15:25:26 +02:00
Ole André Vadla Ravnås 524fa7c68a subprojects: Bump outdated 2025-05-14 09:40:18 +02:00
Ole André Vadla Ravnås fad0ea0209 submodules: Bump releng 2025-05-14 09:40:18 +02:00
Ole André Vadla Ravnås 0d6c0c4e60 subprojects: Prepare for release 2025-05-09 17:43:28 +02:00
Ole André Vadla Ravnås 1403ce084c subprojects: Bump outdated 2025-05-09 17:42:23 +02:00
Ole André Vadla Ravnås 6e29f7b3b6 fruity: Keep TcpTunnelConnection keypair alive
Now that TcpTunnelConnection no longer holds a reference of its own.
2025-05-09 17:33:38 +02:00
Ole André Vadla Ravnås 65d58b8a71 fruity: Use Apple's CoreDeviceProxy as fallback
So we can support systems where NCM is problematic.
2025-05-09 16:06:49 +02:00
Ole André Vadla Ravnås 80a3cb7a89 fruity: Add TcpTunnelConnection.open_stream() 2025-05-09 16:05:12 +02:00
Ole André Vadla Ravnås 59ad0989a7 fruity: Move lockdown service bits to UsbmuxTransport 2025-05-09 15:28:38 +02:00
Ole André Vadla Ravnås 0bdea096d1 fruity: Retransmit mDNS-SD request every 250 ms
Just in case we transmit it too early, we may need to retransmit.
2025-05-09 14:53:17 +02:00
Ole André Vadla Ravnås 3b62211346 subprojects: Prepare for release 2025-05-09 11:55:56 +02:00
Ole André Vadla Ravnås 7bd2507326 subprojects: Bump outdated 2025-05-09 11:54:51 +02:00
Ole André Vadla Ravnås 63739cc623 fruity: Handle OPACK boolean and compact integers
Support for the latter is needed during pairing on iOS 18.4.1.
2025-05-09 11:54:07 +02:00
Ole André Vadla Ravnås ab3026a1ed fruity: Improve portable tunnel error-handling
When we use lockdown to determine if the iDevice supports tunnels, and
that fails due to lack of lockdown-level pairing, simply assume that the
OS supports it.
2025-05-09 11:32:12 +02:00
Ole André Vadla Ravnås 6b712f2262 fruity: Add timeout to the Linux netif wait logic 2025-05-09 11:30:32 +02:00
Ole André Vadla Ravnås e3607bf260 fruity: Handle NetworkManager DISCONNECTED+CARRIER
So we actually wait until the device is ready when it quickly passes
through state=DISCONNECTED with reason=CARRIER.
2025-05-09 11:03:01 +02:00
Ole André Vadla Ravnås c58ad9bec6 fruity: Initiate pairing on macOS too, if needed 2025-05-09 09:52:42 +02:00
Ole André Vadla Ravnås 46a42f8c3d fruity: Move to XpcObjectReader.check_nserror() 2025-05-09 09:51:21 +02:00
Ole André Vadla Ravnås bc9d168581 xpc-object-reader: Add check_nserror() 2025-05-09 09:51:03 +02:00
Ole André Vadla Ravnås 9c8290b51b fruity: Tweak macOS CreateAssertion error handling
So we provide a clean error message when it fails.
2025-05-09 08:52:25 +02:00
Ole André Vadla Ravnås 086af542c9 subprojects: Prepare for release 2025-05-08 22:43:14 +02:00
Ole André Vadla Ravnås badd66adaf subprojects: Bump outdated 2025-05-08 22:41:26 +02:00
Ole André Vadla Ravnås b1bda6f351 subprojects: Prepare for release 2025-05-08 21:30:56 +02:00
Ole André Vadla Ravnås 7b43736e43 api: Install our GLib .gir files if needed
I.e. on systems without such infrastructure in place.
2025-05-08 19:21:15 +02:00
Ole André Vadla Ravnås 5cf879aac8 subprojects: Bump outdated 2025-05-08 17:06:24 +02:00
Ole André Vadla Ravnås b983f9b3fc bus: Remove the device property
Which wasn't meant to be exposed in the first place.
2025-05-07 19:32:46 +02:00
Ole André Vadla Ravnås 55e5cfa7e7 device-manager: Fix crash on early close()
In situations where HostSessionService start() gets cancelled.
2025-05-07 15:44:05 +02:00
Ole André Vadla Ravnås b8319f21e2 web-service: Fix handling of TLS connections
The remote address logic did not take them into account.
2025-05-07 15:21:02 +02:00
Ole André Vadla Ravnås 326190263d gadget: Unseal internal classes
To fix compiler warnings.
2025-05-07 14:41:45 +02:00
Ole André Vadla Ravnås 9acb2dcacd api: Include Injector type struct in the .h 2025-05-07 14:40:23 +02:00
Ole André Vadla Ravnås 2dcabf6a12 api: Hide AgentMessageSink in the .gir 2025-05-03 13:42:08 +02:00
Ole André Vadla Ravnås dce1c12de9 meson: Provide {GLib,GObject}-2.0.gir
For language bindings consuming us as a subproject.

This is a stopgap until we improve our SDKs so .gir assets are included.
2025-04-30 16:39:46 +02:00
Ole André Vadla Ravnås 1d9b0a4787 api: Fix up FridaBase references in the .gir 2025-04-30 16:29:34 +02:00
Ole André Vadla Ravnås f286a57c9c subprojects: Prepare for release 2025-04-25 22:35:55 +02:00
Ole André Vadla Ravnås 7cdc1fa5cd subprojects: Bump outdated 2025-04-25 22:34:26 +02:00
WorksButNotTested b3f7cfec01 linux: Update helpers for armbe8, arm64be and arm64beilp32 (#1160) 2025-04-17 18:36:28 +02:00
Ole André Vadla Ravnås 92f7b0b2a3 subprojects: Bump outdated 2025-04-17 18:15:36 +02:00
WorksButNotTested 7445ad2067 tests: Support big-endian arm64 2025-04-17 18:10:58 +02:00
WorksButNotTested a55e4dc331 tests: Fix labrat support to cover all systems (#1149) 2025-04-17 14:54:26 +02:00
WorksButNotTested 482f0ebebe tests: Skip slow tests on big-endian ARM (#1148) 2025-04-17 14:47:42 +02:00
Ole André Vadla Ravnås 4df7f6f422 subprojects: Prepare for release 2025-04-17 13:53:44 +02:00
Ole André Vadla Ravnås 96a3766f22 subprojects: Bump outdated 2025-04-17 13:52:03 +02:00
Ole André Vadla Ravnås 759dc3aae1 subprojects: Prepare for release 2025-04-16 20:26:45 +02:00
Ole André Vadla Ravnås 23e1dff791 subprojects: Bump outdated 2025-04-16 20:25:26 +02:00
Ole André Vadla Ravnås 08a9ccfe55 subprojects: Bump outdated 2025-04-16 20:16:43 +02:00
Ole André Vadla Ravnås 9f87f61f8e subprojects: Prepare for release 2025-04-14 17:59:46 +02:00
Ole André Vadla Ravnås e323cb1b88 subprojects: Bump outdated 2025-04-14 17:58:21 +02:00
Ole André Vadla Ravnås ef0bb9e844 darwin: Update injector dyld init detection for iOS 18.4 2025-04-14 17:56:53 +02:00
Shane G 35acf74f95 fruity: Update injector dyld init detection for iOS 18.4 (#1154) 2025-04-11 22:32:30 +02:00
Francesco Tamagni 3041f010fd network-stack: Reduce delay between writes
By flagging as writable as soon as some space is available, without
waiting for the low watermark.
2025-04-11 22:29:22 +02:00
Francesco Tamagni 310a3673bf network-stack: Fix TCP write chunk length (#1156) 2025-04-11 11:53:58 +02:00
Francesco Tamagni 270578183b network-stack: Always send enqueued data
This change makes sure `pcb.output()` is called even when no more
space is available on the queue, preventing stall.
2025-04-11 10:27:22 +02:00
Ole André Vadla Ravnås 0da9c2b3a1 subprojects: Prepare for release 2025-04-09 21:50:18 +02:00
Ole André Vadla Ravnås 615eb44e7d subprojects: Bump outdated 2025-04-09 21:48:38 +02:00
Ole André Vadla Ravnås bb3da1d561 network-stack: Fix TcpConnection transmit logic 2025-04-08 22:39:06 +02:00
Ole André Vadla Ravnås d391dc98ce network-stack: Improve VirtualStream locking
To improve batching and avoid unnecessary scheduling on Frida's thread.
2025-04-08 12:04:52 +02:00
Ole André Vadla Ravnås 4b34cb09a4 virtual-stream: Allow update_pending_io() w/o lock
For convenience when a subclass doesn't want to update any other state
before calling it.
2025-04-08 12:03:41 +02:00
Ole André Vadla Ravnås afd27c4235 subprojects: Prepare for release 2025-04-07 19:32:42 +02:00
Ole André Vadla Ravnås 794048e84e subprojects: Bump outdated 2025-04-07 19:31:49 +02:00
Francesco Tamagni 2b7c49c752 channel: Break read loop on empty buffer (#1150) 2025-04-07 19:29:40 +02:00
Ole André Vadla Ravnås 903d941ff0 device-manager: Fix teardown logic
Where we would also stop() the HostSessionService in cases where it
hadn't been start()ed.
2025-04-07 13:12:21 +02:00
Ole André Vadla Ravnås e5b422b8db subprojects: Prepare for release 2025-04-07 10:08:54 +02:00
Ole André Vadla Ravnås aac74e662e subprojects: Bump outdated 2025-04-07 10:08:01 +02:00
Ole André Vadla Ravnås ddab33010d subprojects: Prepare for release 2025-04-05 14:46:58 +02:00
Ole André Vadla Ravnås a2a77cdfa5 subprojects: Bump outdated 2025-04-05 11:14:07 +02:00
Ole André Vadla Ravnås 672bf55778 freebsd: Unseal Binjector to fix compilation
The C glue code depends on its fields for now.
2025-04-05 11:13:38 +02:00
Ole André Vadla Ravnås 722949d5fa subprojects: Prepare for release 2025-04-05 11:10:31 +02:00
Ole André Vadla Ravnås 5fed974dc5 subprojects: Bump outdated 2025-04-05 09:38:34 +02:00
Ole André Vadla Ravnås 7d2c0682e3 qnx: Unseal Qinjector to fix compilation
The C glue code depends on its fields for now.
2025-04-05 09:36:50 +02:00
Ole André Vadla Ravnås fcb66f61da subprojects: Prepare for release 2025-04-05 08:52:16 +02:00
Ole André Vadla Ravnås 23f1086bac subprojects: Bump outdated 2025-04-05 08:50:59 +02:00
Ole André Vadla Ravnås a0cf6a940b meson: Provide Gio-2.0.gir for convenience
So users won't need any GObject Introspection packages installed when
they're building language bindings and consuming us as a subproject.
2025-04-03 15:19:55 +02:00
Ole André Vadla Ravnås 0a4ee7acbb meson: Fix frida_girdir for the uninstalled case
It should point at the directory containing the refined .gir, not the
raw one from the Vala compiler.
2025-04-03 15:15:26 +02:00
Ole André Vadla Ravnås b8aeff0854 api: Seal classes not meant to be subclassed
Except for inner classes, as that results in C compiler warnings.
2025-04-03 12:23:57 +02:00
Ole André Vadla Ravnås 6a1f43f052 api: Fix vapi entries for sealed classes 2025-04-03 10:12:39 +02:00
Ole André Vadla Ravnås 87c293c831 api: Drop some accidentally exposed types 2025-04-02 18:40:57 +02:00
Ole André Vadla Ravnås 3e75fc9b84 subprojects: Prepare for release 2025-03-31 21:22:52 +02:00
Ole André Vadla Ravnås 1b6ca8fe46 subprojects: Bump outdated 2025-03-31 20:17:34 +02:00
Ole André Vadla Ravnås 9e35e245b1 host-session: Add support for remote services
So they are no longer exclusively an out-of-band local API. This means
that ControlService/frida-server can serve service sessions.
2025-03-31 20:10:49 +02:00
Ole André Vadla Ravnås 4a8c0bb13b api: Expose sealed classes 2025-03-31 20:10:49 +02:00
Ole André Vadla Ravnås 7c39f1783a stream: Factor out IOStream commonalities 2025-03-31 20:10:49 +02:00
Ole André Vadla Ravnås 194f025a98 host-session: Add support for remote channels
So they are no longer exclusively an out-of-band local API. This means
that ControlService/frida-server can serve channels.
2025-03-31 20:10:46 +02:00
Ole André Vadla Ravnås e6b2a6d6dd session: Remove unused ObjectPath constant 2025-03-30 16:26:58 +02:00
Ole André Vadla Ravnås e66b93b647 host-session: Factor out duplicated local logic 2025-03-28 17:18:35 +01:00
Ole André Vadla Ravnås 4a887eaed5 host-session: Rename BaseDBusHostSession to LocalHostSession
For clarity.
2025-03-28 17:18:17 +01:00
Ole André Vadla Ravnås 180075a7a0 control-service: Fix session logic for remote device 2025-03-28 15:29:14 +01:00
Ole André Vadla Ravnås 20ebf7fa15 host-session-provider: Add unlink_agent_session()
To support use-cases such as ControlService, where one specific client
gets disconnected and we need to tear down its agent sessions.
2025-03-28 15:29:11 +01:00
Ole André Vadla Ravnås 1018aca28d compiler: Bump frida-compile 2025-03-25 20:14:26 +01:00
Ole André Vadla Ravnås 93870b9f66 compiler: Bump @types/frida-gum 2025-03-24 17:33:23 +01:00
Ole André Vadla Ravnås 259ce04fe6 subprojects: Prepare for release 2025-03-21 14:20:50 +01:00
Ole André Vadla Ravnås 4cdfa4b09c subprojects: Bump outdated 2025-03-21 14:19:27 +01:00
Ole André Vadla Ravnås 7b54e41f88 droidy: Fix the MAX_MESSAGE_LENGTH declaration
The new maximum exceeds the range of a uint16.
2025-03-21 14:18:59 +01:00
Ole André Vadla Ravnås c7b1e17c3e subprojects: Prepare for release 2025-03-21 13:57:14 +01:00
Ole André Vadla Ravnås e844297a61 subprojects: Bump outdated 2025-03-20 20:38:52 +01:00
Ole André Vadla Ravnås 30b00eaa64 subprojects: Bump outdated 2025-03-20 17:00:25 +01:00
Ole André Vadla Ravnås 2109c38e06 submodules: Bump releng 2025-03-20 17:00:25 +01:00
Ole André Vadla Ravnås 1a3da37cf8 compiler: Bump @types/frida-gum 2025-03-20 16:59:53 +01:00
Jan S. 3d9fab2b0d fruity: Fix Input/Output Error on Windows (#1144)
By skipping devices with an empty UDID.
2025-03-19 15:12:07 +01:00
philippmao c58212fe8c droidy: Support more than ~8 ADB-connected devices (#1145)
By bumping the message size limit.
2025-03-19 15:07:44 +01:00
Ole André Vadla Ravnås bce2650980 subprojects: Bump outdated 2025-03-19 10:51:37 +01:00
Ole André Vadla Ravnås 0f03a0ee19 submodules: Bump releng 2025-03-19 10:51:36 +01:00
Ole André Vadla Ravnås d9b4d20adf linux: Include linux/unistd.h for syscall constant
Which, depending on the libc, may not be implicitly included.
2025-03-18 19:11:03 +00:00
Ole André Vadla Ravnås a8db90d6a5 subprojects: Bump outdated 2025-03-18 19:51:10 +01:00
Ole André Vadla Ravnås edcb76f066 submodules: Bump releng 2025-03-18 19:51:09 +01:00
Ole André Vadla Ravnås 1f72d5f102 subprojects: Prepare for release 2025-03-13 19:09:35 +01:00
Ole André Vadla Ravnås 8336d42b94 server: Create DeviceManager without local backend
Since we're pulling it in manually in order to run the frida-helper
in-process, we want to avoid having both implementations.

This reduces our footprint from 58M down to 49M on macOS, up from 46M
before the --device feature.
2025-03-13 19:06:33 +01:00
Ole André Vadla Ravnås 9404147517 device-manager: Support running w/o local backend
So consumers that don't need it can get a smaller footprint.
2025-03-13 19:01:20 +01:00
Ole André Vadla Ravnås ed464e9ccf subprojects: Bump outdated 2025-03-13 15:07:33 +01:00
Ole André Vadla Ravnås ce6178e125 server: Add --device for serving a specific device 2025-03-13 14:43:36 +01:00
Ole André Vadla Ravnås 0e69ec3e77 control-service: Support serving a specific Device 2025-03-13 14:42:57 +01:00
Ole André Vadla Ravnås 4eba770491 subprojects: Bump outdated 2025-03-13 14:09:11 +01:00
WorksButNotTested dc022e4bbe linux: Build helpers for arm64be and arm64beilp32 (#1141) 2025-03-13 13:47:09 +01:00
WorksButNotTested df04bb40c3 linux: Add support for arm64beilp32 (#1140) 2025-03-12 14:26:54 +01:00
WorksButNotTested 0f685ea496 linux: Support building helpers for armbe8 (#1139) 2025-03-12 10:07:43 +01:00
WorksButNotTested 48bfb1e054 linux: Add support for arm64be 2025-03-12 09:33:04 +01:00
Ole André Vadla Ravnås ab8a0a3927 compiler: Bump @types/frida-gum 2025-03-12 08:55:15 +01:00
Ole André Vadla Ravnås 9594e1a8b8 linux: Handle compat ranges during injection
So our spurious range detection doesn't make an incomplete candidate,
and we might end up picking the wrong one.
2025-03-03 23:38:47 +01:00
Ole André Vadla Ravnås 60a6770dba darwin: Fix racy leakage of memory during teardown
Where DarwinHelperBackend.close() would cancel dispatch sources, but
return before the cancel handler got a chance to run. While this leak
typically happened on teardown and wasn't necessarily a big deal
locally, the worse part was that we also leaked large regions of memory
in remote processes that we uninjected from just before teardown.
2025-02-28 17:34:49 +01:00
Ole André Vadla Ravnås c5376242e9 darwin: Fix HelperBackend MainContext assumptions
We should not blindly dispatch to the default one, but take note at
construction time.

This is to avoid surprises down the road, and to improve consistency
across the codebase.
2025-02-28 17:34:49 +01:00
Ole André Vadla Ravnås 17d6161435 linux: Avoid spurious .so ranges during injection
By checking that the mapping starts at file offset zero, and considering
all candidates ranked by the number of mappings, and whether executable
mappings exist in a given cluster.

Now that Gum.Module objects live longer, and may have an Gum.ElfModule
that has the ELF mapped, there's a much higher likelihood of running
into such spurious ranges.
2025-02-20 10:18:44 +01:00
Ole André Vadla Ravnås 26d9b9b6b1 fruity: Fix crash in the Linux getifaddrs() logic
Which failed to handle interfaces without an address.
2025-02-20 08:48:30 +01:00
Ole André Vadla Ravnås 1ed5590c77 submodules: Bump releng 2025-02-18 11:15:09 +01:00
Ole André Vadla Ravnås 25a283e43b ci: Fix the linux-x86 job
Now that ubuntu-latest refers to a newer Ubuntu release, we need to
move to the newer lib32stdc++ package version that matches that of
the gcc-multilib package.
2025-02-18 11:12:51 +01:00
Ole André Vadla Ravnås 04e04166b7 subprojects: Bump outdated 2025-02-18 11:12:51 +01:00
Ole André Vadla Ravnås 2c6c52d22a darwin: Port to the new ModuleResolver API 2025-02-18 11:12:51 +01:00
Ole André Vadla Ravnås ba7d01f232 subprojects: Prepare for release 2025-01-27 20:54:28 +01:00
Ole André Vadla Ravnås 8a16d42652 subprojects: Bump outdated 2025-01-27 20:51:53 +01:00
Ole André Vadla Ravnås 9c13120d67 fruity: Fix lockdown over CoreDevice regression
Introduced by the recent change in d1df792, where our RSDCheckin
includes an EscrowBag in order to support networked lockdown with
services such as “com.apple.crashreportmover”.

Turns out this broke support for quite a few other services, as the
presence of an EscrowBag requires that the particular service is able
to talk to AppleKeyStoreUserClient.

Not yet sure how to handle this. For now we'll maintain a list of
services that lack such privileges, so we can omit the EscrowBag for
those.

Kudos to @as0ler for reporting and helping troubleshoot.
2025-01-27 19:35:52 +01:00
Ole André Vadla Ravnås e70812a1e0 subprojects: Prepare for release 2025-01-23 20:46:57 +01:00
Ole André Vadla Ravnås 283381ca9e subprojects: Bump outdated 2025-01-23 20:31:30 +01:00
Mohamed Amine Amor 72a96226ce linux: Avoid risky code swaps with memfd regions
As they may not be writable, and unlike regular regions, ptrace() won't
help us in case of a missing writable bit.
2025-01-23 19:13:59 +01:00
Mohamed Amine Amor b6577afe81 linux: Relax injector's libc matching for Android
Due to how APEXes are bind-mounted.
2025-01-23 19:13:59 +01:00
Ole André Vadla Ravnås d1df7922bc fruity: Support networked lockdown for CoreDevice
Where we need to provide the remote unlock host key as part of the
RSDCheckin.

Kudos to @as0ler and @mrmacete for reporting and helping get to the
bottom of this one.
2025-01-23 18:41:01 +01:00
Ole André Vadla Ravnås af9c36ce6e xpc: Add support for Data objects 2025-01-23 15:27:47 +01:00
Ole André Vadla Ravnås da58033e9b subprojects: Prepare for release 2025-01-17 16:49:07 +01:00
Ole André Vadla Ravnås 702f3e83eb subprojects: Bump outdated 2025-01-17 16:46:54 +01:00
WorksButNotTested 7644f3dc6d linux: Revive support for ARM BE8 (#1130) 2025-01-17 16:30:59 +01:00
Ole André Vadla Ravnås 24d2d6f055 subprojects: Prepare for release 2025-01-14 19:35:29 +01:00
Ole André Vadla Ravnås 47d44f07ae subprojects: Bump outdated 2025-01-14 19:33:17 +01:00
Ole André Vadla Ravnås 8119fc7569 submodules: Bump releng 2025-01-14 19:33:17 +01:00
Ole André Vadla Ravnås 57409c8056 windows: Port injector to new Gum.Module API 2025-01-14 18:09:55 +01:00
Ole André Vadla Ravnås f497a764b6 subprojects: Prepare for release 2025-01-13 22:20:39 +01:00
Ole André Vadla Ravnås 20b7856fae subprojects: Bump outdated 2025-01-13 22:18:02 +01:00
Ole André Vadla Ravnås f2a81c03e3 subprojects: Prepare for release 2025-01-10 02:04:08 +01:00
Ole André Vadla Ravnås 79b34b9772 subprojects: Bump outdated 2025-01-10 02:02:04 +01:00
Ole André Vadla Ravnås 2fb702ba80 subprojects: Bump outdated 2025-01-09 23:35:23 +01:00
Ole André Vadla Ravnås 262d8f91e5 submodules: Bump releng 2025-01-09 23:35:22 +01:00
Ole André Vadla Ravnås 7638290dcb agent: Exclude OS/arch symbols in version script
Newer toolchains, such as the default toolchain on FreeBSD 14.2,
don't like references to symbols that don't exist. Instead of
listing JNI_OnLoad, which is only defined for Android builds,
we use a separate version script for Android instead.
2025-01-09 23:34:01 +01:00
Ole André Vadla Ravnås 1e0f37faf6 subprojects: Prepare for release 2025-01-09 13:18:38 +01:00
Ole André Vadla Ravnås fb46efaa12 compiler: Bump @types/frida-gum 2025-01-09 13:16:05 +01:00
Ole André Vadla Ravnås bb4a906c16 subprojects: Bump outdated 2025-01-08 19:06:43 +01:00
Ole André Vadla Ravnås 34eff8e9d6 darwin: Fix iOS/tvOS compilation issues
By porting the remaining bits to the new Gum.Module API.
2025-01-06 16:37:55 +01:00
Ole André Vadla Ravnås f28e5d4493 subprojects: Bump outdated 2025-01-06 16:03:28 +01:00
Ole André Vadla Ravnås 6f3434b454 subprojects: Bump outdated 2025-01-06 01:11:39 +01:00
Ole André Vadla Ravnås 90c2420bae submodules: Bump releng 2025-01-06 01:11:38 +01:00
Ole André Vadla Ravnås 95394935cd Port to the new Gum.Module API 2025-01-06 01:09:07 +01:00
Ole André Vadla RavnåsandHåvard Sørbø a2ffb76ff3 ncm: Cap datagram count to 16 for performance
The layout computation could end up working its way down from a very
high number. Though we probably should optimize the layout computation,
there's no point for now.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-17 23:38:37 +01:00
Ole André Vadla Ravnås c1472f9cb8 Create FUNDING.yml 2024-12-12 13:37:04 +01:00
Ole André Vadla Ravnås aabe70d041 subprojects: Bump outdated 2024-12-09 00:58:03 +01:00
Ole André Vadla Ravnås abc464bf49 subprojects: Prepare for release 2024-12-09 00:52:26 +01:00
Ole André Vadla Ravnås b6d7c7259f subprojects: Prepare for release 2024-12-09 00:32:18 +01:00
Ole André Vadla Ravnås 78750a4644 subprojects: Bump outdated 2024-12-09 00:28:54 +01:00
Ole André Vadla RavnåsandHåvard Sørbø a68dc36d2d fruity: Boost NCM performance with multi-transfers
Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-08 22:45:07 +01:00
Ole André Vadla Ravnås de54b7e4cf subprojects: Bump outdated 2024-12-08 16:31:53 +01:00
Ole André Vadla Ravnås 1f292bb856 submodules: Bump releng 2024-12-08 16:31:52 +01:00
Ole André Vadla Ravnås 2025b7aaad fruity: Enable lwIP TCP timestamps and SACK
To align with the Linux IP stack's defaults.
2024-12-08 03:23:34 +01:00
Ole André Vadla Ravnås 534d860a42 meson: Bump lwIP TCP MSS to 4036
For better TCP tunnel performance.
2024-12-08 03:22:06 +01:00
Ole André Vadla Ravnås db28eb0e70 fruity: Fix crash on USB op creation during teardown 2024-12-08 03:20:39 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 8d0b735a75 fruity: Improve userspace NCM driver to perform batching
As we observed packet loss in bursty situations, and implementing
batching avoids it.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-08 01:55:38 +01:00
Ole André Vadla Ravnås 930776dcca compat: Create relative subproject symlinks
So the source tree can be moved without breaking things.
2024-12-07 16:08:52 +01:00
Ole André Vadla Ravnås 7a38663672 compat: Fix subproject symlink_to() error-handling 2024-12-07 15:55:22 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 3779ce9f64 vapi: Add SocketAddressUnion to libngtcp2.vapi
Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:24:13 +01:00
Ole André Vadla RavnåsandHåvard Sørbø b5065e275d fruity: Improve USB device handling on non-macOS
- Do not open a given USB device if kernel NCM is available, as opening
  may fail and won't actually do anything useful in the end.
- Throw when a kernel NCM interface lacks an IPv6 address, instead of
  silently degrading to legacy mode.
- Replace retry logic with a fixed 250 ms delay, applied when a device
  arrives after starting, or during a mode-switch.
- Change USB device configuration if needed.
- Wait for kernel NCM interface to be ready. For now this is limited to
  Linux systems with either NetworkManager or networkd.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:23:24 +01:00
Ole André Vadla RavnåsandHåvard Sørbø a682e51f37 fruity: Only assume jailed if connection refused
Bubble up all other errors.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:23:06 +01:00
Ole André Vadla RavnåsandHåvard Sørbø bdf120016a api: Avoid redundant writes to output files
Modify the output logic to skip writing to files if the contents remain
unchanged, preventing unnecessary file updates. This means quicker
incremental builds.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:23:00 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 61eb12f718 meson: Avoid parsing API multiple times
As Meson's custom_target() supports multiple outputs.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:22:54 +01:00
Ole André Vadla RavnåsandHåvard Sørbø e149f5e332 fruity: Avoid USB access in case of kernel NCM
So we won't run into permission issues, and avoid unneccessary work.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-26 23:04:10 +01:00
Ole André Vadla RavnåsandHåvard Sørbø ef4fa0de7d fruity: Account for frida-server bind() delay
Where we just opened the tunnel, but frida-server hasn't yet noticed the
new interface and had a chance to bind() on it. This means we should
wait a bit and try again. Otherwise we may end up falling back to
usbmuxd, and use a less desirable transport. And if we're really
unlucky, even that could fail, and we'd end up falling back to jailed
mode.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-26 22:02:47 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 1bd9d389b8 fruity: Fix direct channel reliability
Where we might establish the HostSession connection through usbmuxd, and
proceed to establish direct connections through the tunnel. This is
usually fine, except when an Apple service happens to bind to the same
port inside the tunnel. In that case we'd end up talking to that instead
of the broker port, which is listening on INADDR_ANY.

Kudos to @mrmacete for helping track this one down.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-26 19:43:42 +01:00
Ole André Vadla Ravnås b32408c607 device: Fix the constructor logic
Broken by the refactoring in 2790745.
2024-11-24 15:32:58 +01:00
Ole André Vadla Ravnås a8e01c2940 Fix some stylistic inconsistencies 2024-11-24 15:32:14 +01:00
Ole André Vadla Ravnås cd6366a4eb tests: Fix the HostSession suite 2024-11-24 00:58:28 +01:00
Ole André Vadla Ravnås 2c1cf1ec58 api: Add GIR attributes 2024-11-24 00:34:32 +01:00
Ole André Vadla Ravnås 279074501c api: Avoid exposing internal types 2024-11-24 00:33:17 +01:00
Ole André Vadla Ravnås 20cfd56a7a api: Generate a proper gir
- Needed types in frida-base included.
- Internal types omitted.
2024-11-23 23:54:20 +01:00
Ole André Vadla Ravnås d03bda5545 api: Omit APIs involving HostSession 2024-11-23 15:14:37 +01:00
Ole André Vadla Ravnås 951796196c api: Refactor generate.py to improve readability 2024-11-23 15:14:33 +01:00
Ole André Vadla Ravnås 312e38b2ec fruity: Improve TcpTunnelConnection teardown
So the VirtualNetworkStack is torn down right away upon the remote end
closing the connection, instead of once close() is called.

Also ensure any pending write operation is cancelled at that point.
2024-11-22 14:50:31 +01:00
Ole André Vadla Ravnås 36a8ffbb99 subprojects: Prepare for release 2024-11-14 00:30:38 +01:00
Ole André Vadla Ravnås aeb2c0f6e4 subprojects: Bump outdated 2024-11-14 00:28:54 +01:00
Ole André Vadla Ravnås d5591cc453 submodules: Bump releng 2024-11-14 00:28:54 +01:00
lx866 20f4df23a8 android: Revive injector's handling of shared libc ranges
So we still do the right thing if the target process' lowest libc.so
range is a shared mapping, for example:

    HNFRI:/ # grep libc.so /proc/22001/maps
    6e3e1cd000-6e3e2c7000 r--s 00000000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so
    71eb6c2000-71eb6ff000 r--p 00000000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so
    71eb6ff000-71eb781000 r-xp 0003d000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so
    71eb781000-71eb786000 r--p 000bf000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so
    71eb786000-71eb787000 rw-p 000c3000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so

Originally implemented in 5e8314f, but lost in the injector rewrite.
2024-11-14 00:21:58 +01:00
JunGe-Y 89033cd1e8 compat: Fix compilation when using non-UTF-8 locales (#1122) 2024-11-13 23:55:57 +01:00
Ole André Vadla Ravnås a027f5b08e fruity: Skip jailed fallback in case of timeout 2024-11-13 20:37:07 +01:00
Ole André Vadla Ravnås 848f4b52e1 fruity: Expect networked device to respond quickly
When connecting to its pairing service, it should be reasonable to
assume that the TCP connection set up completes within two seconds.

This improves the UX when a device has gone to sleep, and its mDNS
records haven't yet timed out.
2024-11-13 20:35:42 +01:00
Ole André Vadla Ravnås e0524ad90b network-stack: Add open_tcp_connection_with_timeout() 2024-11-13 20:28:09 +01:00
Ole André Vadla Ravnås 5ce8ce0531 fruity: Always try USB transport first
As a network transport may be slower (best-case) or unavailable
(worst-case).
2024-11-13 20:15:52 +01:00
Ole André Vadla Ravnås 8f04f2f677 fruity: Fix TcpTunnelConnection teardown logic
Where it turns out IOStream.close_async() may throw other errors than
just IOError. This is a bug in gio-2.0.vapi, but still, once fixed there
we still want to catch (and ignore) all errors.

Kudos to @mrmacete for helping track this one down.
2024-11-13 18:03:38 +01:00
Ole André Vadla RavnåsandHåvard Sørbø f0593c2aec fruity: Fix QuicTunnelConnection teardown logic
And improve the ngtcp2 bindings.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-13 16:32:04 +01:00
Ole André Vadla RavnåsandHåvard Sørbø ec582967e8 fruity: Fix hang when a USB op starts at teardown
Which would result in such transfers never completing, as our USB worker
is no longer processing libusb events.

Kudos to @mrmacete for helping track this one down.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-13 13:23:39 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 4fce1c4321 fruity: Gracefully close TunnelConnection
Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-06 13:39:42 +01:00
Ole André Vadla Ravnås 667c7491b5 fruity: Relax NCM interface presence check
One operational network interface is sufficient.
2024-11-06 10:47:39 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 85de7a01fb fruity: Add support for the TCP tunnel protocol
And use it by default, to match Apple's new behavior.

The FRIDA_FRUITY_TUNNEL_PROTOCOL environment variable can be used to
revert back to QUIC.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-06 10:47:03 +01:00
Ole André Vadla Ravnås 8fdff55b80 subprojects: Bump outdated 2024-11-06 10:21:11 +01:00
Ole André Vadla Ravnås a420358565 submodules: Bump releng 2024-11-06 10:21:10 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 2457ac45f6 fruity: Fix edge-case in tunnel logic for older OS versions
When usbmuxd is not available, we would try to set up a tunnel
connection. This would then fail when the OS is too old for CoreDevice
support, and we would erroneously cache the Tunnel implementation in its
unopened state. This meant it could be used as if it was opened, causing
undefined behavior.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-28 15:01:40 +01:00
Ole André Vadla Ravnås e797e829d8 fruity: Fix CoreDevice UDID logic for modern devices 2024-10-26 08:54:27 +02:00
WorksButNotTested aa95167156 linux: Pick other temp dir when $TMPDIR is noexec 2024-10-21 22:40:47 +02:00
Ole André Vadla Ravnås 03d609c1a5 linux: Improve helpers Makefile to use internal Meson 2024-10-21 14:55:20 +02:00
Harry Gunnarsson 36619e51e7 linux: Support overriding config when building helpers 2024-10-21 14:55:20 +02:00
Harry Gunnarsson e2b462823c linux: Improve injector's MUSL compatibility
The loader string could look different on different platforms.
2024-10-21 14:32:52 +02:00
Andrew Werner e8ee891924 linux: Allocate stack for injector's remote calls
For some target programs it's not reasonable to assume that any hijacked
thread has a large stack. For example, in Go, stacks are often small and
are allocated on the heap. The injector bootstrap program uses kilobytes
of stack. In order to side-step this problem, this patch changes the
boostrapper to allocate an auxiliary stack for remote calls to use and,
for the bootstrapper and loader, uses it.

The calls to mmap and munmap don't use much stack, so they are fine.

Fixes #544.
2024-10-21 14:07:00 +02:00
Andrew Werner d0fe3a1ae9 linux: Rebuild helper bin files
This commit utilizes the containers created in [frida/docker-images#2]
to rebuild all the Linux injector helper binaries for all the
architectures. It uses a new script to rebuild them and hooks up CI to
rebuild them and make sure that they are all the same as what is checked
in. This should allow us to make changes to these binaries without any
pain and with the confidence that what is checked in matches the source.

[frida/docker-images#2]: https://github.com/frida/docker-images/pull/2
2024-10-20 17:09:55 +02:00
Ole André Vadla Ravnås b223fc4235 darwin: Update to the new RpcClient.call() API 2024-10-20 16:42:12 +02:00
Ole André Vadla Ravnås 5ad248a894 android: Update to the new RpcClient.call() API 2024-10-20 16:40:56 +02:00
Yoav ShaiandOle André Vadla Ravnås d774d0e064 gadget: Support loading assets from APK on Android
On Android, when apps have `extractNativeLibs` set to `false`, the
configuration and potentially script files for frida-gadget are not
extracted and cannot be read from the filesystem.

Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-20 16:40:15 +02:00
WorksButNotTested e11938c11f inject: Support binary data on stdin and stdout 2024-10-20 12:11:31 +02:00
WorksButNotTested fb0049af86 barebone: Support binary data in Script.post() 2024-10-20 12:11:31 +02:00
WorksButNotTested 2fe6922b25 rpc-client: Support binary data in call() 2024-10-20 12:11:31 +02:00
Ole André Vadla Ravnås c96d94f796 subprojects: Prepare for release 2024-10-14 15:32:15 +02:00
Ole André Vadla Ravnås a8b710bc54 subprojects: Bump outdated 2024-10-14 15:30:11 +02:00
Håvard SørbøandOle André Vadla Ravnås 2b0c4da879 fruity: Fix use-after-free in TcpConnection
The error callback might be called at a point where the PCB has already
been freed. This meant that us clearing its user data would result in a
use-after-free where a NULL pointer was written into the unknown.

Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-14 13:24:37 +00:00
Håvard SørbøandOle André Vadla Ravnås d0129614cd fruity: Fix DTXArgumentList.parse() GValue init
Where we were using the wrong setter when encountering an object. This
was caught by GLib's runtime checks, but this went unnoticed because we
usually build without them.

Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-14 13:22:41 +00:00
Håvard SørbøandOle André Vadla Ravnås 12348209da payload: Fix AddressSanitizer build regression
Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-14 13:19:56 +00:00
Ole André Vadla Ravnås 0451ce09b2 subprojects: Prepare for release 2024-10-11 11:18:27 +02:00
Ole André Vadla Ravnås 0fa9765871 subprojects: Bump outdated 2024-10-11 11:16:06 +02:00
ajwerner 71e1068150 ci: Download proper ndk version (#551)
We were relying on the version built into the image being correct. It is
now too new.
2024-10-11 11:13:44 +02:00
Francesco Tamagni 690cc30260 control-service: Fix null dereference on incoming connection (#1060) 2024-10-11 11:12:15 +02:00
Ole André Vadla Ravnås 557aefc898 subprojects: Prepare for release 2024-10-10 22:07:51 +02:00
Ole André Vadla Ravnås 088edc09d7 subprojects: Bump outdated 2024-10-10 22:06:52 +02:00
Ole André Vadla Ravnås 19f6a2f378 compiler: Bump @types/frida-gum 2024-10-10 21:30:42 +02:00
Ole André Vadla Ravnås 16c9035bca subprojects: Prepare for release 2024-10-10 20:18:24 +02:00
Ole André Vadla Ravnås fbb46912db subprojects: Bump outdated 2024-10-10 20:08:54 +02:00
Ole André Vadla Ravnås 11aa03695f submodules: Bump releng 2024-10-10 20:08:53 +02:00
Håvard SørbøandOle André Vadla Ravnås a23fba6ee9 fruity: Bail on iOS tunnel service versions pre-17
Instead of crashing.

Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-10 18:02:07 +00:00
Ole André Vadla RavnåsandHåvard Sørbø 364bf65c59 control-service: Fix reliability on CoreDevice systems
Where having a single transport broker listening on all interfaces may
result in an early TCP RST when trying to communicate with it from
inside a tunnel. The exact cause of this is not known, but we have
confirmed that having one broker per dynamic interface/tunnel does
resolve the issue. We also observed that listening on all interfaces,
but restricted to IPv6, also avoids the issue.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-10 19:03:41 +02:00
Ole André Vadla RavnåsandHåvard Sørbø dcdfcf53d1 fruity: Fix USB mode parsing on iOS < 16
Where the mode is a 3 byte blob.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-10 18:46:44 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 2698d7dd1d meson: Fix i/tvOS compilation with GLib as a subproject
Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-10 18:45:28 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 208aec031c web-service: Close connections of removed dynamic interfaces
To avoid them sticking around until we run out of file-descriptors.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-08 13:15:10 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 03e70d26b7 socket: Transition GSource callbacks to Source.REMOVE
Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-08 13:14:20 +02:00
Ole André Vadla Ravnås b22507ed32 meson: Disable Fruity and friends on FreeBSD
As we currently rely on a libusb API that only exists in our libusb.
2024-10-05 19:53:26 +00:00
Ole André Vadla Ravnås 1c4902e72d fruity: Use USB product string as transport name 2024-10-05 19:36:34 +00:00
Ole André Vadla RavnåsandHåvard Sørbø e5eaedaf85 fruity: Bubble up USB permission errors
Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-05 19:36:31 +00:00
Ole André Vadla Ravnås 944380225a subprojects: Bump outdated 2024-10-05 17:24:56 +02:00
Ole André Vadla Ravnås f84f2887d2 submodules: Bump releng 2024-10-05 17:24:55 +02:00
Ole André Vadla Ravnås e67d513d06 subprojects: Bump outdated 2024-10-05 16:14:44 +02:00
Ole André Vadla Ravnås 558628ad5a submodules: Bump releng 2024-10-05 16:14:43 +02:00
Ole André Vadla Ravnås 9c27b7b453 subprojects: Bump outdated 2024-10-05 16:12:48 +02:00
Ole André Vadla Ravnås 441636acd1 submodules: Bump releng 2024-10-05 16:12:47 +02:00
Ole André Vadla Ravnås 3238e2268a network-stack: Fix racy TCP data loss upon peer closure
Where the closure resulted in us letting go of the PCB, and the recv()
logic would return early because the PCB was gone. At that point there
might still be data left in the RX buffer, but the application wouldn't
see it.
2024-10-03 10:45:36 +02:00
Ole André Vadla Ravnås 66099c705f network-stack: Handle abrupt disposal of TcpConnection
Where we would free the PCB TCB but fail to notify any live TcpIOSource
instances and blocked TcpInputStream.read() calls.
2024-09-20 19:06:33 +02:00
Ole André Vadla Ravnås ca8519cec7 network-stack: Fix race in TcpInputStream.read()
Where the notify::pending-io signal fires after the call to
is_readable() but before our signal handler is connected.
2024-09-20 19:01:04 +02:00
Ole André Vadla Ravnås 416d2ea388 subprojects: Prepare for release 2024-09-19 00:00:49 +02:00
Ole André Vadla Ravnås 02e83a6d4a subprojects: Bump outdated 2024-09-18 23:57:30 +02:00
Ole André Vadla Ravnås 539f359a1f fruity: Handle USB TunnelConnection dropping
Which happens on e.g. an iOS userspace reboot.
2024-09-18 23:49:56 +02:00
Ole André Vadla Ravnås 24dc7f4a3d fruity: Fix unreliable modeswitch activation
Where its Promise could be resolved more than once.
2024-09-18 23:14:35 +02:00
Ole André Vadla Ravnås f48ced3a4a subprojects: Prepare for release 2024-09-18 14:33:15 +02:00
Ole André Vadla Ravnås 54829052bd subprojects: Bump outdated 2024-09-18 14:31:38 +02:00
Ole André Vadla Ravnås 73abf705b1 submodules: Bump releng 2024-09-18 14:31:37 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 7e21f5cb1d fruity: Advertise our RemoteXPC protocol support
Like macOS does, but with most of the properties omitted.

We do this to more closely mimic macOS' behavior, and to avoid an error
ending up in the syslog:

    Invalid or missing remote device connection version flags

Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-18 14:30:21 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 24a1f79b02 fruity: Handle iDevice not paired with anyone
Where the pairVerify step fails early.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-18 14:25:55 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 2d990888d9 fruity: Fix teardown when using our NCM driver
Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-17 18:34:21 +02:00
Ole André Vadla Ravnås 0fd255d3a4 fruity: Fix error marshaling in find_tunnel() for non-macOS 2024-09-17 17:15:35 +02:00
Ole André Vadla Ravnås fc500a19d9 fruity: Fix a stylistic inconsistency 2024-09-17 17:12:12 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 7280bbdbf7 fruity: Reuse NCM peer when tunnel setup fails
Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-17 13:25:25 +02:00
Ole André Vadla Ravnås 9539981511 subprojects: Prepare for release 2024-09-06 22:59:50 +02:00
Ole André Vadla Ravnås 3005ab2aa5 subprojects: Bump outdated 2024-09-06 22:58:46 +02:00
Ole André Vadla Ravnås 140c5cf2cd subprojects: Prepare for release 2024-09-06 21:57:05 +02:00
Ole André Vadla Ravnås 6bb27c17e9 subprojects: Bump outdated 2024-09-06 21:54:47 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 0f2d9c8b40 network-stack: Fix deadlock in perform_on_lwip_thread()
Where in the case of already being on the lwIP thread, we would enqueue
the request and then perform whichever is the oldest pending request. So
when there was already one or more requests pending, we would perform
that request instead. Then next we would join() our request, assuming it
had completed, and end up deadlocking the lwIP thread.

Kudos to @mrmacete for reporting and helping track this one down.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-06 15:16:48 +02:00
Ole André Vadla Ravnås 5606120f6a subprojects: Bump outdated 2024-08-30 23:00:20 +02:00
ajwerner 2376f425a3 linux: Handle process gone when detaching (#543)
This is an attempt to handle the situation where the process has gone
away and we're shutting down. I've observed the system looping
attempting to move the state out of ATTACHED. It's possible that the
state machine here needs to be made more complex (ALREADY_ATTACHED is
misleading).

Informs #478.
2024-08-30 22:37:41 +02:00
Ole André Vadla Ravnås 1f9e24e1ea windows: Revive the system session 2024-08-26 12:26:25 +02:00
Ole André Vadla Ravnås 694118cccc subprojects: Bump outdated 2024-08-26 01:51:50 +02:00
Ole André Vadla Ravnås 9d51496124 submodules: Bump releng 2024-08-26 01:51:49 +02:00
Ole André Vadla Ravnås 27849af528 subprojects: Bump outdated 2024-08-25 23:54:37 +02:00
Ole André Vadla Ravnås 9df97f9e6b windows: Add support for arm64 2024-08-25 23:52:42 +02:00
Ole André Vadla Ravnås 79126f0065 subprojects: Bump outdated 2024-08-25 13:41:41 +02:00
Ole André Vadla Ravnås 4b0d1eab04 meson: Add frida-netif to the public frida-core
It's needed by ControlService.
2024-08-25 13:40:51 +02:00
Ole André Vadla Ravnås 31188db39a subprojects: Prepare for release 2024-08-22 15:40:45 +02:00
Ole André Vadla Ravnås de09ec42d5 subprojects: Bump outdated 2024-08-22 15:39:00 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 34c1548ced tunnel-connection: Ensure JSON request ends up in its own UDP packet
When opening the tunnel, it seems problematic if a datagram and stream
data end up in the same UDP packet. We make our dummy-datagram larger to
avoid this.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-08-22 15:35:07 +02:00
Ole André Vadla RavnåsandHåvard Sørbø b753294acb tunnel-connection: Wire up missing stream close logic
Co-authored-by: Håvard Sørbø <[email protected]>
2024-08-22 15:35:00 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 498c9be83e tunnel-connection: Consistently avoid writes after connection is gone
Which would result in a crash.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-08-22 15:32:30 +02:00
Ole André Vadla RavnåsandHåvard Sørbø bbcbe91b3e network-stack: Handle perform_on_lwip_thread() from the lwIP thread
Instead of deadlocking.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-08-22 15:29:11 +02:00
Ole André Vadla Ravnås ce80773d21 subprojects: Prepare for release 2024-08-20 21:50:41 +02:00
Ole André Vadla Ravnås e06da4d410 subprojects: Bump outdated 2024-08-20 21:48:20 +02:00
Francesco Tamagni 120dc491c4 tunnel-interface-observer: Fix start() crash on i/tvOS
When SCDynamicStoreCopyKeyList() fails.
2024-08-20 21:12:49 +02:00
Ole André Vadla Ravnås 2ebec1addf subprojects: Prepare for release 2024-08-02 14:05:13 +02:00
Håvard Sørbø 6a1e373ba2 fruity: Make find_usbmux_device() non-throwing 2024-08-02 14:03:03 +02:00
Ole André Vadla Ravnås 100b7a63d7 fruity: Guard against lockdown open<->close loop 2024-08-02 14:03:03 +02:00
Håvard Sørbø b3f2d1e7cc fruity: Fix invalidation of closed lockdown client 2024-08-02 14:03:03 +02:00
Håvard Sørbø 313cdc89f8 lockdown-client: Bubble up CONNECTION_CLOSED error 2024-08-02 14:03:03 +02:00
Ole André Vadla Ravnås 3c8221dd55 subprojects: Bump outdated 2024-07-29 11:00:36 +02:00
Ole André Vadla Ravnås dca8509960 submodules: Bump releng 2024-07-29 11:00:36 +02:00
Ole André Vadla Ravnås 78ff6e5b08 subprojects: Prepare for release 2024-07-23 10:14:56 +02:00
Ole André Vadla Ravnås 6537809897 subprojects: Bump outdated 2024-07-23 10:11:56 +02:00
Ole André Vadla Ravnås ead2ff6701 submodules: Bump releng 2024-07-23 10:11:56 +02:00
xiofee d55232fe52 fruity: Fix crash when enumerating network interfaces on Windows (#538)
Some don't have a unicast address, and need to be ignored.
2024-07-23 10:11:26 +02:00
Ole André Vadla Ravnås dab3b91f9e subprojects: Prepare for release 2024-07-22 11:49:03 +02:00
Ole André Vadla Ravnås 71f7b2f16a subprojects: Bump outdated 2024-07-22 11:37:45 +02:00
Ole André Vadla Ravnås 4cf806641f submodules: Bump releng 2024-07-22 11:37:44 +02:00
Ole André Vadla Ravnås e34a533a35 fruity: Handle devices without tunnel support on non-macOS
In the portable CoreDevice backend.
2024-07-22 11:28:23 +02:00
Ole André Vadla Ravnås 6b56c88295 fruity: Use UsbmuxDevice from USB transport if present
So we can reach the loopback interface, and for better performance.
2024-07-19 23:10:15 +02:00
Ole André Vadla Ravnås d810111f1e fruity: Expose name from USB transport if present
It has a more descriptive name in case of UsbmuxTransport.
2024-07-19 23:09:42 +02:00
Ole André Vadla Ravnås 3d17ad39da subprojects: Prepare for release 2024-07-17 22:43:10 +02:00
Ole André Vadla Ravnås 429607e7e3 xpc-client: Wire up cancellable in request()
As we can't cancel the request itself, we have to cancel the connection.
2024-07-17 22:34:24 +02:00
Ole André Vadla Ravnås 6ef660718a subprojects: Bump outdated 2024-07-17 22:10:01 +02:00
Ole André Vadla Ravnås cf61fda141 subprojects: Prepare for release 2024-07-16 15:24:54 +02:00
Ole André Vadla Ravnås b272dda27d subprojects: Bump outdated 2024-07-16 15:20:35 +02:00
Ole André Vadla Ravnås 300d176e85 ci: Re-enable tests on macOS 2024-07-16 15:14:43 +02:00
Ole André Vadla Ravnås e7f045bbe9 darwin: Await ObjC init on macOS Sequoia and iOS 18
By making use of notifyObjCInit() if available.
2024-07-16 11:45:16 +02:00
Ole André Vadla Ravnås 0b6abfeb7c darwin: Handle dyld restart on macOS Sequoia and iOS 18 2024-07-16 11:12:02 +02:00
Ole André Vadla Ravnås c17c6e31bc tests: Avoid relying on executable name on Darwin 2024-07-16 11:06:55 +02:00
Ole André Vadla Ravnås 0825aab1d0 fruity: Improve CoreDevice pairing support
- Fix support for multiple pairing relationships.
- Keep the in-memory peer store up-to-date, so new pairing relationships
  don't require a process restart to be able to match them up with
  pairing services on the network.
2024-07-15 14:41:03 +02:00
Ole André Vadla Ravnås be65296610 ncm: Fix a stylistic inconsistency 2024-07-15 13:24:16 +02:00
Ole André Vadla Ravnås 0a6002a3ce ncm: Avoid using a broken kernel NCM driver
Where only one of the two network interfaces exist, i.e. the tethering
interface.
2024-07-15 13:03:49 +02:00
Ole André Vadla Ravnås a3deb22999 ncm: Detach all drivers before changing configuration
We would previously only try to detach for the data interface, which
makes no sense if that interface is on a different configuration.
2024-07-15 12:54:14 +02:00
Ole André Vadla Ravnås 5aeb800a7a subprojects: Prepare for release 2024-07-13 00:34:04 +02:00
Ole André Vadla Ravnås a01f5dcd3d subprojects: Bump outdated 2024-07-13 00:06:51 +02:00
Ole André Vadla Ravnås 23b15b5f4b ncm: Switch USB device configuration if needed 2024-07-12 15:31:43 +02:00
Ole André Vadla Ravnås f1fdd980aa fruity: Add support for networked devices on Windows
By making use of DnsServiceBrowse() if the OS supports it -- which means
Windows 10 and newer.
2024-07-12 15:29:15 +02:00
Ole André Vadla Ravnås 05a68332f6 network-stack: Fix TcpConnection use-after-free
When lwIP notifies us about the PCB being closed or an error, we must
clear its user data so any future callbacks don't end up using the
TcpConnection after it's gone.
2024-07-12 00:06:17 +02:00
Ole André Vadla Ravnås 13521724f7 fruity: Remove commented-out variable 2024-07-11 23:57:55 +02:00
Ole André Vadla Ravnås 6c700a511e fruity: Split out DnsPacketReader 2024-07-11 23:14:01 +02:00
Ole André Vadla Ravnås 02ccafe516 fruity: Move LinuxPairingBrowser to ResolveService
Which is simpler and avoids some roundtrips to systemd-resolved.
2024-07-11 23:09:08 +02:00
Ole André Vadla Ravnås fb672d7a0b ci: Move the macOS x86_64 job to macos-latest
As the macos-11 runner is gone.

Also skip running tests on macOS entirely for now, as a stopgap until
__CFInitialize() has been dealt with.
2024-07-11 15:13:14 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 81fbfe2ab5 fruity: Add support for networked devices on Linux
By making use of systemd-resolved for mDNS-SD lookups.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås 3aef106ec2 fruity: Fix the LWIP.NetworkInterface bindings
Where we would end up passing in a copy of the struct and have e.g.
neighbor discovery timers make use of dangling pointers.
2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås 370f1836a7 dtx: Fix teardown of DTXConnection vs. DTXChannel
So channels never make use of the connection once it's gone.
2024-07-11 15:09:12 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 70bb82bb5d fruity: Remove forgotten .pcap debug output
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås dc43be94c5 buffer: Add BufferReader 2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås 7c7367b010 buffer: Add content validation to read_fixed_string()
To support parsing untrusted data.
2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås a9073c07eb buffer: Add content validation to read_string()
To support parsing untrusted data.
2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås fd5a274680 subprojects: Prepare for release 2024-07-08 14:27:06 +02:00
Ole André Vadla Ravnås d3f949a51c subprojects: Bump outdated 2024-07-08 14:25:06 +02:00
Ole André Vadla Ravnås 6d3ea5f589 fruity: Clean up OS-specific bits 2024-07-08 14:24:29 +02:00
Ole André Vadla Ravnås 3f6b41dc8c fruity: Handle libusb failing to initialize
Which may happen due to insufficient privileges, stripped down
environments such as containers, etc.
2024-07-08 10:26:46 +02:00
Ole André Vadla Ravnås 2c23afacfd subprojects: Prepare for release 2024-07-06 00:07:28 +02:00
Ole André Vadla Ravnås 51bf048d5b subprojects: Bump outdated 2024-07-06 00:06:32 +02:00
Ole André Vadla RavnåsandHåvard Sørbø be6a2b305c socket: Fix Host header logic in negotiate_connection()
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-06 00:04:35 +02:00
Ole André Vadla Ravnås 5625a08fd9 device: Fix property getters for id and name
When Device is created with a custom value for either.

Due to typos the getters ended up recursing until stack overflow.
2024-07-05 23:35:47 +02:00
Ole André Vadla Ravnås 684739a1e6 subprojects: Prepare for release 2024-07-05 15:32:45 +02:00
Ole André Vadla RavnåsandHåvard Sørbø e0c36e6826 fruity: Retry RSD port lookup on failure
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-05 15:31:42 +02:00
Ole André Vadla RavnåsandHåvard Sørbø eeb0c7a50a fruity: Fix gadget upload when no usbmux connection is available
By listening on all interfaces, not just loopback, so we can connect to
it across the tunnel.

Also switch to IPv6 while at it.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-05 15:22:40 +02:00
Ole André Vadla RavnåsandHåvard Sørbø f2dc84324a fruity: Skip fetching dyld symbols if libSystem is initialized
We only need them for early instrumentation.

This means we can attach to a running app not spawned by Frida, even on
latest iOS versions where dyld restarts.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-05 14:22:26 +02:00
Ole André Vadla RavnåsandHåvard Sørbø b9d07f0bfb fruity: Wire up MacOSCoreDeviceTransport event handling
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-05 13:55:34 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 8b54716bfc fruity: Ensure provider name doesn't mutate
In case of a transport departing and taking the string storage with it.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-05 13:51:59 +02:00
Ole André Vadla Ravnås 68bfde7ae0 xpc-object-reader: Add get_uuid_value() 2024-07-05 13:50:57 +02:00
Ole André Vadla RavnåsandHåvard Sørbø bcdcc090b6 device: Refactor construction and property wiring
We can compute some of the properties from the provider.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-05 13:50:19 +02:00
Ole André Vadla Ravnås 2a1a80abd9 fruity: Tweak ordering of system parameters 2024-07-05 10:44:44 +02:00
ea6307d60b fruity: Add os.build and hardware to system parameters (#534)
Co-authored-by: Ole André Vadla Ravnås <[email protected]>
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-05 10:10:17 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 2bf45ececd fruity: Await ObjC runtime initialization on iOS >= 18
By making use of notifyObjCInit() if available.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-04 15:20:51 +02:00
Ole André Vadla RavnåsandHåvard Sørbø d6b502eb3e fruity: Add support for dyld restart on iOS >= 18
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-04 14:56:51 +02:00
Ole André Vadla Ravnås 0de45afe2f meson: Auto-disable external device backends for 32-bit host machines 2024-07-04 13:49:25 +02:00
Ole André Vadla Ravnås 7262e55468 macos: Replace logging with TODOs in the CoreDevice transport 2024-07-04 13:36:01 +02:00
Ole André Vadla RavnåsandHåvard Sørbø def974818f socket: Support IPv6 addresses in negotiate_connection()
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-04 12:51:58 +02:00
Ole André Vadla Ravnås d5312d288f pipe: Fix tvOS build regression
We need to make sure we include the Mach headers before CoreFoundation
does, so our version availability overrides are used.
2024-07-04 11:16:06 +02:00
Ole André Vadla Ravnås 7e9fb1e1c6 subprojects: Bump outdated 2024-07-03 23:20:05 +02:00
Ole André Vadla RavnåsandHåvard Sørbø e415a2ec83 fruity: Fix the macOS CoreDevice connection type logic
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-03 14:20:35 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 248127623f tests: Add manual XPC application launching test
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-03 13:45:09 +02:00
Ole André Vadla RavnåsandHåvard Sørbø f246b4e17d xpc-service: Support type-annotating request parameters
Represented using a `(type, value)` tuple.

This means uint64 and UUID values can be passed in.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-03 13:42:48 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 7c4633358b fruity: Improve open_channel() to support tcp:service-name
Useful for e.g. `com.apple.coredevice.openstdiosocket`.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-03 13:35:08 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 85d063ab9b fruity: Revive HostChannelProvider implementation
Removed by accident in 08e5d37348.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-03 13:33:25 +02:00
Ole André Vadla RavnåsandHåvard Sørbø a6650efecb xpc: Make add_uuid_value() expect a raw UUID
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-03 13:31:54 +02:00
Ole André Vadla RavnåsandHåvard Sørbø d382734bca value: Remove unused UUID functionality
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-03 13:30:29 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 08e5d37348 fruity: Rework to support userspace NCM
To support systems without a compatible NCM driver, such as contemporary
Linux kernels, Windows, etc.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-03 11:20:16 +02:00
Ole André Vadla Ravnås 6317446c37 xpc-client: Add post() 2024-07-03 11:14:41 +02:00
Ole André Vadla Ravnås 7048e851b0 xpc-client: Handle closure in open state 2024-07-03 11:14:41 +02:00
Ole André Vadla Ravnås 7d22da8d3d meson: Summarize backends and more of the features 2024-07-03 11:14:41 +02:00
Ole André Vadla Ravnås 1f164564ef meson: Auto-disable external device backends on non-desktop 2024-07-03 11:14:41 +02:00
Ole André Vadla Ravnås 47a2e6728b submodules: Bump releng 2024-07-03 11:14:36 +02:00
Ole André Vadla Ravnås b19333420c web-service: Listen on dynamic interfaces last
So that specifying e.g. 0.0.0.0 takes precedence and won't cause start()
to fail.
2024-07-03 10:47:09 +02:00
Ole André Vadla Ravnås 29ec9f0c98 tunnel-interface-observer: Fix confusing variable name
The tunnel isn't only for development tools.
2024-07-03 10:43:02 +02:00
Ole André Vadla Ravnås cbcb7f37bf gadget: Integrate TunnelInterfaceObserver
So we listen on Apple's CoreDevice tunnel network interfaces on iOS and
tvOS.
2024-07-02 22:50:09 +02:00
Ole André Vadla Ravnås f53230bd7a control-service: Integrate TunnelInterfaceObserver
So we listen on Apple's CoreDevice tunnel network interfaces on iOS and
tvOS.
2024-07-02 22:50:09 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 39486a5331 netif: Add TunnelInterfaceObserver for iOS and tvOS
For observing Apple's CoreDevice tunnel network interfaces. Intended for
ControlService (frida-server) and frida-gadget to be able to listen on
such interfaces as they arrive and depart.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-02 22:50:05 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 67f6895e13 base: Add an iterable CFArray wrapper
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-02 22:26:15 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 1b80ce0779 vapi: Improve the CoreFoundation bindings
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-02 22:26:15 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 9bd3c3974f web-service: Support dynamic network interfaces
By providing a DynamicInterfaceObserver with the desired behavior.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-02 22:26:12 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 055fe8744a socket: Remove the partial NECP integration
It's not a good fit for keeping track of network interfaces.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-02 14:00:35 +02:00
Ole André Vadla RavnåsandHåvard Sørbø a0f7df8d0e socket: Sketch a partial NECP integration
In pursuit of notifications when network interfaces arrive and depart.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-06-28 14:14:01 +02:00
Ole André Vadla Ravnås 4b5fe35b00 devkit: Also install frida-core.gir 2024-06-07 09:54:32 +02:00
Håvard Sørbø 9330f02ca5 xpc-service: Fix handling of request() with arrays (#532)
Where we forgot to call begin/end to actually generate an array, and
would end up generating an invalid XPC object.
2024-06-06 22:46:35 +02:00
Ole André Vadla Ravnås 5d23227efc subprojects: Prepare for release 2024-06-04 14:14:40 +02:00
Ole André Vadla Ravnås 300a55b75c subprojects: Bump outdated 2024-06-04 14:12:37 +02:00
Ole André Vadla Ravnås f2e071ed78 subprojects: Prepare for release 2024-06-04 13:41:11 +02:00
Ole André Vadla Ravnås bc7f73b492 subprojects: Bump outdated 2024-06-04 13:38:40 +02:00
f91a3c92fe darwin: Avoid thread_set_state() during injection (#530)
So we don't get killed by the system on e.g. macOS >= 14.5.

We can create the thread in running state. There is no need to keep it
suspended until we have created the dispatch source.

Co-authored-by: Håvard Sørbø <[email protected]>
Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-06-04 13:36:31 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 6eacc889cd fruity: Perform RSDCheckin on services that need it
In this way we retain backwards-compatibility for open_channel() of
lockdown services when a CoreDevice tunnel is available.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-06-04 12:27:57 +02:00
Ole André Vadla RavnåsandHåvard Sørbø d21ba21aea fruity: Stop caching the LockdownClient
To avoid issues with multiple consumers.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-06-04 11:34:55 +02:00
Ole André Vadla Ravnås cfcdc26d29 subprojects: Prepare for release 2024-05-31 22:52:22 +02:00
Ole André Vadla Ravnås 69555bbbb6 subprojects: Bump outdated 2024-05-31 22:50:47 +02:00
Ole André Vadla Ravnås d2d014c081 subprojects: Prepare for release 2024-05-31 15:42:49 +02:00
Ole André Vadla Ravnås 8f9c30953b subprojects: Bump outdated 2024-05-31 15:41:33 +02:00
Ole André Vadla Ravnås 2396ad5717 fruity: Remove temporary debug helpers
Useful during bring-up, but not so much anymore.
2024-05-31 14:14:27 +02:00
Ole André Vadla Ravnås ded45c9c93 fruity: Remove the xpc-test program
It has served its purpose. We now have tests that can be run instead.
2024-05-31 14:10:28 +02:00
Ole André Vadla Ravnås 8d375b5e46 fruity: Avoid leaking Posix types into the public API 2024-05-31 14:08:52 +02:00
Ole André Vadla Ravnås 1722429383 subprojects: Bump outdated 2024-05-31 06:45:37 +02:00
Ole André Vadla Ravnås ffd23574a9 submodules: Bump releng 2024-05-31 06:45:36 +02:00
Ole André Vadla Ravnås 5a8bd3fbaf meson: Add new Fruity private requirements to .pc 2024-05-31 00:06:55 +02:00
Ole André Vadla Ravnås 56605717ad meson: Fix build when glib-networking is a subproject 2024-05-30 23:15:15 +02:00
Ole André Vadla Ravnås d8a7c7d3fb subprojects: Bump outdated 2024-05-30 21:58:55 +02:00
Ole André Vadla Ravnås 39725e427b ci: Fix apt-get steps in the native and cross jobs
Need to update the database before installing.
2024-05-30 21:58:13 +02:00
Ole André Vadla Ravnås 7fe3a00543 subprojects: Bump outdated 2024-05-30 21:50:35 +02:00
Ole André Vadla Ravnås 41c31ba0a0 subprojects: Bump outdated 2024-05-30 21:42:28 +02:00
Ole André Vadla Ravnås c8e1ebdb7c ci: Allow Corellium test steps to fail for now
Until we figure out the stability issue.
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 3a678a3553 meson: Fix build when connectivity deps are subprojects
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 2048115cb3 meson: Change connectivity option default to enabled
So fallbacks trigger, and we build with the same features irrespective
of whether we build with a Frida SDK present.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 82a68e55cc fruity: Add RemoteXPC support
With two platform integrations:

- macOS: where we use Apple's tunnel, by talking to remotepairingd and
  creating an assertion to ensure the tunnel is up and stays up for as
  long as we need it. The challenging part here was figuring out the
  device-side RemoteServiceDiscovery (RSD) port inside the tunnel, as
  it appears no API exposes it. Our solution is to ask the kernel for
  a list of TCP sockets, and picking out the ones where the foreign
  address is the device-side IPv6 address inside the tunnel, **and**
  where the process that created the socket is remoted. This seems to
  consistenly result in us finding a single socket, connected to the RSD
  port, but we try all of them in case this behavior ends up changing.
- Linux: where we open our own tunnel, assuming the iDevice has been
  mode-switched (e.g. by usbmuxd), and the Linux CDC NCM driver has been
  patched something along the lines of:
  https://lore.kernel.org/all/[email protected]/T/

We don't yet have a platform integration for Windows, as Apple's
software doesn't currently set up a tunnel. The official driver also
appears to keep the USB device busy, meaning we can't easily trigger
a mode-switch. This is an area that needs more research.

Another area that needs future improvement is that we only support
cabled connectivity on macOS. This should be easy to improve on once we
have updated frida-server and frida-gadget so they listen on tunnel
interfaces whenever they appear.

Kudos to @doronz88 for figuring out most of the protocol bits that we
needed.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø e0d6c29c41 meson: Add wrap for lwip
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 1f820ae2ac meson: Add wrap for ngtcp2
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø c0bc5f5bd9 base: Add helpers for handling JSON and GLib.Variant
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 7ab0cf75ea fruity: Fix spawn() on jailed iOS 17
The jailed equivalent of 827eee33cc.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 2175cc756a dtx: Use more appropriate GValue setter for NSObject
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 90d60683dd dtx: Make DTXArgumentList elements visible to consumers
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø cf09ba46e4 dtx: Allow notification payload to be of any type
The value is not always an NSDictionary, e.g. in case of a DTTapMessage.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø ed9fcb10c1 dtx: Fix channel code interpretation for inbound invokes
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 333ca2f852 dtx: Bump max message size to 128 MB
Screenshots can be quite large, and we might in theory be asked to fetch
large files.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø c9e541cc0e keyed-archive: Add support for decoding DTTapMessage
And its subclasses.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 3e86270d77 keyed-archive: Add support for encoding NSArray
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 8a21929415 keyed-archive: Add NSArray.add_object()
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 4865ea07eb keyed-archive: Add support for decoding NSData
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 28f7895704 keyed-archive: Improve NSNumber support
So boolean/float/double values are treated distinctly from int64.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 859d6cd7de plist: Fix support for float and double in to_binary()
Co-authored-by: Håvard Sørbø <[email protected]>
2024-05-30 21:28:33 +02:00
Ole André Vadla Ravnås b71c861b1d subprojects: Bump outdated 2024-05-30 20:51:53 +02:00
Ole André Vadla Ravnås b486936b33 submodules: Bump releng 2024-05-30 20:51:53 +02:00
Ole André Vadla Ravnås 5b587f587f base: Add Numeric.int64_{hash,equal}() 2024-05-29 23:18:13 +02:00
Ole André Vadla Ravnås 39e2c7bf81 subprojects: Prepare for release 2024-05-21 12:50:31 +02:00
Ole André Vadla Ravnås 2b82c21df1 subprojects: Bump outdated 2024-05-21 12:48:55 +02:00
Ole André Vadla Ravnås e45989dbdf subprojects: Prepare for release 2024-05-20 22:54:26 +02:00
Ole André Vadla Ravnås 204b16a4b7 compat: Escape spaces in depfile paths
Quoting isn't supported, so we should be escaping the spaces instead.
2024-05-20 22:50:29 +02:00
Ole André Vadla Ravnås d9f33a918e meson: Find DbgHelp and SymSrv using Gum's variables 2024-05-20 22:41:48 +02:00
Ole André Vadla Ravnås 082b100ab9 subprojects: Bump outdated 2024-05-20 22:40:31 +02:00
Ole André Vadla Ravnås 20cdf64312 meson: Fix vapidir exported in our .pc 2024-05-20 22:39:15 +02:00
Ole André Vadla Ravnås 0bb558e2a1 meson: Refactor the (un)installed variables logic 2024-05-20 22:37:59 +02:00
311 changed files with 292709 additions and 7874 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
github: frida
+268 -16
View File
@@ -16,13 +16,13 @@ jobs:
strategy:
matrix:
include:
- { id: windows-x86_64, runner: '"windows-latest"' }
- { id: windows-x86, runner: '"windows-latest"' }
- { id: macos-x86_64, runner: '"macos-11"' }
- { id: macos-arm64, runner: '"macos-latest"' }
- { id: linux-x86_64, runner: '"ubuntu-latest"' }
- { id: linux-x86, runner: '"ubuntu-latest"' }
- { id: freebsd-arm64, runner: '["self-hosted", "freebsd", "arm64"]' }
- { id: windows-arm64, runner: '"windows-11-arm"', sys: CLANGARM64, pkg: 'mingw-w64-clang-aarch64-clang' }
- { id: windows-x86_64, runner: '"windows-latest"', sys: MINGW64, pkg: 'mingw-w64-x86_64-gcc' }
- { id: windows-x86, runner: '"windows-latest"', sys: MINGW32, pkg: 'mingw-w64-i686-gcc' }
- { id: macos-x86_64, runner: '"macos-latest"' }
- { id: macos-arm64, runner: '"macos-latest"' }
- { id: linux-x86_64, runner: '"ubuntu-latest"' }
- { id: linux-x86, runner: '"ubuntu-latest"' }
fail-fast: false
runs-on: ${{ fromJSON(matrix.runner) }}
steps:
@@ -30,6 +30,18 @@ jobs:
uses: actions/checkout@v4
with:
submodules: recursive
- name: Install MinGW toolchain for cgo support
if: ${{ startsWith(matrix.id, 'windows-') }}
id: msys2
uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.sys }}
install: ${{ matrix.pkg }}
- name: Install Go toolchain
uses: actions/setup-go@v5
with:
go-version-file: 'src/compiler/go.mod'
cache-dependency-path: 'src/compiler/go.mod'
- name: Set up Apple certificates
if: ${{ startsWith(matrix.id, 'macos-') }}
uses: ./.github/actions/setup-apple-certificates
@@ -42,22 +54,35 @@ jobs:
run: sudo security authorizationdb write system.privilege.taskport allow
- name: Install gcc-multilib
if: matrix.id == 'linux-x86'
run: sudo apt-get install gcc-multilib lib32stdc++-11-dev
run: |
sudo apt-get update
sudo apt-get install gcc-multilib lib32stdc++-13-dev
- name: Build
if: ${{ startsWith(matrix.id, 'windows-') }}
run: |
.\configure ${{ env.FRIDA_CORE_OPTIONS }}
.\configure `
--host=${{ matrix.id }} `
--enable-compiler-backend `
${{ env.FRIDA_CORE_OPTIONS }}
.\make
env:
MSYS2_LOCATION: ${{ steps.msys2.outputs.msys2-location }}
- name: Build
if: ${{ !startsWith(matrix.id, 'windows-') && matrix.id != 'linux-x86' }}
run: |
./configure ${{ env.FRIDA_CORE_OPTIONS }}
./configure \
--enable-compiler-backend \
${{ env.FRIDA_CORE_OPTIONS }}
make
- name: Build
if: matrix.id == 'linux-x86'
run: |
CC="gcc -m32" CXX="g++ -m32" STRIP="strip" \
./configure --build=linux-x86 --host=linux-x86 ${{ env.FRIDA_CORE_OPTIONS }}
./configure \
--build=linux-x86 \
--host=linux-x86 \
--enable-compiler-backend \
${{ env.FRIDA_CORE_OPTIONS }}
make
- name: Upload devkit
if: ${{ !startsWith(matrix.id, 'linux-') }}
@@ -66,7 +91,7 @@ jobs:
name: core-devkit-${{ matrix.id }}
path: build/src/devkit/
- name: Test
if: matrix.id != 'macos-arm64'
if: ${{ matrix.id != 'windows-arm64' && !startsWith(matrix.id, 'macos-') }}
run: make test
cross:
@@ -87,10 +112,20 @@ jobs:
with:
submodules: recursive
- name: Install toolchain
run: sudo apt-get install ${{ matrix.pkg }}
run: |
sudo apt-get update
sudo apt-get install ${{ matrix.pkg }}
- name: Install Go toolchain
uses: actions/setup-go@v5
with:
go-version-file: 'src/compiler/go.mod'
cache-dependency-path: 'src/compiler/go.mod'
- name: Build
run: |
./configure ${{ matrix.opts }} ${{ env.FRIDA_CORE_OPTIONS }}
./configure \
${{ matrix.opts }} \
${{ !contains(matrix.id, 'mips') && '--enable-compiler-backend' || '' }} \
${{ env.FRIDA_CORE_OPTIONS }}
make
- name: Upload devkit
if: ${{ !startsWith(matrix.id, 'linux-') }}
@@ -111,9 +146,17 @@ jobs:
uses: actions/checkout@v4
with:
submodules: recursive
- name: Install Go toolchain
uses: actions/setup-go@v5
with:
go-version-file: 'src/compiler/go.mod'
cache-dependency-path: 'src/compiler/go.mod'
- name: Build
run: |
./configure --host=$XTOOLS_HOST ${{ env.FRIDA_CORE_OPTIONS }}
./configure \
--host=$XTOOLS_HOST \
${{ !startsWith(matrix.arch, 'mips') && '--enable-compiler-backend' || '' }} \
${{ env.FRIDA_CORE_OPTIONS }}
make
- name: Upload devkit
uses: actions/upload-artifact@v4
@@ -124,6 +167,131 @@ jobs:
if: matrix.arch == 'x86' || matrix.arch == 'x86_64'
run: make test
emulator:
strategy:
matrix:
arch: [armbe8, arm64be]
fail-fast: false
runs-on: ubuntu-latest
container: ghcr.io/frida/x-tools-linux-${{ matrix.arch }}:latest
steps:
- name: Check out repo
uses: actions/checkout@v4
with:
submodules: recursive
- name: Build
run: |
./configure --host=$XTOOLS_HOST --without-prebuilds=sdk:host --enable-tests
make
- name: Run custom container
uses: addnab/docker-run-action@v3
with:
image: docker:stable
options: -v ${{ github.workspace }}:/workspace:delegated
run: |
cat <<EOF > /workspace/initscript
#!/bin/sh
dmesg -n1
mount -t proc none /proc
mount -t sysfs none /sys
mount -t tmpfs none /tmp
mount -t devtmpfs none /dev
mount -t 9p -o rw,sync,dirsync,relatime,trans=virtio,msize=131072,version=9p2000.L host0 /workspace
ip link set lo up
ip addr add 192.168.76.20/24 dev eth0
ip link set eth0 up
ip route add default via 192.168.76.2 dev eth0
export LD_LIBRARY_PATH=/lib:/lib64:/libilp32
/sbin/entropy
cat /etc/motd
export PS1='\u@frida:\w\$ '
/root/frida-tests
status=\$?
echo "exit status: \$status"
if [ \$status -eq 0 ]; then
echo EXIT_OK
elif [ \$status -gt 128 ]; then
signal=\$((\$status - 128))
echo "EXIT_FAIL (terminated by signal \$signal)"
else
echo "EXIT_FAIL (exit code \$status)"
fi
EOF
cat <<EOF > /workspace/launch.sh
#!/bin/sh
LOGFILE=/workspace/qemu.log
: > "\$LOGFILE"
timeout 120 qemu-system-aarch64 \
-M virt \
-machine virtualization=true \
-machine type=virt \
-cpu cortex-a72 \
-smp 4 \
-kernel /root/Image.gz \
-initrd /root/initramfs.img \
-append 'earlyprintk=serial,ttyAMA0 console=ttyAMA0 coredump_filter=0x3f' \
-m 4096M \
-net nic,id=eth \
-net user,id=mynet,net=192.168.76.0/24 \
-virtfs local,path=/workspace/,mount_tag=host0,security_model=passthrough,id=host0 \
-nographic \
-no-reboot \
>> "\$LOGFILE" 2>&1 &
QEMU_PID=\$!
echo "QEMU started with PID \$QEMU_PID"
tail -n 0 -f "\$LOGFILE" | while read line; do
echo "\$line"
echo "\$line" | grep "EXIT_OK" >/dev/null 2>&1
if [ \$? -eq 0 ]; then
echo "Success signal received from guest. Killing QEMU..."
kill -9 "\$QEMU_PID"
cat -n "\$LOGFILE"
exit 0
fi
echo "\$line" | grep "EXIT_FAIL" >/dev/null 2>&1
if [ \$? -eq 0 ]; then
echo "Failure signal received from guest. Killing QEMU..."
kill -9 "\$QEMU_PID"
cat -n "\$LOGFILE"
exit 1
fi
if ! kill -0 "\$QEMU_PID" 2>/dev/null; then
echo "QEMU process has exited."
cat -n "\$LOGFILE"
exit 1
fi
done
EOF
cat <<EOF > /workspace/Dockerfile.ci
FROM ghcr.io/frida/x-tools-linux-be-target:latest
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && \
apt-get install -y \
cpio
RUN mkdir /tmp/initramfs
WORKDIR /tmp/initramfs
RUN cpio --extract < /root/initramfs.img
RUN mkdir /tmp/initramfs/workspace
COPY initscript /tmp/initramfs/init
RUN chmod +x /tmp/initramfs/init
COPY build/tests /tmp/initramfs/root/
RUN find . | cpio -o --format=newc -R root:root > /root/initramfs.img
COPY launch.sh /root/launch.sh
RUN chmod +x /root/launch.sh
ENTRYPOINT ["/root/launch.sh"]
EOF
docker build -t ci-image -f /workspace/Dockerfile.ci /workspace
docker run --rm -v /workspace:/workspace ci-image
mobile:
strategy:
matrix:
@@ -140,6 +308,11 @@ jobs:
uses: actions/checkout@v4
with:
submodules: recursive
- name: Install Go toolchain
uses: actions/setup-go@v5
with:
go-version-file: 'src/compiler/go.mod'
cache-dependency-path: 'src/compiler/go.mod'
- name: Set up Apple certificates
if: startsWith(matrix.id, 'ios-')
uses: ./.github/actions/setup-apple-certificates
@@ -147,9 +320,20 @@ jobs:
certificates-p12: ${{ secrets.APPLE_CERTIFICATES_P12 }}
certificates-password: ${{ secrets.APPLE_CERTIFICATES_PASSWORD }}
keychain-password: ${{ secrets.APPLE_KEYCHAIN_PASSWORD }}
- uses: nttld/setup-ndk@v1
if: startsWith(matrix.id, 'android-')
id: setup-ndk
with:
ndk-version: r25c
- name: Add NDK to env
if: startsWith(matrix.id, 'android-')
run: echo ANDROID_NDK_ROOT=${{ steps.setup-ndk.outputs.ndk-path }} >> $GITHUB_ENV
- name: Build
run: |
./configure --host=${{ matrix.id }} ${{ env.FRIDA_CORE_OPTIONS }}
./configure \
--host=${{ matrix.id }} \
--enable-compiler-backend \
${{ env.FRIDA_CORE_OPTIONS }}
make
- name: Upload devkit
uses: actions/upload-artifact@v4
@@ -177,6 +361,7 @@ jobs:
tar -C /tmp/pkg -czf /tmp/runner.tar.gz .
- name: Test on Corellium iOS device
if: matrix.id == 'ios-arm64'
continue-on-error: true
uses: frida/corellium-action@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
@@ -192,6 +377,7 @@ jobs:
./frida-tests
- name: Test on Corellium Android device
if: matrix.id == 'android-arm64'
continue-on-error: true
uses: frida/corellium-action@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
@@ -228,3 +414,69 @@ jobs:
cp -a tests/frida-tests tests/labrats lib/agent/frida-agent.so /tmp/pkg/
tar -C /tmp/pkg -cf /tmp/runner.tar .
/opt/sabrelite/run.sh /tmp/runner.tar /opt/frida/frida-tests
# This job is used to check that the Linux helpers are built correctly for all
# supported architectures. We do this because the binary artifacts are checked
# in, and we want to ensure that they are up-to-date with respect to the source
# for all architectures.
check-linux-helpers:
strategy:
matrix:
arch: [x86, x86_64, arm, armbe8, arm64, arm64be, arm64beilp32, mips, mipsel, mips64, mips64el]
fail-fast: false
runs-on: ubuntu-latest
container: ghcr.io/frida/core-linux-helpers-${{ matrix.arch }}:latest
steps:
- name: Check out repo
uses: actions/checkout@v4
with:
submodules: recursive
- name: Build
run: |
./src/linux/helpers/rebuild.sh ${{ matrix.arch }}
- name: Check for unexpected changes
run: |
git config --global --add safe.directory "$(realpath .)"
status_output=$(git status --porcelain tests/labrats/{resident-agent,simple-agent}-linux-${{ matrix.arch }}.so tests/labrats/{forker,sleeper,spawner}-linux-${{ matrix.arch }})
if [ -n "$status_output" ]; then
echo "Unexpected changes detected:"
echo "$status_output"
echo "Diff:"
git diff
exit 1
else
echo "No unexpected changes detected."
fi
# This job is used to check that the Linux labrats are built correctly for all
# supported architectures. We do this because the binary artifacts are checked
# in, and we want to ensure that they are up-to-date with respect to the source
# for all architectures.
check-labrats:
strategy:
matrix:
arch: [x86, x86_64, arm, armbe8, arm64, arm64be, arm64beilp32, mips, mipsel, mips64, mips64el]
fail-fast: false
runs-on: ubuntu-latest
container: ghcr.io/frida/core-linux-helpers-${{ matrix.arch }}:latest
steps:
- name: Check out repo
uses: actions/checkout@v4
with:
submodules: recursive
- name: Build
run: |
./tests/labrats/rebuild.sh ${{ matrix.arch }}
- name: Check for unexpected changes
run: |
git config --global --add safe.directory "$(realpath .)"
status_output=$(git status --porcelain src/linux/helpers/{bootstrapper,loader}-${{ matrix.arch }}.bin)
if [ -n "$status_output" ]; then
echo "Unexpected changes detected:"
echo "$status_output"
echo "Diff:"
git diff
exit 1
else
echo "No unexpected changes detected."
fi
+7
View File
@@ -3,9 +3,16 @@
/src/barebone/helpers/memory-scanner/target/
/src/barebone/helpers/target/
/src/barebone/node_modules/
/src/barebone/script-runtime.js
/src/compiler/node_modules/
/src/darwin/agent/osanalytics/node_modules/
/src/darwin/agent/osanalytics/osanalytics.js
/src/darwin/agent/reportcrash/node_modules/
/src/darwin/agent/reportcrash/reportcrash.js
/src/droidy/helper/build/
/src/fruity/helpers/build/
/src/linux/agent/system-server/node_modules/
/src/linux/agent/system-server/system-server.js
/src/linux/helpers/build/
/src/linux/helpers/ext/
/subprojects/*
+58 -12
View File
@@ -4,6 +4,7 @@ import base64
from collections import OrderedDict
from dataclasses import dataclass, field
import itertools
import locale
import os
from pathlib import Path
import pickle
@@ -14,7 +15,7 @@ import subprocess
import sys
import tempfile
import traceback
from typing import Any, Literal, Mapping, Optional, Sequence
from typing import Any, Literal, Mapping, Optional, Sequence, Tuple
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -140,16 +141,19 @@ def setup(role: Role,
compat = set()
else:
summary = "enabled by user"
missing: list[MissingFeature] = []
if "native" in compat:
have_toolchain = True
other_label: Optional[str] = None
other_triplet: Optional[str] = None
extra_environ: dict[str, str] = {}
if host_os == "windows" and host_arch == "x86_64" and host_config == "mingw":
other_triplet = "i686-w64-mingw32"
have_toolchain = shutil.which(other_triplet + "-gcc") is not None
other_label = "x86"
have_toolchain, other_triplet = detect_mingw_toolchain_for("x86")
elif host_os == "linux" and host_arch == "x86_64" and host_config is None:
other_label = "x86"
other_triplet = "i686-linux-gnu"
have_toolchain = shutil.which(other_triplet + "-gcc") is not None
if not have_toolchain:
@@ -173,7 +177,7 @@ def setup(role: Role,
if not have_toolchain:
if not auto_detect:
raise ToolchainNotFoundError(f"unable to locate toolchain for {other_triplet}")
summary = "disabled due to missing toolchain for {other_triplet}"
missing.append(MissingFeature(other_label, other_triplet))
if host_os == "windows" and host_arch == "x86_64" and have_toolchain:
group = OutputGroup("x86", other_triplet, extra_environ)
@@ -269,6 +273,28 @@ def setup(role: Role,
]
if "emulated" in compat:
if host_os == "windows" and host_arch == "arm64":
for kind, emulated_arch in [("modern", "x86_64"), ("legacy", "x86")]:
if host_config == "mingw":
found, emulated_triplet = detect_mingw_toolchain_for(emulated_arch)
if not found:
if not auto_detect:
raise ToolchainNotFoundError(f"unable to locate toolchain for {emulated_triplet}")
missing.append(MissingFeature(emulated_arch, emulated_triplet))
continue
else:
emulated_triplet = None
outputs[OutputGroup(emulated_arch, emulated_triplet, extra_environ)] = [
Output(identifier=f"helper_emulated_{kind}",
name=HELPER_FILE_WINDOWS.name.replace(".exe", f"-{emulated_arch}.exe"),
file=HELPER_FILE_WINDOWS,
target=HELPER_TARGET),
Output(identifier=f"agent_emulated_{kind}",
name=AGENT_FILE_WINDOWS.name.replace(".dll", f"-{emulated_arch}.dll"),
file=AGENT_FILE_WINDOWS,
target=AGENT_TARGET),
]
if host_os == "android" and host_arch in {"x86_64", "x86"}:
outputs[OutputGroup("arm")] = [
Output(identifier="agent_emulated_legacy",
@@ -290,6 +316,8 @@ def setup(role: Role,
state = State(role, builddir, top_builddir, frida_version, host_os, host_config, allowed_prebuilds, outputs)
serialized_state = base64.b64encode(pickle.dumps(state)).decode('ascii')
if missing:
summary = ", ".join([f"{m.label} disabled due to missing toolchain for {m.triplet}" for m in missing])
variable_names, output_names = zip(*[(output.identifier, output.name) \
for output in itertools.chain.from_iterable(outputs.values())])
print("ok")
@@ -349,6 +377,12 @@ class Output:
target: str
@dataclass
class MissingFeature:
label: str
triplet: str
def compile(privdir: Path, state: State):
releng_location = query_releng_location(state.role)
subprojects = detect_relevant_subprojects(releng_location)
@@ -367,7 +401,7 @@ def compile(privdir: Path, state: State):
**kwargs,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"encoding": "utf-8",
"encoding": locale.getpreferredencoding(),
}
else:
silenced_kwargs = kwargs
@@ -401,6 +435,7 @@ def compile(privdir: Path, state: State):
environ={**build_env, **group.extra_environ},
allowed_prebuilds=state.allowed_prebuilds,
extra_meson_options=[
"-Dcompiler_backend=disabled",
"-Dhelper_modern=",
"-Dhelper_legacy=",
"-Dagent_modern=",
@@ -432,7 +467,7 @@ def compile(privdir: Path, state: State):
path = Path(raw_path)
if not path.is_absolute():
path = Path(os.path.relpath(workdir / path, top_builddir))
input_entries.append(quote(path.as_posix()))
input_entries.append(escape_depfile_path(path.as_posix()))
depfile_lines.append(f"{output_relpath}: {' '.join(input_entries)}")
(state.builddir / DEPFILE_FILENAME).write_text("\n".join(depfile_lines), encoding="utf-8")
@@ -465,6 +500,8 @@ def option_should_be_forwarded(k: "OptionKey",
if k.is_project():
if is_for_us:
if k.name == "compiler_backend":
return False
tokens = k.name.split("_")
if tokens[0] in {"helper", "agent"} and tokens[-1] in {"modern", "legacy"}:
return False
@@ -523,10 +560,8 @@ def scrub_windows_devenv_dirs_from_path(raw_path: str, env: Mapping[str, str]) -
return ";".join(clean_entries)
def quote(path: str) -> str:
if " " not in path:
return path
return "\"" + path.replace ("\"", "\\\"") + "\""
def escape_depfile_path(path: str) -> str:
return path.replace(" ", "\\ ")
def query_releng_location(role: Role) -> Path:
@@ -572,10 +607,10 @@ def grab_subprojects_from_parent(subprojects: dict[str, Path], releng_location:
continue
try:
subp_here.symlink_to(location, target_is_directory=True)
subp_here.symlink_to(Path("..") / ".." / name, target_is_directory=True)
continue
except OSError as e:
if not getattr(e, "winerror") == 1314:
if not getattr(e, "winerror", None) == 1314:
raise e
subprocess.run(["git", "worktree", "add", subp_here],
@@ -591,6 +626,12 @@ def configure_import_path(releng_location: Path):
sys.path.insert(0, str(releng_location.parent))
def detect_mingw_toolchain_for(arch: str) -> Tuple[bool, Optional[str]]:
triplet = MINGW_ARCHS.get(arch, arch) + "-w64-mingw32"
found = shutil.which(triplet + "-gcc") is not None
return (found, triplet)
STATE_FILENAME = "state.dat"
DEPFILE_FILENAME = "compat.deps"
@@ -618,6 +659,11 @@ MSVS_ENVVARS = {
"LIB",
}
MINGW_ARCHS = {
"x86": "i686",
"arm64": "aarch64",
}
if __name__ == "__main__":
main(sys.argv)
+3
View File
@@ -1,6 +1,8 @@
helper_modern = get_option('helper_modern')
helper_legacy = get_option('helper_legacy')
helper_compat = ''
helper_emulated_modern = get_option('helper_emulated_modern')
helper_emulated_legacy = get_option('helper_emulated_legacy')
helper_depends = []
agent_modern = get_option('agent_modern')
@@ -18,6 +20,7 @@ server_depends = []
no_overridden_compat_bits = \
helper_modern == 'auto' and helper_legacy == 'auto' \
and helper_emulated_modern == 'auto' and helper_emulated_legacy == 'auto' \
and agent_modern == 'auto' and agent_legacy == 'auto' \
and agent_emulated_modern == 'auto' and agent_emulated_legacy == 'auto'
+63 -34
View File
@@ -147,7 +147,7 @@ namespace Frida.Inject {
public extern void init ();
}
public class Application : Object {
public sealed class Application : Object {
public string? device_id {
get;
construct;
@@ -388,7 +388,7 @@ namespace Frida.Inject {
return false;
}
script_runner.on_stdin (line);
script_runner.on_stdin (line, null);
return true;
}
@@ -414,14 +414,19 @@ namespace Frida.Inject {
buf[n] = 0;
script_runner.on_stdin ((string) buf);
if (script_runner.terminal_mode == TerminalMode.BINARY) {
var bytes = new Bytes (buf[:n]);
script_runner.on_stdin ("", bytes);
} else {
script_runner.on_stdin ((string) buf, null);
}
return true;
}
#endif
}
private class ScriptRunner : Object, RpcPeer {
private sealed class ScriptRunner : Object, RpcPeer {
public TerminalMode terminal_mode {
get;
private set;
@@ -549,7 +554,7 @@ namespace Frida.Inject {
var stage = new Json.Node.alloc ().init_string ("early");
try {
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, io_cancellable);
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, null, io_cancellable);
} catch (GLib.Error e) {
}
}
@@ -591,7 +596,7 @@ namespace Frida.Inject {
private async TerminalMode query_terminal_mode () {
Json.Node mode_value;
try {
mode_value = yield rpc_client.call ("getFridaTerminalMode", new Json.Node[] {}, io_cancellable);
mode_value = yield rpc_client.call ("getFridaTerminalMode", new Json.Node[] {}, null, io_cancellable);
} catch (GLib.Error e) {
return COOKED;
}
@@ -599,7 +604,14 @@ namespace Frida.Inject {
if (mode_value.get_value_type () != typeof (string))
return COOKED;
return (mode_value.get_string () == "raw") ? TerminalMode.RAW : TerminalMode.COOKED;
switch (mode_value.get_string ()) {
case "raw":
return TerminalMode.RAW;
case "binary":
return TerminalMode.BINARY;
default:
return TerminalMode.COOKED;
}
}
private void apply_terminal_mode (TerminalMode mode) throws Error {
@@ -632,10 +644,10 @@ namespace Frida.Inject {
}
#endif
public void on_stdin (string data) {
var data_value = new Json.Node.alloc ().init_string (data);
public void on_stdin (string str, Bytes? data) {
var str_value = new Json.Node.alloc ().init_string (str);
rpc_client.call.begin ("onFridaStdin", new Json.Node[] { data_value }, io_cancellable);
rpc_client.call.begin ("onFridaStdin", new Json.Node[] { str_value }, data, io_cancellable);
}
private void on_script_file_changed (File file, File? other_file, FileMonitorEvent event_type) {
@@ -675,7 +687,7 @@ namespace Frida.Inject {
handled = try_handle_log_message (message);
break;
case "send":
handled = try_handle_stdout_message (message);
handled = try_handle_stdout_message (message, data);
break;
default:
handled = false;
@@ -722,20 +734,19 @@ namespace Frida.Inject {
*
* {"type":"send","payload":["frida:stdout","DATA"]}
*/
private bool try_handle_stdout_message (Json.Object message) {
private bool try_handle_stdout_message (Json.Object message, Bytes? data) {
var payload = message.get_member ("payload");
if (payload.get_node_type () != Json.NodeType.ARRAY)
return false;
var tuple = payload.get_array ();
if (tuple.get_length () != 2)
var tuple_len = tuple.get_length ();
if (tuple_len == 0)
return false;
var first_element = tuple.get_element (0);
if (first_element.get_value_type () != typeof (string))
var type = tuple.get_element (0).get_string ();
if (type == null)
return false;
var type = first_element.get_string ();
switch (type) {
case "frida:stdout":
case "frida:stderr":
@@ -744,31 +755,49 @@ namespace Frida.Inject {
return false;
}
var second_element = tuple.get_element (1);
if (second_element.get_value_type () != typeof (string))
return false;
var str = second_element.get_string ();
switch (type) {
case "frida:stdout":
stdout.write (str.data);
stdout.flush ();
return true;
case "frida:stderr":
stderr.write (str.data);
return true;
default:
if (tuple_len >= 2) {
var str = tuple.get_element (1).get_string ();
if (str == null)
return false;
switch (type) {
case "frida:stdout":
stdout.write (str.data);
stdout.flush ();
break;
case "frida:stderr":
stderr.write (str.data);
break;
default:
return false;
}
}
if (data != null) {
switch (type) {
case "frida:stdout":
stdout.write (data.get_data ());
stdout.flush ();
break;
case "frida:stderr":
stderr.write (data.get_data ());
break;
default:
return false;
}
}
return true;
}
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
script.post (json, null);
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
script.post (json, data);
}
}
private enum TerminalMode {
COOKED,
RAW
RAW,
BINARY
}
}
+22 -23
View File
@@ -11,7 +11,7 @@ namespace Frida.Agent {
PROCESS_TRANSITION
}
private class Runner : Object, ProcessInvader, AgentSessionProvider, ExitHandler, ForkHandler, SpawnHandler {
private sealed class Runner : Object, ProcessInvader, AgentSessionProvider, ExitHandler, ForkHandler, SpawnHandler {
public static Runner shared_instance = null;
public static Mutex shared_mutex;
private static string? cached_agent_path = null;
@@ -1400,12 +1400,12 @@ namespace Frida.Agent {
if (nb_api.unload_library == null)
parameters.append ("|eternal|sticky");
/*
* Disable ExitMonitor to work around a bug in Android's libndk_translation.so on Android 11.
* We need to avoid modifying libc.so ranges that the translator potentially depends on, to
* avoid blowing up when Interceptor's CPU cache flush results in the translated code being
* discarded, which seems like an edge-case the translator doesn't handle.
* Disable Exceptor and ExitMonitor to work around a bug in Android's libndk_translation.so
* on Android 11. We need to avoid modifying libc.so ranges that the translator potentially
* depends on, to avoid blowing up when Interceptor's CPU cache flush results in the translated
* code being discarded, which seems like an edge-case the translator doesn't handle.
*/
parameters.append ("|exit-monitor:off");
parameters.append ("|exceptor:off|exit-monitor:off");
emulated_bridge_state = new BridgeState (parameters.str);
@@ -1509,13 +1509,14 @@ namespace Frida.Agent {
}
public static NativeBridgeApi open () throws Error {
string? nb_mod = null;
string? vm_mod = null;
Gum.Process.enumerate_modules ((details) => {
if (/\/lib(64)?\/libnativebridge.so$/.match (details.path))
nb_mod = details.path;
else if (/^lib(art|dvm).so$/.match (details.name) && !/\/system\/fake-libs/.match (details.path))
vm_mod = details.path;
Gum.Module? nb_mod = null;
Gum.Module? vm_mod = null;
Gum.Process.enumerate_modules (module => {
unowned string path = module.path;
if (/\/lib(64)?\/libnativebridge.so$/.match (path))
nb_mod = module;
else if (/^lib(art|dvm).so$/.match (module.name) && !/\/system\/fake-libs/.match (path))
vm_mod = module;
bool carry_on = nb_mod == null || vm_mod == null;
return carry_on;
});
@@ -1530,29 +1531,27 @@ namespace Frida.Agent {
NBUnloadLibraryFunc? unload;
NBGetTrampolineFunc get_trampoline;
load = (NBLoadLibraryFunc) Gum.Module.find_export_by_name (nb_mod, "NativeBridgeLoadLibrary");;
load = (NBLoadLibraryFunc) nb_mod.find_export_by_name ("NativeBridgeLoadLibrary");;
if (load != null) {
flavor = MODERN;
load_ext = (NBLoadLibraryExtFunc) Gum.Module.find_export_by_name (nb_mod, "NativeBridgeLoadLibraryExt");
load_ext = (NBLoadLibraryExtFunc) nb_mod.find_export_by_name ("NativeBridgeLoadLibraryExt");
// XXX: NativeBridgeUnloadLibrary() is only a stub as of Android 11 w/ libndk_translation.so
unload = null;
get_trampoline = (NBGetTrampolineFunc) Gum.Module.find_export_by_name (nb_mod,
"NativeBridgeGetTrampoline");
get_trampoline = (NBGetTrampolineFunc) nb_mod.find_export_by_name ("NativeBridgeGetTrampoline");
} else {
flavor = LEGACY;
load = (NBLoadLibraryFunc) Gum.Module.find_export_by_name (nb_mod,
"_ZN7android23NativeBridgeLoadLibraryEPKci");
load_ext = (NBLoadLibraryExtFunc) Gum.Module.find_export_by_name (nb_mod,
load = (NBLoadLibraryFunc) nb_mod.find_export_by_name ("_ZN7android23NativeBridgeLoadLibraryEPKci");
load_ext = (NBLoadLibraryExtFunc) nb_mod.find_export_by_name (
"_ZN7android26NativeBridgeLoadLibraryExtEPKciPNS_25native_bridge_namespace_tE");
// XXX: Unload implementation seems to be unreliable.
unload = null;
get_trampoline = (NBGetTrampolineFunc) Gum.Module.find_export_by_name (nb_mod,
get_trampoline = (NBGetTrampolineFunc) nb_mod.find_export_by_name (
"_ZN7android25NativeBridgeGetTrampolineEPvPKcS2_j");
}
if (load == null || get_trampoline == null)
throw new Error.NOT_SUPPORTED ("NativeBridge API is not available on this system");
var get_vms = (JNIGetCreatedJavaVMsFunc) Gum.Module.find_export_by_name (vm_mod, "JNI_GetCreatedJavaVMs");
var get_vms = (JNIGetCreatedJavaVMsFunc) vm_mod.find_export_by_name ("JNI_GetCreatedJavaVMs");
if (get_vms == null)
throw new Error.NOT_SUPPORTED ("Unable to locate Java VM");
@@ -1622,7 +1621,7 @@ namespace Frida.Agent {
}
#endif
private class LiveAgentSession : BaseAgentSession {
private sealed class LiveAgentSession : BaseAgentSession {
public uint registration_id {
get;
set;
+8
View File
@@ -0,0 +1,8 @@
{
global:
frida_agent_main;
JNI_OnLoad;
local:
*;
};
-1
View File
@@ -1,7 +1,6 @@
{
global:
frida_agent_main;
JNI_OnLoad;
local:
*;
+1 -1
View File
@@ -28,7 +28,7 @@ if host_os_family == 'windows'
elif host_os_family == 'darwin'
extra_link_args += '-Wl,-exported_symbol,_frida_agent_main'
else
symscript = 'frida-agent.version'
symscript = (host_os == 'android') ? 'frida-agent-android.version' : 'frida-agent.version'
extra_link_args += '-Wl,--version-script,' + meson.current_source_dir() / symscript
extra_link_depends += symscript
endif
+150 -11
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class BufferBuilder : Object {
public sealed class BufferBuilder : Object {
public ByteOrder byte_order {
get;
construct;
@@ -307,7 +307,7 @@ namespace Frida {
NUL
}
public class Buffer : Object {
public sealed class Buffer : Object {
public Bytes bytes {
get;
construct;
@@ -428,21 +428,35 @@ namespace Frida {
return *((double *) &bits);
}
public string read_string (size_t offset) {
public string read_string (size_t offset) throws Error {
string * start = (string *) get_pointer (offset, sizeof (char));
size_t max_length = size - offset;
string * val = (string *) get_pointer (offset, sizeof (char));
string * end = memchr (val, 0, max_length);
assert (end != null);
size_t size = end - val;
return val->substring (0, (long) size);
string * end = memchr (start, 0, max_length);
if (end == null)
throw new Error.PROTOCOL ("Missing null character");
size_t size = end - start;
string val = start->substring (0, (long) size);
if (!val.validate ())
throw new Error.PROTOCOL ("Invalid UTF-8 string");
return val;
}
[CCode (cname = "memchr", cheader_filename = "string.h")]
private extern static string * memchr (string * s, int c, size_t n);
public string read_fixed_string (size_t offset, size_t size) {
string * val = (string *) get_pointer (offset, size);
return val->substring (0, (long) size);
public string read_fixed_string (size_t offset, size_t size) throws Error {
string * start = (string *) get_pointer (offset, size);
size_t max_length = size_t.min (size, this.size - offset);
string * end = memchr (start, 0, max_length);
size_t n;
if (end != null)
n = end - start;
else
n = size;
string val = start->substring (0, (long) n);
if (!val.validate ())
throw new Error.PROTOCOL ("Invalid UTF-8 string");
return val;
}
public unowned Buffer write_string (size_t offset, string val) {
@@ -458,4 +472,129 @@ namespace Frida {
return data + offset;
}
}
public sealed class BufferReader {
public size_t available {
get {
return buffer.bytes.get_size () - offset;
}
}
private Buffer buffer;
private size_t offset = 0;
public BufferReader (Buffer buf) {
buffer = buf;
}
public uint64 read_pointer (size_t offset) throws Error {
var pointer_size = buffer.pointer_size;
check_available (pointer_size);
var ptr = buffer.read_pointer (offset);
offset += pointer_size;
return ptr;
}
public int8 read_int8 () throws Error {
check_available (sizeof (int8));
var val = buffer.read_int8 (offset);
offset += sizeof (int8);
return val;
}
public uint8 read_uint8 () throws Error {
check_available (sizeof (uint8));
var val = buffer.read_uint8 (offset);
offset += sizeof (uint8);
return val;
}
public int16 read_int16 () throws Error {
check_available (sizeof (int16));
var val = buffer.read_int16 (offset);
offset += sizeof (int16);
return val;
}
public uint16 read_uint16 () throws Error {
check_available (sizeof (uint16));
var val = buffer.read_uint16 (offset);
offset += sizeof (uint16);
return val;
}
public int32 read_int32 () throws Error {
check_available (sizeof (int32));
var val = buffer.read_int32 (offset);
offset += sizeof (int32);
return val;
}
public uint32 read_uint32 () throws Error {
check_available (sizeof (uint32));
var val = buffer.read_uint32 (offset);
offset += sizeof (uint32);
return val;
}
public int64 read_int64 () throws Error {
check_available (sizeof (int64));
var val = buffer.read_int64 (offset);
offset += sizeof (int64);
return val;
}
public uint64 read_uint64 () throws Error {
check_available (sizeof (uint64));
var val = buffer.read_uint64 (offset);
offset += sizeof (uint64);
return val;
}
public float read_float () throws Error {
check_available (sizeof (float));
var val = buffer.read_float (offset);
offset += sizeof (float);
return val;
}
public double read_double () throws Error {
check_available (sizeof (double));
var val = buffer.read_double (offset);
offset += sizeof (double);
return val;
}
public string read_string () throws Error {
check_available (1);
var val = buffer.read_string (offset);
offset += val.length + 1;
return val;
}
public string read_fixed_string (size_t size) throws Error {
check_available (size);
var val = buffer.read_fixed_string (offset, size);
offset += size;
return val;
}
public Bytes read_bytes (size_t size) throws Error {
check_available (size);
var val = buffer.bytes[offset:offset + size];
offset += size;
return val;
}
public unowned BufferReader skip (size_t n) throws Error {
check_available (n);
offset += n;
return this;
}
private void check_available (size_t n) throws Error {
if (available < n)
throw new Error.PROTOCOL ("Malformed buffer: truncated");
}
}
}
+243
View File
@@ -0,0 +1,243 @@
namespace Frida {
public sealed class ChannelRegistry : Object {
public signal void channel_closed (ChannelId id);
private Gee.Map<ChannelId?, weak IOStream> channels =
new Gee.HashMap<ChannelId?, weak IOStream> (ChannelId.hash, ChannelId.equal);
~ChannelRegistry () {
clear ();
}
public void clear () {
foreach (IOStream stream in channels.values.to_array ()) {
var channel_stream = stream as ChannelStream;
if (channel_stream != null)
channel_stream.abandon ();
}
channels.clear ();
}
public void register (ChannelId id, IOStream stream) {
stream.set_data ("channel-registry-entry", new Entry (this, id));
lock (channels)
channels[id] = stream;
}
public IOStream link (ChannelId id) throws Error {
IOStream? stream;
lock (channels)
stream = channels[id];
if (stream == null)
throw new Error.INVALID_ARGUMENT ("Invalid channel ID");
return stream;
}
public void unlink (ChannelId id) {
lock (channels) {
if (!channels.unset (id))
return;
}
channel_closed (id);
}
private class Entry {
public ChannelRegistry parent;
public ChannelId id;
public Entry (ChannelRegistry parent, ChannelId id) {
this.parent = parent;
this.id = id;
}
~Entry () {
parent.unlink (id);
}
}
}
public sealed class ChannelEndpoint : Object, Channel {
private IOStream? stream;
private ByteArray write_queue = new ByteArray ();
private bool writing = false;
private Cancellable io_cancellable = new Cancellable ();
public ChannelEndpoint (IOStream stream) {
this.stream = stream;
read_loop.begin ();
}
public async void close (Cancellable? cancellable) throws Error, IOError {
io_cancellable.cancel ();
}
public async void input (uint8[] data, Cancellable? cancellable) throws Error, IOError {
if (io_cancellable.is_cancelled ())
throw new Error.INVALID_OPERATION ("Channel is closed");
write_queue.append (data);
if (!writing) {
writing = true;
var source = new IdleSource ();
source.set_callback (() => {
process_write_queue.begin ();
return false;
});
source.attach (MainContext.get_thread_default ());
}
}
private async void read_loop () {
var input = stream.get_input_stream ();
var buffer = new uint8[64 * 1024];
while (true) {
ssize_t n;
try {
n = yield input.read_async (buffer, Priority.DEFAULT, io_cancellable);
} catch (GLib.Error e) {
break;
}
output (buffer[:n]);
if (n == 0)
break;
}
stream.close_async.begin ();
stream = null;
}
private async void process_write_queue () {
if (stream != null) {
var output = stream.get_output_stream ();
while (write_queue.len > 0) {
uint8[] batch = write_queue.steal ();
size_t bytes_written;
try {
yield output.write_all_async (batch, Priority.DEFAULT, io_cancellable, out bytes_written);
} catch (GLib.Error e) {
break;
}
}
}
writing = false;
}
}
public sealed class ChannelStream : VirtualStream {
public Channel channel {
get;
construct;
}
private ByteArray recv_queue = new ByteArray ();
private ByteArray send_queue = new ByteArray ();
public ChannelStream (Channel channel) {
Object (channel: channel);
}
construct {
channel.output.connect (on_output);
}
public void abandon () {
with_state_lock (() => {
state = CLOSED;
update_pending_io ();
});
}
protected override IOCondition query_events () {
IOCondition new_events = 0;
if (recv_queue.len != 0 || state == CLOSED)
new_events |= IN;
if (state == OPEN)
new_events |= OUT;
return new_events;
}
protected override void handle_close () {
channel.close.begin (null);
}
public override ssize_t read (uint8[] buffer) throws IOError {
ssize_t n = 0;
with_state_lock (() => {
n = ssize_t.min (recv_queue.len, buffer.length);
if (n > 0) {
Memory.copy (buffer, recv_queue.data, n);
recv_queue.remove_range (0, (uint) n);
update_pending_io ();
} else {
if (state == OPEN)
n = -1;
}
});
if (n == -1)
throw new IOError.WOULD_BLOCK ("Resource temporarily unavailable");
return n;
}
public override ssize_t write (uint8[] buffer) throws IOError {
with_state_lock (() => {
send_queue.append (buffer);
});
if (main_context.is_owner ()) {
process_send_queue ();
} else {
var source = new IdleSource ();
source.set_callback (() => {
process_send_queue ();
return Source.REMOVE;
});
source.attach (main_context);
}
return buffer.length;
}
private void process_send_queue () {
uint8[]? chunk = null;
with_state_lock (() => {
size_t n = send_queue.len;
if (n == 0)
return;
chunk = send_queue.data[0:n];
send_queue.remove_range (0, (uint) n);
});
if (chunk == null)
return;
channel.input.begin (chunk, io_cancellable);
}
private void on_output (uint8[] data) {
with_state_lock (() => {
if (data.length != 0)
recv_queue.append (data);
else
state = CLOSED;
update_pending_io ();
});
}
}
}
+34
View File
@@ -0,0 +1,34 @@
namespace Frida {
public sealed class CFArray<T> {
private CoreFoundation.Array handle;
public static CFArray<T> wrap<T> (void * handle) {
return new CFArray<T> ((CoreFoundation.Array) handle);
}
private CFArray (CoreFoundation.Array handle) {
this.handle = handle;
}
public Iterator<T> iterator () {
return new Iterator<T> (handle);
}
public class Iterator<T> {
public CoreFoundation.Array handle;
private CoreFoundation.Index i = 0;
private CoreFoundation.Index length;
internal Iterator (CoreFoundation.Array arr) {
handle = arr;
length = arr.length;
}
public unowned T? next_value () {
if (i == length)
return null;
return handle[i++];
}
}
}
}
+1 -1
View File
@@ -60,7 +60,7 @@ namespace Frida {
return yield connection.get_proxy (null, ObjectPath.HOST_SESSION, DBusProxyFlags.NONE, cancellable);
}
private class DummyInputStream : InputStream {
private sealed class DummyInputStream : InputStream {
private bool done = false;
private Mutex mutex;
private Cond cond;
+51
View File
@@ -0,0 +1,51 @@
#include "frida-darwin.h"
gpointer
_frida_dispatch_retain (gpointer object)
{
dispatch_retain (object);
return object;
}
void
_frida_xpc_connection_set_event_handler (xpc_connection_t connection, FridaXpcHandler handler, gpointer user_data)
{
xpc_connection_set_event_handler (connection, ^(xpc_object_t object)
{
handler (object, user_data);
});
}
void
_frida_xpc_connection_send_message_with_reply (xpc_connection_t connection, xpc_object_t message, dispatch_queue_t replyq,
FridaXpcHandler handler, gpointer user_data, GDestroyNotify notify)
{
xpc_connection_send_message_with_reply (connection, message, replyq, ^(xpc_object_t object)
{
handler (object, user_data);
if (notify != NULL)
notify (user_data);
});
}
gchar *
_frida_xpc_object_to_string (xpc_object_t object)
{
gchar * result;
char * str;
str = xpc_copy_description (object);
result = g_strdup (str);
free (str);
return result;
}
gboolean
_frida_xpc_dictionary_apply (xpc_object_t dict, FridaXpcDictionaryApplier applier, gpointer user_data)
{
return xpc_dictionary_apply (dict, ^bool (const char * key, xpc_object_t val)
{
return applier (key, val, user_data);
});
}
+22
View File
@@ -0,0 +1,22 @@
#ifndef __FRIDA_DARWIN_H__
#define __FRIDA_DARWIN_H__
#ifdef HAVE_MACOS
#include <glib.h>
#include <xpc/xpc.h>
typedef void (* FridaXpcHandler) (xpc_object_t object, gpointer user_data);
typedef gboolean (* FridaXpcDictionaryApplier) (const gchar * key, xpc_object_t val, gpointer user_data);
gpointer _frida_dispatch_retain (gpointer object);
void _frida_xpc_connection_set_event_handler (xpc_connection_t connection, FridaXpcHandler handler, gpointer user_data);
void _frida_xpc_connection_send_message_with_reply (xpc_connection_t connection, xpc_object_t message, dispatch_queue_t replyq,
FridaXpcHandler handler, gpointer user_data, GDestroyNotify notify);
gchar * _frida_xpc_object_to_string (xpc_object_t object);
gboolean _frida_xpc_dictionary_apply (xpc_object_t dict, FridaXpcDictionaryApplier applier, gpointer user_data);
#endif
#endif
+114
View File
@@ -0,0 +1,114 @@
namespace Frida.FS {
public void mkdirp (File dir, Cancellable? cancellable = null) throws Error {
try {
dir.make_directory_with_parents (cancellable);
} catch (GLib.Error e) {
if (!(e is IOError.EXISTS))
throw new Error.PERMISSION_DENIED ("%s", e.message);
}
}
public void rmtree (File dir, Cancellable? cancellable = null) throws Error {
rmtree_worker (dir, 0, cancellable);
}
private void rmtree_worker (File dir, uint depth, Cancellable? cancellable = null) throws Error {
FileEnumerator enumerator;
try {
enumerator = dir.enumerate_children (FileAttribute.STANDARD_NAME, NOFOLLOW_SYMLINKS, cancellable);
} catch (GLib.Error e) {
if (depth == 0 && e is IOError.NOT_FOUND)
return;
throw new Error.PERMISSION_DENIED ("%s", e.message);
}
try {
FileInfo? info;
File? child;
while (enumerator.iterate (out info, out child, cancellable) && info != null) {
if (info == null)
continue;
if (info.get_file_type () == DIRECTORY)
rmtree (child, cancellable);
else
child.delete (cancellable);
}
dir.delete (cancellable);
} catch (GLib.Error e) {
if (!(e is IOError.EXISTS))
throw new Error.PERMISSION_DENIED ("%s", e.message);
}
}
public async void rmtree_async (File dir, Cancellable? cancellable = null) throws Error, IOError {
yield rmtree_async_worker (dir, 0, cancellable);
}
private async void rmtree_async_worker (File dir, uint depth, Cancellable? cancellable = null) throws Error, IOError {
int io_priority = Priority.DEFAULT;
FileEnumerator enumerator;
try {
enumerator = yield dir.enumerate_children_async (FileAttribute.STANDARD_NAME, NOFOLLOW_SYMLINKS, io_priority,
cancellable);
} catch (GLib.Error e) {
if (depth == 0 && e is IOError.NOT_FOUND)
return;
throw new Error.PERMISSION_DENIED ("%s", e.message);
}
try {
while (true) {
var batch = yield enumerator.next_files_async (1000, io_priority, cancellable);
if (batch.is_empty ())
break;
foreach (FileInfo info in batch) {
File child = dir.get_child (info.get_name ());
if (info.get_file_type () == DIRECTORY)
yield rmtree_async_worker (child, depth + 1, cancellable);
else
yield child.delete_async (io_priority, cancellable);
}
}
yield dir.delete_async (io_priority, cancellable);
} catch (GLib.Error e) {
throw new Error.PERMISSION_DENIED ("%s", e.message);
}
}
public async string read_all_text (File f, Cancellable? cancellable) throws Error, IOError {
Bytes b = yield read_all_bytes (f, cancellable);
string text = (string) b.get_data ();
if (!text.validate ())
throw new Error.PROTOCOL ("Unable to read '%s': invalid UTF-8", f.get_parse_name ());
return text;
}
public async void write_all_text (File f, string t, Cancellable? cancellable) throws Error, IOError {
yield write_all_bytes (f, new Bytes (t.data), cancellable);
}
public async Bytes read_all_bytes (File f, Cancellable? cancellable) throws Error, IOError {
try {
return yield f.load_bytes_async (cancellable, null);
} catch (GLib.Error e) {
if (e is IOError.CANCELLED)
throw (IOError) e;
if (e is IOError.NOT_FOUND)
throw new Error.INVALID_ARGUMENT ("%s", e.message);
throw new Error.PERMISSION_DENIED ("%s", e.message);
}
}
public async void write_all_bytes (File f, Bytes b, Cancellable? cancellable) throws Error, IOError {
try {
yield f.replace_contents_bytes_async (b, null, false, FileCreateFlags.NONE, cancellable, null);
} catch (GLib.Error e) {
if (e is IOError.CANCELLED)
throw (IOError) e;
throw new Error.PERMISSION_DENIED ("%s", e.message);
}
}
}
@@ -1,6 +1,7 @@
#ifndef __FRIDA_SYSCALL_H__
#define __FRIDA_SYSCALL_H__
#ifndef __FRIDA_LINUX_SYSCALL_H__
#define __FRIDA_LINUX_SYSCALL_H__
#include <linux/unistd.h>
#include <sys/syscall.h>
#undef SYS_process_vm_readv
@@ -14,7 +14,7 @@ namespace Frida {
[CCode (cheader_filename = "sys/mman.h", cname = "MAP_ANONYMOUS")]
public const int MAP_ANONYMOUS;
[CCode (cheader_filename = "linux/frida-syscall.h", cprefix = "SYS_", has_type_id = false)]
[CCode (cheader_filename = "linux-syscall.h", cprefix = "SYS_", has_type_id = false)]
public enum SysCall {
memfd_create,
pidfd_getfd,
+107
View File
@@ -0,0 +1,107 @@
namespace Frida {
private uint linux_major = 0;
private uint linux_minor = 0;
public bool check_kernel_version (uint major, uint minor) {
if (linux_major == 0) {
var name = Posix.utsname ();
name.release.scanf ("%u.%u", out linux_major, out linux_minor);
}
return (linux_major == major && linux_minor >= minor) || linux_major > major;
}
public class FileDescriptor : Object, FileDescriptorBased {
public int handle;
public FileDescriptor (int handle) {
this.handle = handle;
}
~FileDescriptor () {
if (handle != -1)
Posix.close (handle);
}
public int steal () {
int result = handle;
handle = -1;
return result;
}
public int get_fd () {
return handle;
}
}
public sealed class PidFileDescriptor : FileDescriptor {
private uint pid;
private PidFileDescriptor (int fd, uint pid) {
base (fd);
this.pid = pid;
}
public static bool is_supported () {
return check_kernel_version (5, 3);
}
public static bool getfd_is_supported () {
return check_kernel_version (5, 6);
}
public static PidFileDescriptor from_pid (uint pid) throws Error {
int fd = pidfd_open (pid, 0);
if (fd == -1)
throw_pidfd_error (pid, errno);
return new PidFileDescriptor (fd, pid);
}
public FileDescriptor getfd (int targetfd) throws Error {
int fd = pidfd_getfd (handle, targetfd, 0);
if (fd == -1)
throw_pidfd_error (pid, errno);
return new FileDescriptor (fd);
}
private static int pidfd_open (uint pid, uint flags) {
return Linux.syscall (SysCall.pidfd_open, pid, flags);
}
private static int pidfd_getfd (int pidfd, int targetfd, uint flags) {
return Linux.syscall (SysCall.pidfd_getfd, pidfd, targetfd, flags);
}
[NoReturn]
private static void throw_pidfd_error (uint pid, int err) throws Error {
switch (err) {
case Posix.ESRCH:
throw new Error.PROCESS_NOT_FOUND ("Process not found");
case Posix.EPERM:
throw new Error.PERMISSION_DENIED ("Unable to use pidfd for pid %u: %s", pid, strerror (err));
default:
throw new Error.NOT_SUPPORTED ("Unable to use pidfd for pid %u: %s", pid, strerror (err));
}
}
}
namespace MemoryFileDescriptor {
public bool is_supported () {
return check_kernel_version (3, 17);
}
public static FileDescriptor from_bytes (string name, Bytes bytes) {
assert (is_supported ());
var fd = new FileDescriptor (memfd_create (name, 0));
unowned uint8[] data = bytes.get_data ();
ssize_t n = Posix.write (fd.handle, data, data.length);
assert (n == data.length);
return fd;
}
private int memfd_create (string name, uint flags) {
return Linux.syscall (SysCall.memfd_create, name, flags);
}
}
}
+44 -2
View File
@@ -1,17 +1,43 @@
base_sources = [
'session.vala',
'session-glue.c',
'channel.vala',
'service.vala',
'stream.vala',
'rpc.vala',
'p2p.vala',
'p2p-glue.c',
'dbus.vala',
'promise.vala',
'fs.vala',
'socket.vala',
'socket-glue.c',
'buffer.vala',
'value.vala',
]
extra_vala_args = []
if host_os == 'macos'
base_sources += [
'xpc.vala',
'frida-darwin.c',
]
endif
if host_os_family == 'darwin'
base_sources += 'corefoundation.vala'
endif
if host_os_family == 'linux'
base_sources += 'linux.vala'
extra_vala_args += [
'--pkg=linux',
'--pkg=linux-system',
'--pkg=posix',
]
endif
extra_deps = []
if host_os_family != 'windows'
extra_vala_args += '--pkg=gio-unix-2.0'
@@ -22,21 +48,37 @@ base_vala_args = [gum_vala_args, '--pkg=gio-2.0', '--pkg=json-glib-1.0']
if nice_dep.found()
base_vala_args += '--pkg=nice'
endif
if host_os_family == 'darwin'
base_vala_args += [
'--pkg=corefoundation',
'--pkg=darwin-gcd',
'--pkg=darwin-xpc',
]
endif
if host_os_family == 'linux'
base_vala_args += [
'--vapidir=' + meson.current_source_dir(),
'--pkg=gio-unix-2.0',
]
endif
base_gir_name = f'FridaBase-@[email protected]'
base = static_library('frida-base-' + api_version, base_sources,
c_args: frida_component_cflags,
vala_args: [base_vala_args, '--pkg=libsoup-3.0'] + extra_vala_args,
vala_header: 'frida-base.h',
vala_gir: base_gir_name,
vala_vapi: f'frida-base-@[email protected]',
dependencies: [glib_dep, gobject_dep, gio_dep, libsoup_dep, nice_dep, usrsctp_dep, gee_dep, json_glib_dep, gum_dep, openssl_dep] + extra_deps,
install: true,
install_dir: [true, header_install_dir, true],
install_dir: [true, header_install_dir, true, false],
)
base_dep = declare_dependency(
include_directories: include_directories('.'),
link_with: base,
dependencies: [nice_dep, json_glib_dep, gum_dep],
dependencies: [nice_dep, json_glib_dep, gum_dep] + extra_deps,
)
base_build_dir = meson.current_build_dir()
+37 -248
View File
@@ -169,7 +169,7 @@ namespace Frida {
}
}
public class PeerSocket : Object, DatagramBased {
public sealed class PeerSocket : Object, DatagramBased {
public Nice.Agent agent {
get;
construct;
@@ -452,6 +452,8 @@ namespace Frida {
if ((_pending_io & c) != 0)
source.set_ready_time (0);
}
notify_property ("pending-io");
}
private void prepare_for_io (int64 timeout, Cancellable? cancellable, out int64 deadline) throws IOError {
@@ -563,7 +565,7 @@ namespace Frida {
}
}
public class SctpConnection : IOStream {
public sealed class SctpConnection : VirtualStream {
public DatagramBased transport_socket {
get;
construct;
@@ -584,55 +586,14 @@ namespace Frida {
construct;
}
public State state {
get {
return _state;
}
}
public override InputStream input_stream {
get {
return _input_stream;
}
}
public override OutputStream output_stream {
get {
return _output_stream;
}
}
public IOCondition pending_io {
get {
lock (state)
return sctp_events;
}
}
private State _state = CREATED;
private SctpInputStream _input_stream;
private SctpOutputStream _output_stream;
private DatagramBasedSource transport_source;
private uint8[] transport_buffer = new uint8[65536];
private void * sctp_socket;
private IOCondition sctp_events = 0;
private SctpTimerSource sctp_source;
private uint16 stream_id;
private ByteArray dcep_message = new ByteArray ();
private Gee.Map<unowned Source, IOCondition> sources = new Gee.HashMap<unowned Source, IOCondition> ();
private Cancellable io_cancellable = new Cancellable ();
public enum State {
CREATED,
OPENING,
OPENED,
CLOSED
}
public SctpConnection (DatagramBased transport_socket, PeerSetup setup, uint16 port, size_t max_message_size) {
Object (
transport_socket: transport_socket,
@@ -649,14 +610,9 @@ namespace Frida {
protected extern static void _initialize_sctp_backend ();
construct {
_input_stream = new SctpInputStream (this);
_output_stream = new SctpOutputStream (this);
sctp_socket = _create_sctp_socket ();
_connect_sctp_socket (sctp_socket, port);
var main_context = MainContext.get_thread_default ();
transport_source = transport_socket.create_source (IOCondition.IN, io_cancellable);
transport_source.set_callback (on_transport_socket_readable);
transport_source.attach (main_context);
@@ -669,17 +625,22 @@ namespace Frida {
protected extern void _connect_sctp_socket (void * sock, uint16 port);
public override bool close (GLib.Cancellable? cancellable) throws IOError {
do_close ();
return true;
protected override VirtualStream.State query_initial_state () {
return CREATED;
}
public override async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws IOError {
do_close ();
return true;
protected override IOCondition query_events () {
return _query_sctp_socket_events (sctp_socket);
}
private void do_close () {
protected override void update_pending_io () {
base.update_pending_io ();
sctp_source.invalidate ();
}
protected extern static IOCondition _query_sctp_socket_events (void * sock);
protected override void handle_close () {
sctp_source.destroy ();
transport_source.destroy ();
@@ -689,13 +650,17 @@ namespace Frida {
public extern static void _close (void * sock);
public void shutdown (SctpShutdownType type) throws IOError {
_shutdown (sctp_socket, type);
public override void shutdown_read () throws IOError {
_shutdown (sctp_socket, READ);
}
public override void shutdown_write () throws IOError {
_shutdown (sctp_socket, WRITE);
}
public extern static void _shutdown (void * sock, SctpShutdownType type) throws IOError;
public ssize_t recv (uint8[] buffer) throws IOError {
public override ssize_t read (uint8[] buffer) throws IOError {
ssize_t n = -1;
try {
@@ -711,18 +676,18 @@ namespace Frida {
handle_dcep_message (stream_id, dcep_message.steal ());
}
throw new IOError.WOULD_BLOCK ("Resource temporarily unavailable");
} else if (protocol_id == NONE || _state != OPENED) {
} else if (protocol_id == NONE || state != OPEN) {
throw new IOError.WOULD_BLOCK ("Resource temporarily unavailable");
}
} finally {
update_sctp_events ();
update_pending_io ();
}
return n;
}
public ssize_t send (uint8[] buffer) throws IOError {
if (_state != OPENED)
public override ssize_t write (uint8[] buffer) throws IOError {
if (state != OPEN)
throw new IOError.WOULD_BLOCK ("Resource temporarily unavailable");
ssize_t n = ssize_t.min (buffer.length, (ssize_t) max_message_size);
@@ -730,20 +695,10 @@ namespace Frida {
try {
return _send (sctp_socket, stream_id, WEBRTC_BINARY, buffer[0:n]);
} finally {
update_sctp_events ();
update_pending_io ();
}
}
public void register_source (Source source, IOCondition condition) {
lock (state)
sources[source] = condition | IOCondition.ERR | IOCondition.HUP;
}
public void unregister_source (Source source) {
lock (state)
sources.unset (source);
}
private bool on_transport_socket_readable (DatagramBased datagram_based, IOCondition condition) {
var v = InputVector ();
v.buffer = transport_buffer;
@@ -774,31 +729,18 @@ namespace Frida {
protected extern void _handle_transport_packet (uint8[] data);
protected int _emit_transport_packet (uint8[] data) {
var v = OutputVector ();
v.buffer = data;
v.size = data.length;
OutputVector[] vectors = { v };
var m = OutputMessage ();
m.vectors = vectors;
m.num_vectors = vectors.length;
OutputMessage[] messages = { m };
try {
transport_socket.send_messages (messages, 0, 0, io_cancellable);
Udp.send (data, transport_socket, io_cancellable);
return 0;
} catch (GLib.Error e) {
return -1;
}
return 0;
}
protected void _on_sctp_socket_events_changed () {
update_sctp_events ();
update_pending_io ();
if (_state == CREATED && setup == ACTIVE && (sctp_events & IOCondition.OUT) != 0) {
if (state == CREATED && setup == ACTIVE && (pending_io & IOCondition.OUT) != 0) {
stream_id = 1;
uint8[] open_message = {
@@ -812,31 +754,12 @@ namespace Frida {
};
try {
_send (sctp_socket, stream_id, WEBRTC_DCEP, open_message);
_state = OPENING;
state = OPENING;
} catch (IOError e) {
}
}
}
private void update_sctp_events () {
IOCondition new_events = _query_sctp_socket_events (sctp_socket);
lock (state) {
sctp_events = new_events;
foreach (var entry in sources.entries) {
unowned Source source = entry.key;
IOCondition c = entry.value;
if ((new_events & c) != 0)
source.set_ready_time (0);
}
sctp_source.invalidate ();
}
}
protected extern static IOCondition _query_sctp_socket_events (void * sock);
protected extern static ssize_t _recv (void * sock, uint8[] buffer, out uint16 stream_id,
out PayloadProtocolId protocol_id, out SctpMessageFlags message_flags) throws IOError;
@@ -848,7 +771,7 @@ namespace Frida {
switch (type) {
case DATA_CHANNEL_OPEN: {
if (_state != CREATED || setup == ACTIVE)
if (state != CREATED || setup == ACTIVE)
return;
this.stream_id = stream_id;
@@ -856,15 +779,15 @@ namespace Frida {
uint8[] reply = { DcepMessageType.DATA_CHANNEL_ACK };
_send (sctp_socket, stream_id, WEBRTC_DCEP, reply);
_state = OPENED;
state = OPEN;
break;
}
case DATA_CHANNEL_ACK:
if (_state != OPENING)
if (state != OPENING)
return;
_state = OPENED;
state = OPEN;
break;
}
@@ -899,140 +822,6 @@ namespace Frida {
DATA_CHANNEL_ACK = 0x02
}
private class SctpInputStream : InputStream, PollableInputStream {
public weak SctpConnection connection {
get;
construct;
}
public SctpInputStream (SctpConnection connection) {
Object (connection: connection);
}
public override bool close (Cancellable? cancellable) throws IOError {
connection.shutdown (READ);
return true;
}
public override async bool close_async (int io_priority, Cancellable? cancellable) throws GLib.IOError {
return close (cancellable);
}
public override ssize_t read (uint8[] buffer, Cancellable? cancellable) throws IOError {
assert_not_reached ();
}
public bool can_poll () {
return true;
}
public bool is_readable () {
return (connection.pending_io & IOCondition.IN) != 0;
}
public PollableSource create_source (Cancellable? cancellable) {
return new PollableSource.full (this, new SctpIOSource (connection, IOCondition.IN), cancellable);
}
public ssize_t read_nonblocking_fn (uint8[] buffer) throws GLib.Error {
return connection.recv (buffer);
}
}
private class SctpOutputStream : OutputStream, PollableOutputStream {
public weak SctpConnection connection {
get;
construct;
}
public SctpOutputStream (SctpConnection connection) {
Object (connection: connection);
}
public override bool close (Cancellable? cancellable) throws IOError {
connection.shutdown (WRITE);
return true;
}
public override async bool close_async (int io_priority, Cancellable? cancellable) throws GLib.IOError {
return close (cancellable);
}
public override bool flush (GLib.Cancellable? cancellable) throws GLib.Error {
return true;
}
public override async bool flush_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error {
return true;
}
public override ssize_t write (uint8[] buffer, Cancellable? cancellable) throws IOError {
assert_not_reached ();
}
public bool can_poll () {
return true;
}
public bool is_writable () {
return (connection.pending_io & IOCondition.OUT) != 0;
}
public PollableSource create_source (Cancellable? cancellable) {
return new PollableSource.full (this, new SctpIOSource (connection, IOCondition.OUT), cancellable);
}
public ssize_t write_nonblocking_fn (uint8[]? buffer) throws GLib.Error {
return connection.send (buffer);
}
public PollableReturn writev_nonblocking_fn (OutputVector[] vectors, out size_t bytes_written) throws GLib.Error {
assert_not_reached ();
}
}
private class SctpIOSource : Source {
public SctpConnection connection;
public IOCondition condition;
public SctpIOSource (SctpConnection connection, IOCondition condition) {
this.connection = connection;
this.condition = condition;
connection.register_source (this, condition);
}
~SctpIOSource () {
connection.unregister_source (this);
}
protected override bool prepare (out int timeout) {
timeout = -1;
return (connection.pending_io & condition) != 0;
}
protected override bool check () {
return (connection.pending_io & condition) != 0;
}
protected override bool dispatch (SourceFunc? callback) {
set_ready_time (-1);
if (callback == null)
return Source.REMOVE;
return callback ();
}
protected static bool closure_callback (Closure closure) {
var return_value = Value (typeof (bool));
closure.invoke (ref return_value, {});
return return_value.get_boolean ();
}
}
private class SctpTimerSource : Source {
private static int64 last_process_time = -1;
+53 -13
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class Promise<T> {
public sealed class Promise<T> {
private Impl<T> impl;
public Future<T> future {
@@ -46,7 +46,8 @@ namespace Frida {
}
private GLib.Error? _error;
private Gee.ArrayQueue<CompletionFuncEntry> on_complete;
private Gee.ArrayQueue<CompletionFuncEntry>? on_complete;
private Gee.ArrayQueue<ThenHandlerEntry<T>>? on_then;
public async T wait_async (Cancellable? cancellable) throws Frida.Error, IOError {
if (_ready)
@@ -74,7 +75,21 @@ namespace Frida {
return get_result ();
}
private T get_result () throws Frida.Error, IOError {
public void then (owned FutureCompletionHandler<T> handler) {
if (_ready) {
schedule (() => {
handler (this);
return Source.REMOVE;
});
return;
}
if (on_then == null)
on_then = new Gee.ArrayQueue<ThenHandlerEntry<T>> ();
on_then.offer (new ThenHandlerEntry<T> ((owned) handler));
}
public T get_result () throws Frida.Error, IOError {
if (error != null) {
if (error is Frida.Error)
throw (Frida.Error) error;
@@ -111,19 +126,32 @@ namespace Frida {
internal void transition_to_ready () {
_ready = true;
if (on_complete != null && !on_complete.is_empty) {
var source = new IdleSource ();
source.set_priority (Priority.HIGH);
source.set_callback (() => {
CompletionFuncEntry? entry;
while ((entry = on_complete.poll ()) != null)
entry.func ();
on_complete = null;
return false;
if (on_complete != null || on_then != null) {
schedule (() => {
if (on_complete != null) {
CompletionFuncEntry? entry;
while ((entry = on_complete.poll ()) != null)
entry.func ();
on_complete = null;
}
if (on_then != null) {
ThenHandlerEntry? entry;
while ((entry = on_then.poll ()) != null)
entry.handler (this);
on_then = null;
}
return Source.REMOVE;
});
source.attach (MainContext.get_thread_default ());
}
}
private static void schedule (owned SourceFunc function) {
var source = new IdleSource ();
source.set_callback ((owned) function);
source.attach (MainContext.get_thread_default ());
}
}
private class CompletionFuncEntry {
@@ -133,6 +161,14 @@ namespace Frida {
this.func = (owned) func;
}
}
private class ThenHandlerEntry<T> {
public FutureCompletionHandler<T> handler;
public ThenHandlerEntry (owned FutureCompletionHandler<T> handler) {
this.handler = (owned) handler;
}
}
}
public interface Future<T> : Object {
@@ -140,5 +176,9 @@ namespace Frida {
public abstract T? value { get; }
public abstract GLib.Error? error { get; }
public abstract async T wait_async (Cancellable? cancellable) throws Frida.Error, IOError;
public abstract void then (owned FutureCompletionHandler<T> handler);
public abstract T get_result () throws Frida.Error, IOError;
}
public delegate void FutureCompletionHandler<T> (Future<T> future);
}
+4 -4
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class RpcClient : Object {
public sealed class RpcClient : Object {
public weak RpcPeer peer {
get;
construct;
@@ -11,7 +11,7 @@ namespace Frida {
Object (peer: peer);
}
public async Json.Node call (string method, Json.Node[] args, Cancellable? cancellable) throws Error, IOError {
public async Json.Node call (string method, Json.Node[] args, Bytes? data, Cancellable? cancellable) throws Error, IOError {
string request_id = Uuid.string_random ();
var request = new Json.Builder ();
@@ -39,7 +39,7 @@ namespace Frida {
pending_responses[request_id] = pending;
try {
yield peer.post_rpc_message (raw_request, cancellable);
yield peer.post_rpc_message (raw_request, data, cancellable);
} catch (Error e) {
if (pending_responses.unset (request_id))
pending.complete_with_error (e);
@@ -158,6 +158,6 @@ namespace Frida {
}
public interface RpcPeer : Object {
public abstract async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError;
public abstract async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError;
}
}
+48
View File
@@ -0,0 +1,48 @@
namespace Frida {
public sealed class ServiceSessionRegistry : Object {
public signal void session_closed (ServiceSessionId id);
private Gee.Map<ServiceSessionId?, ServiceSession> sessions =
new Gee.HashMap<ServiceSessionId?, ServiceSession> (ServiceSessionId.hash, ServiceSessionId.equal);
~ServiceSessionRegistry () {
clear ();
}
public void clear () {
foreach (var session in sessions.values.to_array ())
session.close ();
sessions.clear ();
}
public void register (ServiceSessionId id, ServiceSession session) {
sessions[id] = session;
ServiceSessionId? boxed_id = id;
session.set_data ("service-session-id", boxed_id);
session.close.connect (on_session_close);
}
public ServiceSession link (ServiceSessionId id) throws Error {
var session = sessions[id];
if (session == null)
throw new Error.INVALID_ARGUMENT ("Invalid session ID");
return session;
}
public void unlink (ServiceSessionId id) {
ServiceSession? session;
if (sessions.unset (id, out session)) {
session.close.disconnect (on_session_close);
session_closed (id);
}
}
private void on_session_close (ServiceSession session) {
ServiceSessionId? id = session.get_data ("service-session-id");
unlink (id);
}
}
}
+116 -25
View File
@@ -1,5 +1,5 @@
namespace Frida {
[DBus (name = "re.frida.HostSession16")]
[DBus (name = "re.frida.HostSession17")]
public interface HostSession : Object {
public abstract async void ping (uint interval_seconds, Cancellable? cancellable) throws GLib.Error;
@@ -27,6 +27,10 @@ namespace Frida {
public abstract async InjectorPayloadId inject_library_blob (uint pid, uint8[] blob, string entrypoint, string data,
Cancellable? cancellable) throws GLib.Error;
public abstract async ChannelId open_channel (string address, Cancellable? cancellable) throws GLib.Error;
public abstract async ServiceSessionId open_service (string address, Cancellable? cancellable) throws GLib.Error;
public signal void spawn_added (HostSpawnInfo info);
public signal void spawn_removed (HostSpawnInfo info);
public signal void child_added (HostChildInfo info);
@@ -34,10 +38,12 @@ namespace Frida {
public signal void process_crashed (CrashInfo crash);
public signal void output (uint pid, int fd, uint8[] data);
public signal void agent_session_detached (AgentSessionId id, SessionDetachReason reason, CrashInfo crash);
public signal void channel_closed (ChannelId id);
public signal void service_session_closed (ServiceSessionId id);
public signal void uninjected (InjectorPayloadId id);
}
[DBus (name = "re.frida.AgentSessionProvider16")]
[DBus (name = "re.frida.AgentSessionProvider17")]
public interface AgentSessionProvider : Object {
public abstract async void open (AgentSessionId id, HashTable<string, Variant> options,
Cancellable? cancellable) throws GLib.Error;
@@ -52,7 +58,7 @@ namespace Frida {
public signal void child_gating_changed (uint subscriber_count);
}
[DBus (name = "re.frida.AgentSession16")]
[DBus (name = "re.frida.AgentSession17")]
public interface AgentSession : Object {
public abstract async void close (Cancellable? cancellable) throws GLib.Error;
@@ -94,7 +100,7 @@ namespace Frida {
public signal void candidate_gathering_done ();
}
[DBus (name = "re.frida.AgentController16")]
[DBus (name = "re.frida.AgentController17")]
public interface AgentController : Object {
#if !WINDOWS
public abstract async HostChildId prepare_to_fork (uint parent_pid, Cancellable? cancellable, out uint parent_injectee_id,
@@ -115,7 +121,7 @@ namespace Frida {
Cancellable? cancellable) throws GLib.Error;
}
[DBus (name = "re.frida.AgentMessageSink16")]
[DBus (name = "re.frida.AgentMessageSink17")]
public interface AgentMessageSink : Object {
public abstract async void post_messages (AgentMessage[] messages, uint batch_id,
Cancellable? cancellable) throws GLib.Error;
@@ -145,7 +151,7 @@ namespace Frida {
DEBUGGER
}
public class AgentMessageTransmitter : Object {
public sealed class AgentMessageTransmitter : Object {
public signal void closed ();
public signal void new_candidates (string[] candidate_sdps);
public signal void candidate_gathering_done ();
@@ -743,13 +749,30 @@ namespace Frida {
}
}
[DBus (name = "re.frida.TransportBroker16")]
[DBus (name = "re.frida.Channel17")]
public interface Channel : Object {
public abstract async void close (Cancellable? cancellable) throws GLib.Error;
public abstract async void input (uint8[] data, Cancellable? cancellable) throws GLib.Error;
public signal void output (uint8[] data);
}
[DBus (name = "re.frida.ServiceSession17")]
public interface ServiceSession : Object {
public signal void close ();
public signal void message (Variant message);
public abstract async void activate (Cancellable? cancellable) throws GLib.Error;
public abstract async void cancel (Cancellable? cancellable) throws GLib.Error;
public abstract async Variant request (Variant parameters, Cancellable? cancellable) throws GLib.Error;
}
[DBus (name = "re.frida.TransportBroker17")]
public interface TransportBroker : Object {
public abstract async void open_tcp_transport (AgentSessionId id, Cancellable? cancellable, out uint16 port,
out string token) throws GLib.Error;
}
[DBus (name = "re.frida.PortalSession16")]
[DBus (name = "re.frida.PortalSession17")]
public interface PortalSession : Object {
public abstract async void join (HostApplicationInfo app, SpawnStartState current_state,
AgentSessionId[] interrupted_sessions, HashTable<string, Variant> options, Cancellable? cancellable,
@@ -758,19 +781,19 @@ namespace Frida {
public signal void kill ();
}
[DBus (name = "re.frida.BusSession16")]
[DBus (name = "re.frida.BusSession17")]
public interface BusSession : Object {
public abstract async void attach (Cancellable? cancellable) throws GLib.Error;
public abstract async void post (string json, bool has_data, uint8[] data, Cancellable? cancellable) throws GLib.Error;
public signal void message (string json, bool has_data, uint8[] data);
}
[DBus (name = "re.frida.AuthenticationService16")]
[DBus (name = "re.frida.AuthenticationService17")]
public interface AuthenticationService : Object {
public abstract async string authenticate (string token, Cancellable? cancellable) throws GLib.Error;
}
public class StaticAuthenticationService : Object, AuthenticationService {
public sealed class StaticAuthenticationService : Object, AuthenticationService {
public string token_hash {
get;
construct;
@@ -795,13 +818,13 @@ namespace Frida {
}
}
public class NullAuthenticationService : Object, AuthenticationService {
public sealed class NullAuthenticationService : Object, AuthenticationService {
public async string authenticate (string token, Cancellable? cancellable) throws Error, IOError {
throw new Error.INVALID_OPERATION ("Authentication not expected");
}
}
public class UnauthorizedHostSession : Object, HostSession {
public sealed class UnauthorizedHostSession : Object, HostSession {
public async void ping (uint interval_seconds, Cancellable? cancellable) throws Error, IOError {
throw_not_authorized ();
}
@@ -875,9 +898,17 @@ namespace Frida {
Cancellable? cancellable) throws Error, IOError {
throw_not_authorized ();
}
public async ChannelId open_channel (string address, Cancellable? cancellable) throws Error, IOError {
throw_not_authorized ();
}
public async ServiceSessionId open_service (string address, Cancellable? cancellable) throws Error, IOError {
throw_not_authorized ();
}
}
public class UnauthorizedPortalSession : Object, PortalSession {
public sealed class UnauthorizedPortalSession : Object, PortalSession {
public async void join (HostApplicationInfo app, SpawnStartState current_state,
AgentSessionId[] interrupted_sessions, HashTable<string, Variant> options,
Cancellable? cancellable, out SpawnStartState next_state) throws Error, IOError {
@@ -885,7 +916,7 @@ namespace Frida {
}
}
public class UnauthorizedBusSession : Object, BusSession {
public sealed class UnauthorizedBusSession : Object, BusSession {
public async void attach (Cancellable? cancellable) throws Error, IOError {
throw_not_authorized ();
}
@@ -1083,7 +1114,7 @@ namespace Frida {
}
}
public class FrontmostQueryOptions : Object {
public sealed class FrontmostQueryOptions : Object {
public Scope scope {
get;
set;
@@ -1113,7 +1144,7 @@ namespace Frida {
}
}
public class ApplicationQueryOptions : Object {
public sealed class ApplicationQueryOptions : Object {
public Scope scope {
get;
set;
@@ -1171,7 +1202,7 @@ namespace Frida {
}
}
public class ProcessQueryOptions : Object {
public sealed class ProcessQueryOptions : Object {
public Scope scope {
get;
set;
@@ -1313,7 +1344,7 @@ namespace Frida {
}
}
public class SessionOptions : Object {
public sealed class SessionOptions : Object {
public Realm realm {
get;
set;
@@ -1502,6 +1533,46 @@ namespace Frida {
}
}
public struct ChannelId {
public string handle;
public ChannelId (string handle) {
this.handle = handle;
}
public ChannelId.generate () {
this.handle = Uuid.string_random ().replace ("-", "");
}
public static uint hash (ChannelId? id) {
return id.handle.hash ();
}
public static bool equal (ChannelId? a, ChannelId? b) {
return a.handle == b.handle;
}
}
public struct ServiceSessionId {
public string handle;
public ServiceSessionId (string handle) {
this.handle = handle;
}
public ServiceSessionId.generate () {
this.handle = Uuid.string_random ().replace ("-", "");
}
public static uint hash (ServiceSessionId? id) {
return id.handle.hash ();
}
public static bool equal (ServiceSessionId? a, ServiceSessionId? b) {
return a.handle == b.handle;
}
}
public struct AgentScriptId {
public uint handle;
@@ -1518,7 +1589,7 @@ namespace Frida {
}
}
public class ScriptOptions : Object {
public sealed class ScriptOptions : Object {
public string? name {
get;
set;
@@ -1608,7 +1679,7 @@ namespace Frida {
SHARED_MEMORY
}
public class SnapshotOptions : Object {
public sealed class SnapshotOptions : Object {
public string? warmup_script {
get;
set;
@@ -1683,7 +1754,7 @@ namespace Frida {
}
}
public class PortalOptions : Object {
public sealed class PortalOptions : Object {
public TlsCertificate? certificate {
get;
set;
@@ -1746,7 +1817,7 @@ namespace Frida {
}
}
public class PeerOptions : Object {
public sealed class PeerOptions : Object {
public string? stun_server {
get;
set;
@@ -1807,7 +1878,7 @@ namespace Frida {
}
}
public class Relay : Object {
public sealed class Relay : Object {
public string address {
get;
construct;
@@ -2048,7 +2119,8 @@ namespace Frida {
public const string AGENT_SESSION = "/re/frida/AgentSession";
public const string AGENT_CONTROLLER = "/re/frida/AgentController";
public const string AGENT_MESSAGE_SINK = "/re/frida/AgentMessageSink";
public const string CHILD_SESSION = "/re/frida/ChildSession";
public const string CHANNEL = "/re/frida/Channel";
public const string SERVICE = "/re/frida/Service";
public const string TRANSPORT_BROKER = "/re/frida/TransportBroker";
public const string PORTAL_SESSION = "/re/frida/PortalSession";
public const string BUS_SESSION = "/re/frida/BusSession";
@@ -2061,6 +2133,14 @@ namespace Frida {
public static string for_agent_message_sink (AgentSessionId id) {
return AGENT_MESSAGE_SINK + "/" + id.handle;
}
public static string for_channel (ChannelId id) {
return CHANNEL + "/" + id.handle;
}
public static string for_service_session (ServiceSessionId id) {
return SERVICE + "/" + id.handle;
}
}
namespace Marshal {
@@ -2079,6 +2159,17 @@ namespace Frida {
}
namespace Numeric {
public uint int64_hash (int64? val) {
uint64 v = (uint64) val.abs ();
return (uint) ((v >> 32) ^ (v & 0xffffffffU));
}
public bool int64_equal (int64? val_a, int64? val_b) {
int64 a = val_a;
int64 b = val_b;
return a == b;
}
public uint uint64_hash (uint64? val) {
uint64 v = val;
return (uint) ((v >> 32) ^ (v & 0xffffffffU));
+610 -587
View File
File diff suppressed because it is too large. Load diff
+336
View File
@@ -0,0 +1,336 @@
namespace Frida {
public abstract class VirtualStream : IOStream {
public override InputStream input_stream {
get {
return _input_stream;
}
}
public override OutputStream output_stream {
get {
return _output_stream;
}
}
public IOCondition pending_io {
get {
lock (state)
return _pending_io;
}
}
protected State state = OPEN;
private VirtualInputStream _input_stream;
private VirtualOutputStream _output_stream;
private IOCondition _pending_io;
private Gee.Map<unowned Source, IOCondition> sources = new Gee.HashMap<unowned Source, IOCondition> ();
protected Cancellable io_cancellable = new Cancellable ();
protected MainContext main_context;
protected enum State {
CREATED,
OPENING,
OPEN,
CLOSED
}
protected delegate void WorkFunc ();
construct {
_input_stream = new VirtualInputStream (this);
_output_stream = new VirtualOutputStream (this);
main_context = MainContext.ref_thread_default ();
state = query_initial_state ();
_pending_io = query_events ();
}
public override void dispose () {
_output_stream.detach ();
_input_stream.detach ();
io_cancellable.cancel ();
base.dispose ();
}
protected virtual State query_initial_state () {
return OPEN;
}
protected abstract IOCondition query_events ();
public override bool close (GLib.Cancellable? cancellable) throws IOError {
_close ();
return true;
}
public override async bool close_async (int io_priority, GLib.Cancellable? cancellable) throws IOError {
_close ();
return true;
}
private void _close () {
if (main_context.is_owner ()) {
do_close ();
} else {
var source = new IdleSource ();
source.set_callback (() => {
do_close ();
return Source.REMOVE;
});
source.attach (main_context);
}
}
private void do_close () {
if (state == CLOSED)
return;
handle_close ();
}
protected abstract void handle_close ();
public virtual void shutdown_read () throws IOError {
}
public virtual void shutdown_write () throws IOError {
}
public abstract ssize_t read (uint8[] buffer) throws IOError;
public abstract ssize_t write (uint8[] buffer) throws IOError;
protected void with_state_lock (WorkFunc func) {
lock (state)
func ();
}
public void register_source (Source source, IOCondition condition) {
lock (state)
sources[source] = condition | IOCondition.ERR | IOCondition.HUP;
}
public void unregister_source (Source source) {
lock (state)
sources.unset (source);
}
protected virtual void update_pending_io () {
lock (state) {
_pending_io = query_events ();
foreach (var entry in sources.entries) {
unowned Source source = entry.key;
IOCondition c = entry.value;
if ((_pending_io & c) != 0)
source.set_ready_time (0);
}
}
notify_property ("pending-io");
}
}
private sealed class VirtualInputStream : InputStream, PollableInputStream {
private weak VirtualStream stream;
public VirtualInputStream (VirtualStream stream) {
Object ();
this.stream = stream;
}
internal void detach () {
stream = null;
}
public override bool close (Cancellable? cancellable) throws IOError {
if (stream != null)
stream.shutdown_read ();
return true;
}
public override async bool close_async (int io_priority, Cancellable? cancellable) throws GLib.IOError {
return close (cancellable);
}
public override ssize_t read (uint8[] buffer, Cancellable? cancellable) throws IOError {
if (stream == null)
return 0;
if (!is_readable ()) {
bool done = false;
var mutex = Mutex ();
var cond = Cond ();
ulong io_handler = stream.notify["pending-io"].connect ((obj, pspec) => {
if (is_readable ()) {
mutex.lock ();
done = true;
cond.signal ();
mutex.unlock ();
}
});
ulong cancellation_handler = 0;
if (cancellable != null) {
cancellation_handler = cancellable.connect (() => {
mutex.lock ();
done = true;
cond.signal ();
mutex.unlock ();
});
}
if (!is_readable ()) {
mutex.lock ();
while (!done)
cond.wait (mutex);
mutex.unlock ();
}
if (cancellation_handler != 0)
cancellable.disconnect (cancellation_handler);
stream.disconnect (io_handler);
cancellable.set_error_if_cancelled ();
}
return stream.read (buffer);
}
public bool can_poll () {
return true;
}
public bool is_readable () {
if (stream == null)
return true;
return (stream.pending_io & IOCondition.IN) != 0;
}
public PollableSource create_source (Cancellable? cancellable) {
return new PollableSource.full (this, new VirtualIOSource (stream, IOCondition.IN), cancellable);
}
public ssize_t read_nonblocking_fn (uint8[] buffer) throws GLib.Error {
if (stream == null)
return 0;
return stream.read (buffer);
}
}
private sealed class VirtualOutputStream : OutputStream, PollableOutputStream {
private weak VirtualStream? stream;
public VirtualOutputStream (VirtualStream stream) {
Object ();
this.stream = stream;
}
internal void detach () {
stream = null;
}
public override bool close (Cancellable? cancellable) throws IOError {
if (stream != null)
stream.shutdown_write ();
return true;
}
public override async bool close_async (int io_priority, Cancellable? cancellable) throws GLib.IOError {
return close (cancellable);
}
public override bool flush (GLib.Cancellable? cancellable) throws GLib.Error {
return true;
}
public override async bool flush_async (int io_priority, GLib.Cancellable? cancellable) throws GLib.Error {
return true;
}
public override ssize_t write (uint8[] buffer, Cancellable? cancellable) throws IOError {
return stream.write (buffer);
}
public bool can_poll () {
return true;
}
public bool is_writable () {
if (stream == null)
return false;
return (stream.pending_io & IOCondition.OUT) != 0;
}
public PollableSource create_source (Cancellable? cancellable) {
return new PollableSource.full (this, new VirtualIOSource (stream, IOCondition.OUT), cancellable);
}
public ssize_t write_nonblocking_fn (uint8[]? buffer) throws GLib.Error {
if (stream == null)
throw new IOError.CLOSED ("Virtual is closed");
return stream.write (buffer);
}
public PollableReturn writev_nonblocking_fn (OutputVector[] vectors, out size_t bytes_written) throws GLib.Error {
assert_not_reached ();
}
}
private class VirtualIOSource : Source {
public VirtualStream? stream;
public IOCondition condition;
public VirtualIOSource (VirtualStream stream, IOCondition condition) {
this.stream = stream;
this.condition = condition;
if (stream != null)
stream.register_source (this, condition);
}
~VirtualIOSource () {
if (stream != null)
stream.unregister_source (this);
}
protected override bool prepare (out int timeout) {
timeout = -1;
return is_ready ();
}
protected override bool check () {
return is_ready ();
}
private bool is_ready () {
IOCondition pending_io = (stream != null) ? stream.pending_io : IOCondition.IN;
return (pending_io & condition) != 0;
}
protected override bool dispatch (SourceFunc? callback) {
set_ready_time (-1);
if (callback == null)
return Source.REMOVE;
return callback ();
}
protected static bool closure_callback (Closure closure) {
var return_value = Value (typeof (bool));
closure.invoke (ref return_value, {});
return return_value.get_boolean ();
}
}
}
+391
View File
@@ -0,0 +1,391 @@
namespace Frida {
public interface ObjectBuilder : Object {
public abstract unowned ObjectBuilder begin_dictionary ();
public abstract unowned ObjectBuilder set_member_name (string name);
public abstract unowned ObjectBuilder end_dictionary ();
public abstract unowned ObjectBuilder begin_array ();
public abstract unowned ObjectBuilder end_array ();
public abstract unowned ObjectBuilder add_null_value ();
public abstract unowned ObjectBuilder add_bool_value (bool val);
public abstract unowned ObjectBuilder add_int64_value (int64 val);
public abstract unowned ObjectBuilder add_uint64_value (uint64 val);
public abstract unowned ObjectBuilder add_data_value (Bytes val);
public abstract unowned ObjectBuilder add_string_value (string val);
public abstract unowned ObjectBuilder add_uuid_value (uint8[] val);
public abstract unowned ObjectBuilder add_raw_value (Bytes val);
public abstract Bytes build ();
}
public interface ObjectReader : Object {
public abstract bool has_member (string name) throws Error;
public abstract unowned ObjectReader read_member (string name) throws Error;
public abstract unowned ObjectReader end_member ();
public abstract uint count_elements () throws Error;
public abstract unowned ObjectReader read_element (uint index) throws Error;
public abstract unowned ObjectReader end_element () throws Error;
public abstract bool get_bool_value () throws Error;
public abstract uint8 get_uint8_value () throws Error;
public abstract uint16 get_uint16_value () throws Error;
public abstract int64 get_int64_value () throws Error;
public abstract uint64 get_uint64_value () throws Error;
public abstract Bytes get_data_value () throws Error;
public abstract unowned string get_string_value () throws Error;
public abstract unowned string get_uuid_value () throws Error;
}
public sealed class VariantReader : Object, ObjectReader {
public Variant root_object {
get {
return scopes.peek_head ().val;
}
}
public Variant current_object {
get {
return scopes.peek_tail ().val;
}
}
private Gee.Deque<Scope> scopes = new Gee.ArrayQueue<Scope> ();
public VariantReader (Variant v) {
push_scope (v);
}
public bool has_member (string name) throws Error {
var scope = peek_scope ();
if (scope.dict == null)
throw new Error.PROTOCOL ("Dictionary expected, but at %s", scope.val.print (true));
return scope.dict.contains (name);
}
public unowned ObjectReader read_member (string name) throws Error {
var scope = peek_scope ();
if (scope.dict == null)
throw new Error.PROTOCOL ("Dictionary expected, but at %s", scope.val.print (true));
Variant? v = scope.dict.lookup_value (name, null);
if (v == null)
throw new Error.PROTOCOL ("Key '%s' not found in dictionary: %s", name, scope.val.print (true));
push_scope (v);
return this;
}
public unowned ObjectReader end_member () {
pop_scope ();
return this;
}
public uint count_elements () throws Error {
var scope = peek_scope ();
scope.check_array ();
return (uint) scope.val.n_children ();
}
public unowned ObjectReader read_element (uint index) throws Error {
var scope = peek_scope ();
scope.check_array ();
push_scope (scope.val.get_child_value (index).get_variant ());
return this;
}
public unowned ObjectReader end_element () throws Error {
pop_scope ();
return this;
}
public bool get_bool_value () throws Error {
return peek_scope ().get_value (VariantType.BOOLEAN).get_boolean ();
}
public uint8 get_uint8_value () throws Error {
return peek_scope ().get_value (VariantType.BYTE).get_byte ();
}
public uint16 get_uint16_value () throws Error {
return peek_scope ().get_value (VariantType.UINT16).get_uint16 ();
}
public int64 get_int64_value () throws Error {
return peek_scope ().get_value (VariantType.INT64).get_int64 ();
}
public uint64 get_uint64_value () throws Error {
return peek_scope ().get_value (VariantType.UINT64).get_uint64 ();
}
public Bytes get_data_value () throws Error {
return peek_scope ().get_value (new VariantType.array (VariantType.BYTE)).get_data_as_bytes ();
}
public unowned string get_string_value () throws Error {
return peek_scope ().get_value (VariantType.STRING).get_string ();
}
public unowned string get_uuid_value () throws Error {
return peek_scope ().get_value (VariantType.STRING).get_string (); // TODO: Use a tuple to avoid ambiguity.
}
private void push_scope (Variant v) {
scopes.offer_tail (new Scope (v));
}
private Scope peek_scope () {
return scopes.peek_tail ();
}
private Scope pop_scope () {
return scopes.poll_tail ();
}
private class Scope {
public Variant val;
public VariantDict? dict;
public bool is_array = false;
public Scope (Variant v) {
val = v;
VariantType t = v.get_type ();
if (t.equal (VariantType.VARDICT))
dict = new VariantDict (v);
else if (t.is_subtype_of (VariantType.ARRAY))
is_array = true;
}
public Variant get_value (VariantType expected_type) throws Error {
if (!val.get_type ().equal (expected_type)) {
throw new Error.PROTOCOL ("Expected type '%s', got '%s'",
(string) expected_type.peek_string (),
(string) val.get_type ().peek_string ());
}
return val;
}
public void check_array () throws Error {
if (!is_array)
throw new Error.PROTOCOL ("Array expected, but at %s", val.print (true));
}
}
}
public sealed class JsonObjectBuilder : Object, ObjectBuilder {
private Json.Builder builder = new Json.Builder ();
private Gee.Map<string, Bytes> raw_values = new Gee.HashMap<string, Bytes> ();
public unowned ObjectBuilder begin_dictionary () {
builder.begin_object ();
return this;
}
public unowned ObjectBuilder set_member_name (string name) {
builder.set_member_name (name);
return this;
}
public unowned ObjectBuilder end_dictionary () {
builder.end_object ();
return this;
}
public unowned ObjectBuilder begin_array () {
builder.begin_array ();
return this;
}
public unowned ObjectBuilder end_array () {
builder.end_array ();
return this;
}
public unowned ObjectBuilder add_null_value () {
builder.add_null_value ();
return this;
}
public unowned ObjectBuilder add_bool_value (bool val) {
builder.add_boolean_value (val);
return this;
}
public unowned ObjectBuilder add_int64_value (int64 val) {
builder.add_int_value (val);
return this;
}
public unowned ObjectBuilder add_uint64_value (uint64 val) {
builder.add_int_value ((int64) val);
return this;
}
public unowned ObjectBuilder add_data_value (Bytes val) {
builder.add_string_value (Base64.encode (val.get_data ()));
return this;
}
public unowned ObjectBuilder add_string_value (string val) {
builder.add_string_value (val);
return this;
}
public unowned ObjectBuilder add_uuid_value (uint8[] val) {
assert_not_reached ();
}
public unowned ObjectBuilder add_raw_value (Bytes val) {
string uuid = Uuid.string_random ();
builder.add_string_value (uuid);
raw_values[uuid] = val;
return this;
}
public Bytes build () {
string json = Json.to_string (builder.get_root (), false);
foreach (var e in raw_values.entries) {
unowned string uuid = e.key;
Bytes val = e.value;
unowned string raw_str = (string) val.get_data ();
string str = raw_str[:(long) val.get_size ()];
json = json.replace ("\"" + uuid + "\"", str);
}
return new Bytes (json.data);
}
}
public sealed class JsonObjectReader : Object, ObjectReader {
private Json.Reader reader;
public JsonObjectReader (string json) throws Error {
try {
reader = new Json.Reader (Json.from_string (json));
} catch (GLib.Error e) {
throw new Error.INVALID_ARGUMENT ("%s", e.message);
}
}
public bool has_member (string name) throws Error {
bool result = reader.read_member (name);
reader.end_member ();
return result;
}
public unowned ObjectReader read_member (string name) throws Error {
if (!reader.read_member (name))
throw_dict_access_error ();
return this;
}
public unowned ObjectReader end_member () {
reader.end_member ();
return this;
}
[NoReturn]
private void throw_dict_access_error () throws Error {
GLib.Error e = reader.get_error ();
reader.end_member ();
throw new Error.PROTOCOL ("%s", e.message);
}
public uint count_elements () throws Error {
int n = reader.count_elements ();
if (n == -1)
throw_array_access_error ();
return n;
}
public unowned ObjectReader read_element (uint index) throws Error {
if (!reader.read_element (index)) {
GLib.Error e = reader.get_error ();
reader.end_element ();
throw new Error.PROTOCOL ("%s", e.message);
}
return this;
}
public unowned ObjectReader end_element () throws Error {
reader.end_element ();
return this;
}
[NoReturn]
private void throw_array_access_error () throws Error {
GLib.Error e = reader.get_error ();
reader.end_element ();
throw new Error.PROTOCOL ("%s", e.message);
}
public bool get_bool_value () throws Error {
bool v = reader.get_boolean_value ();
if (!v)
maybe_throw_value_access_error ();
return v;
}
public uint8 get_uint8_value () throws Error {
int64 v = get_int64_value ();
if (v < 0 || v > uint8.MAX)
throw new Error.PROTOCOL ("Invalid uint8");
return (uint8) v;
}
public uint16 get_uint16_value () throws Error {
int64 v = get_int64_value ();
if (v < 0 || v > uint16.MAX)
throw new Error.PROTOCOL ("Invalid uint16");
return (uint16) v;
}
public int64 get_int64_value () throws Error {
int64 v = reader.get_int_value ();
if (v == 0)
maybe_throw_value_access_error ();
return v;
}
public uint64 get_uint64_value () throws Error {
int64 v = get_int64_value ();
if (v < 0)
throw new Error.PROTOCOL ("Invalid uint64");
return v;
}
public Bytes get_data_value () throws Error {
return new Bytes (Base64.decode (get_string_value ()));
}
public unowned string get_string_value () throws Error {
unowned string? v = reader.get_string_value ();
if (v == null)
maybe_throw_value_access_error ();
return v;
}
public unowned string get_uuid_value () throws Error {
return get_string_value ();
}
private void maybe_throw_value_access_error () throws Error {
GLib.Error? e = reader.get_error ();
if (e == null)
return;
reader.end_member ();
throw new Error.PROTOCOL ("%s", e.message);
}
}
}
+291
View File
@@ -0,0 +1,291 @@
namespace Frida {
public sealed class XpcClient : Object {
public signal void message (Darwin.Xpc.Object obj);
public State state {
get {
return _state;
}
}
public Darwin.Xpc.Connection connection {
get;
construct;
}
public Darwin.GCD.DispatchQueue queue {
get;
construct;
}
private State _state;
private string? close_reason;
private MainContext main_context;
public enum State {
OPEN,
CLOSING,
CLOSED,
}
public static XpcClient make_for_mach_service (string name, Darwin.GCD.DispatchQueue queue) {
return new XpcClient (Darwin.Xpc.Connection.create_mach_service (name, queue, 0), queue);
}
public XpcClient (Darwin.Xpc.Connection connection, Darwin.GCD.DispatchQueue queue) {
Object (connection: connection, queue: queue);
}
construct {
main_context = MainContext.ref_thread_default ();
connection.set_event_handler (on_event);
connection.activate ();
}
public override void dispose () {
if (close_reason != null) {
change_state (CLOSED);
} else {
change_state (CLOSING);
this.ref ();
connection.cancel ();
}
base.dispose ();
}
public async Darwin.Xpc.Object request (Darwin.Xpc.Object message, Cancellable? cancellable) throws Error, IOError {
Darwin.Xpc.Object? reply = null;
connection.send_message_with_reply (message, queue, r => {
schedule_on_frida_thread (() => {
reply = r;
request.callback ();
return Source.REMOVE;
});
});
var cancel_source = new CancellableSource (cancellable);
cancel_source.set_callback (() => {
connection.cancel ();
return Source.REMOVE;
});
cancel_source.attach (main_context);
yield;
cancel_source.destroy ();
if (reply.type == Darwin.Xpc.Error.TYPE) {
var e = (Darwin.Xpc.Error) reply;
throw new Error.NOT_SUPPORTED ("%s", e.get_string (Darwin.Xpc.Error.KEY_DESCRIPTION));
}
return reply;
}
public void post (Darwin.Xpc.Object message) throws Error, IOError {
connection.send_message (message);
}
private void change_state (State new_state) {
_state = new_state;
notify_property ("state");
}
private void on_event (Darwin.Xpc.Object obj) {
schedule_on_frida_thread (() => {
if (obj.type == Darwin.Xpc.Error.TYPE) {
var e = (Darwin.Xpc.Error) obj;
close_reason = e.get_string (Darwin.Xpc.Error.KEY_DESCRIPTION);
switch (state) {
case OPEN:
change_state (CLOSED);
break;
case CLOSING:
change_state (CLOSED);
unref ();
break;
case CLOSED:
assert_not_reached ();
}
} else {
message (obj);
}
return Source.REMOVE;
});
}
private void schedule_on_frida_thread (owned SourceFunc function) {
var source = new IdleSource ();
source.set_callback ((owned) function);
source.attach (main_context);
}
}
public sealed class XpcObjectReader {
public Darwin.Xpc.Object root_object {
get {
return scopes.peek_head ().object;
}
}
public Darwin.Xpc.Object current_object {
get {
return scopes.peek_tail ().object;
}
}
public delegate int TranslateErrorFunc (string domain, int code, string description);
private Gee.Deque<Scope> scopes = new Gee.ArrayQueue<Scope> ();
public XpcObjectReader (Darwin.Xpc.Object obj) {
push_scope (obj);
}
public bool has_member (string name) throws Error {
return peek_scope ().get_dictionary ().get_value (name) != null;
}
public bool try_read_member (string name) throws Error {
var scope = peek_scope ();
var dict = scope.get_dictionary ();
var val = dict.get_value (name);
if (val == null)
return false;
push_scope (val);
return true;
}
public unowned XpcObjectReader read_member (string name) throws Error {
var scope = peek_scope ();
var dict = scope.get_dictionary ();
var val = dict.get_value (name);
if (val == null)
throw new Error.PROTOCOL ("Key '%s' not found in dictionary: %s", name, scope.object.to_string ());
push_scope (val);
return this;
}
public unowned XpcObjectReader end_member () {
pop_scope ();
return this;
}
public size_t count_elements () throws Error {
return peek_scope ().get_array ().count;
}
public unowned XpcObjectReader read_element (size_t index) throws Error {
push_scope (peek_scope ().get_array ().get_value (index));
return this;
}
public unowned XpcObjectReader end_element () throws Error {
pop_scope ();
return this;
}
public bool get_bool_value () throws Error {
return peek_scope ().get_object<Darwin.Xpc.Bool> (Darwin.Xpc.Bool.TYPE).get_value ();
}
public int64 get_int64_value () throws Error {
return peek_scope ().get_object<Darwin.Xpc.Int64> (Darwin.Xpc.Int64.TYPE).get_value ();
}
public uint64 get_uint64_value () throws Error {
return peek_scope ().get_object<Darwin.Xpc.UInt64> (Darwin.Xpc.UInt64.TYPE).get_value ();
}
public unowned uint8[] get_data_value () throws Error {
var data = peek_scope ().get_object<Darwin.Xpc.Data> (Darwin.Xpc.Data.TYPE);
unowned uint8[] buf = (uint8[]) data.get_bytes_ptr ();
buf.length = (int) data.get_length ();
return buf;
}
public unowned string get_string_value () throws Error {
return peek_scope ().get_object<Darwin.Xpc.String> (Darwin.Xpc.String.TYPE).get_string_ptr ();
}
public unowned uint8[] get_uuid_value () throws Error {
return peek_scope ().get_object<Darwin.Xpc.Uuid> (Darwin.Xpc.Uuid.TYPE).get_bytes ()[:16];
}
public unowned string get_error_description () throws Error {
var error = peek_scope ().get_object<Darwin.Xpc.Error> (Darwin.Xpc.Error.TYPE);
return error.get_string (Darwin.Xpc.Error.KEY_DESCRIPTION);
}
public void check_nserror (TranslateErrorFunc translate_error) throws Error {
if (!has_member ("error"))
return;
read_member ("error");
unowned string domain = read_member ("domain").get_string_value ();
end_member ();
var code = (int) read_member ("code").get_int64_value ();
end_member ();
string description = read_member ("userInfo").read_member ("NSLocalizedDescription").get_string_value ();
if (description.has_suffix ("."))
description = description[:description.length - 1];
throw (Error) new GLib.Error.literal (
Quark.from_string ("frida-error-quark"),
translate_error (domain, code, description),
description);
}
public unowned Darwin.Xpc.Object get_object_value (Darwin.Xpc.Type expected_type) throws Error {
return peek_scope ().get_object<Darwin.Xpc.Object> (expected_type);
}
private void push_scope (Darwin.Xpc.Object obj) {
scopes.offer_tail (new Scope (obj));
}
private Scope peek_scope () {
return scopes.peek_tail ();
}
private Scope pop_scope () {
return scopes.poll_tail ();
}
private class Scope {
public Darwin.Xpc.Object object;
private unowned Darwin.Xpc.Type type;
public Scope (Darwin.Xpc.Object obj) {
object = obj;
type = obj.type;
}
public unowned T get_object<T> (Darwin.Xpc.Type expected_type) throws Error {
if (type != expected_type)
throw new Error.PROTOCOL ("Expected type '%s', got '%s'", expected_type.name, type.name);
return object;
}
public unowned Darwin.Xpc.Array get_array () throws Error {
return get_object<Darwin.Xpc.Array> (Darwin.Xpc.Array.TYPE);
}
public unowned Darwin.Xpc.Dictionary get_dictionary () throws Error {
return get_object<Darwin.Xpc.Dictionary> (Darwin.Xpc.Dictionary.TYPE);
}
}
}
}
+95 -27
View File
@@ -1,5 +1,5 @@
namespace Frida.Gadget {
private class Config : Object, Json.Serializable {
private sealed class Config : Object, Json.Serializable {
public Object interaction {
get;
set;
@@ -93,7 +93,7 @@ namespace Frida.Gadget {
}
}
private class ScriptInteraction : Object, Json.Serializable {
private sealed class ScriptInteraction : Object, Json.Serializable {
public string path {
get;
set;
@@ -145,7 +145,7 @@ namespace Frida.Gadget {
}
}
private class ScriptDirectoryInteraction : Object {
private sealed class ScriptDirectoryInteraction : Object {
public string path {
get;
set;
@@ -164,7 +164,7 @@ namespace Frida.Gadget {
}
}
private class ScriptConfig : Object, Json.Serializable {
private sealed class ScriptConfig : Object, Json.Serializable {
public ProcessFilter? filter {
get;
set;
@@ -216,7 +216,7 @@ namespace Frida.Gadget {
}
}
private class ProcessFilter : Object {
private sealed class ProcessFilter : Object {
public string[] executables {
get;
set;
@@ -258,7 +258,7 @@ namespace Frida.Gadget {
}
}
private class ListenInteraction : SocketInteraction {
private sealed class ListenInteraction : SocketInteraction {
public PortConflictBehavior on_port_conflict {
get;
set;
@@ -287,7 +287,7 @@ namespace Frida.Gadget {
}
}
private class ConnectInteraction : SocketInteraction, Json.Serializable {
private sealed class ConnectInteraction : SocketInteraction, Json.Serializable {
public string[]? acl {
get;
set;
@@ -328,7 +328,7 @@ namespace Frida.Gadget {
}
}
private class Location : Object {
private sealed class Location : Object {
public string executable_name {
get;
construct;
@@ -751,7 +751,7 @@ namespace Frida.Gadget {
string config_data;
try {
FileUtils.get_contents (config_path, out config_data);
load_asset_text (config_path, out config_data);
} catch (FileError e) {
if (e is FileError.NOENT)
return new Config ();
@@ -988,7 +988,7 @@ namespace Frida.Gadget {
}
}
private class ScriptRunner : BaseController {
private sealed class ScriptRunner : BaseController {
private ScriptEngine engine;
private Script script;
@@ -1036,7 +1036,7 @@ namespace Frida.Gadget {
}
}
private class ScriptDirectoryRunner : BaseController {
private sealed class ScriptDirectoryRunner : BaseController {
public string directory_path {
get;
construct;
@@ -1226,7 +1226,7 @@ namespace Frida.Gadget {
private ScriptConfig load_config (string path) throws Error {
string data;
try {
FileUtils.get_contents (path, out data);
load_asset_text (path, out data);
} catch (FileError e) {
if (e is FileError.NOENT)
return new ScriptConfig ();
@@ -1241,8 +1241,14 @@ namespace Frida.Gadget {
}
}
private class Script : Object, RpcPeer {
private const uint8 QUICKJS_BYTECODE_MAGIC = 0x02;
private sealed class Script : Object, RpcPeer {
private const uint8 QUICKJS_BYTECODE_MAGIC =
#if BIG_ENDIAN
0x42
#else
0x02
#endif
;
public enum ChangeBehavior {
IGNORE,
@@ -1349,9 +1355,9 @@ namespace Frida.Gadget {
try {
var path = this.path;
uint8[] contents;
Bytes contents;
try {
FileUtils.get_data (path, out contents);
load_asset_bytes (path, out contents);
} catch (FileError e) {
throw new Error.INVALID_ARGUMENT ("%s", e.message);
}
@@ -1360,11 +1366,10 @@ namespace Frida.Gadget {
options.name = Path.get_basename (path).split (".", 2)[0];
ScriptEngine.ScriptInstance instance;
if (contents.length > 0 && contents[0] == QUICKJS_BYTECODE_MAGIC) {
instance = yield engine.create_script (null, new Bytes (contents), options);
} else {
instance = yield engine.create_script ((string) contents, null, options);
}
if (contents.length > 0 && contents[0] == QUICKJS_BYTECODE_MAGIC)
instance = yield engine.create_script (null, contents, options);
else
instance = yield engine.create_script ((string) contents.get_data (), null, options);
if (id.handle != 0)
yield engine.destroy_script (id);
@@ -1381,7 +1386,7 @@ namespace Frida.Gadget {
var stage = new Json.Node.alloc ().init_string ((peek_state () == State.CREATED) ? "early" : "late");
try {
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, null);
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, null, null);
} catch (GLib.Error e) {
}
}
@@ -1449,12 +1454,12 @@ namespace Frida.Gadget {
return true;
}
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
engine.post_to_script (id, json);
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
engine.post_to_script (id, json, data);
}
}
private class ControlServer : BaseController {
private sealed class ControlServer : BaseController {
public EndpointParameters endpoint_params {
get;
construct;
@@ -1497,7 +1502,8 @@ namespace Frida.Gadget {
var endpoint_params = new EndpointParameters (interaction.address, interaction.port,
parse_certificate (interaction.certificate, location), interaction.origin, auth_service, asset_root);
service = new WebService (endpoint_params, CONTROL, interaction.on_port_conflict);
service = new WebService (endpoint_params, WebServiceFlavor.CONTROL, interaction.on_port_conflict,
new TunnelInterfaceObserver ());
service.incoming.connect (on_incoming_connection);
yield service.start (io_cancellable);
}
@@ -1927,6 +1933,14 @@ namespace Frida.Gadget {
throw new Error.NOT_SUPPORTED ("Unable to inject libraries when embedded");
}
public async ChannelId open_channel (string address, Cancellable? cancellable) throws Error, IOError {
throw new Error.NOT_SUPPORTED ("Unable to open channels when embedded");
}
public async ServiceSessionId open_service (string address, Cancellable? cancellable) throws Error, IOError {
throw new Error.NOT_SUPPORTED ("Unable to open services when embedded");
}
private void validate_pid (uint pid) throws Error {
if (pid != this_process.pid)
throw new Error.NOT_SUPPORTED ("Unable to act on other processes when embedded");
@@ -1958,7 +1972,7 @@ namespace Frida.Gadget {
}
}
private class ClusterClient : BaseController {
private sealed class ClusterClient : BaseController {
public SocketConnectable connectable {
get;
construct;
@@ -2075,6 +2089,60 @@ namespace Frida.Gadget {
}
#endif
private void load_asset_text (string filename, out string text) throws FileError {
Bytes raw_contents;
load_asset_bytes (filename, out raw_contents);
unowned string str = (string) raw_contents.get_data ();
if (!str.validate ())
throw new FileError.FAILED ("%s: invalid UTF-8", filename);
text = str;
}
private void load_asset_bytes (string filename, out Bytes bytes) throws FileError {
#if ANDROID
if (maybe_load_asset_bytes_from_apk (filename, out bytes))
return;
#endif
uint8[] data;
FileUtils.get_data (filename, out data);
bytes = new Bytes.take ((owned) data);
}
#if ANDROID
private bool maybe_load_asset_bytes_from_apk (string filename, out Bytes contents) throws FileError {
contents = null;
var tokens = filename.split ("!", 2);
if (tokens.length != 2 || !tokens[0].has_suffix (".apk"))
return false;
unowned string apk_path = tokens[0];
unowned string file_path = tokens[1];
var reader = Minizip.Reader.create ();
try {
if (reader.open_file (apk_path) != OK)
throw new FileError.FAILED ("Unable to open APK");
if (reader.locate_entry (file_path[1:], true) != OK)
throw new FileError.FAILED ("Unable to locate %s inside APK", file_path);
var size = reader.entry_save_buffer_length ();
var data = new uint8[size + 1];
if (reader.entry_save_buffer (data[:size]) != OK)
throw new FileError.FAILED ("Unable to extract %s from APK", file_path);
contents = new Bytes.take ((owned) data);
return true;
} finally {
reader.close ();
Minizip.Reader.destroy (ref reader);
}
}
#endif
private Json.Node make_empty_json_object () {
return new Json.Node.alloc ().init_object (new Json.Object ());
}
+6 -1
View File
@@ -29,6 +29,11 @@ if host_os_family == 'darwin'
extra_link_args += '-Wl,-framework,Foundation'
endif
if host_os == 'android'
extra_vala_args += '--pkg=minizip'
platform_deps += minizip_dep
endif
if host_os_family == 'windows'
if host_toolchain != 'microsoft'
symfile = 'frida-gadget.symbols'
@@ -60,7 +65,7 @@ raw_gadget = shared_library('frida-gadget-raw', gadget_sources,
link_depends: extra_link_depends,
vs_module_defs: 'frida-gadget.def',
override_options: ['b_asneeded=true'],
dependencies: [gio_dep, gee_dep, json_glib_dep, gum_dep, gumjs_dep, base_dep, tls_provider_dep, payload_dep] + platform_deps,
dependencies: [gio_dep, gee_dep, json_glib_dep, gum_dep, gumjs_dep, base_dep, netif_dep, tls_provider_dep, payload_dep] + platform_deps,
)
operations = [
+1
View File
@@ -2,6 +2,7 @@ if host_os == 'android'
subdir('selinux')
endif
subdir('base')
subdir('netif')
subdir('pipe')
subdir('payload')
if have_local_backend
+28
View File
@@ -0,0 +1,28 @@
netif_sources = [
'tunnel-interface-observer.vala',
]
extra_vala_args = []
extra_link_args = []
if host_os in ['ios', 'tvos']
extra_vala_args += [
'--pkg=corefoundation',
'--pkg=darwin-gcd',
'--pkg=darwin-systemconfiguration',
]
extra_link_args += '-Wl,-framework,SystemConfiguration'
endif
netif = static_library('frida-netif', netif_sources,
c_args: frida_component_cflags,
vala_args: [base_vala_args, extra_vala_args],
dependencies: [base_dep, gee_dep],
)
netif_dep = declare_dependency(
include_directories: include_directories('.'),
link_args: extra_link_args,
link_with: netif,
dependencies: base_dep,
)
+99
View File
@@ -0,0 +1,99 @@
public sealed class Frida.TunnelInterfaceObserver : Object, DynamicInterfaceObserver {
#if IOS || TVOS
private Gee.Map<string, DynamicInterface> interfaces = new Gee.HashMap<string, DynamicInterface> ();
private Darwin.SystemConfiguration.DynamicStore? store;
private Darwin.GCD.DispatchQueue event_queue =
new Darwin.GCD.DispatchQueue ("re.frida.endpoint-enumerator", Darwin.GCD.DispatchQueueAttr.SERIAL);
private MainContext? main_context;
public override void dispose () {
if (store != null) {
store.set_dispatch_queue (null);
store = null;
ref ();
event_queue.dispatch_async (do_dispose);
}
base.dispose ();
}
private void do_dispose () {
unref ();
}
public void start () {
main_context = MainContext.ref_thread_default ();
Darwin.SystemConfiguration.DynamicStoreContext context = { 0, };
context.info = this;
store = new Darwin.SystemConfiguration.DynamicStore (null, CoreFoundation.String.make ("Frida"),
on_interfaces_changed_wrapper, context);
var pattern = CoreFoundation.String.make ("State:/Network/Interface/utun.*/IPv6");
var patterns = new CoreFoundation.Array (null, ((CoreFoundation.Type[]) &pattern)[:1]);
store.set_notification_keys (null, patterns);
store.set_dispatch_queue (event_queue);
var initial_keys = store.copy_key_list (pattern);
if (initial_keys != null)
handle_interface_changes (initial_keys);
}
private static void on_interfaces_changed_wrapper (Darwin.SystemConfiguration.DynamicStore store,
CoreFoundation.Array changed_keys, void * info) {
unowned TunnelInterfaceObserver enumerator = (TunnelInterfaceObserver) info;
enumerator.on_interfaces_changed (changed_keys);
}
private void on_interfaces_changed (CoreFoundation.Array changed_keys) {
schedule_on_frida_thread (() => {
if (store != null)
handle_interface_changes (changed_keys);
return Source.REMOVE;
});
}
private void handle_interface_changes (CoreFoundation.Array changed_keys) {
var addresses_str = CoreFoundation.String.make ("Addresses");
foreach (var key in CFArray.wrap<CoreFoundation.String> (changed_keys)) {
string name = key.to_string ().split ("/")[3];
var val = (CoreFoundation.Dictionary) store.copy_value (key);
if (val != null) {
InetAddress? address = null;
foreach (var raw_address in CFArray.wrap<CoreFoundation.String> (val[addresses_str])) {
var str = raw_address.to_string ();
bool is_reserved_ipv6_range = str.has_prefix ("fc") || str.has_prefix ("fd");
bool is_tunnel = is_reserved_ipv6_range && str.has_suffix ("::1");
if (is_tunnel) {
address = new InetAddress.from_string (str);
break;
}
}
if (address != null && !interfaces.has_key (name)) {
var iface = new DynamicInterface (name, address);
interfaces[name] = iface;
interface_attached (iface);
}
} else {
DynamicInterface iface;
if (interfaces.unset (name, out iface))
interface_detached (iface);
}
}
}
private void schedule_on_frida_thread (owned SourceFunc function) {
var source = new IdleSource ();
source.set_callback ((owned) function);
source.attach (main_context);
}
#else
public void start () {
}
#endif
}
+27 -24
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class ThreadIgnoreScope {
public sealed class ThreadIgnoreScope {
public enum Kind {
APPLICATION_THREAD,
FRIDA_THREAD
@@ -43,7 +43,7 @@ namespace Frida {
}
#if ANDROID
public class ThreadCountCloaker : Object {
public sealed class ThreadCountCloaker : Object {
private ReadFunc * read_slot;
private static ReadFunc old_read_impl;
@@ -53,15 +53,18 @@ namespace Frida {
private delegate ssize_t ReadFunc (int fd, void * buf, size_t count);
construct {
Gum.Module.enumerate_imports ("libart.so", imp => {
if (imp.name == "read") {
read_slot = (ReadFunc *) imp.slot;
return false;
}
return true;
});
if (read_slot != null)
old_read_impl = update_read_slot (on_read);
var art = Gum.Process.find_module_by_name ("libart.so");
if (art != null) {
art.enumerate_imports (imp => {
if (imp.name == "read") {
read_slot = (ReadFunc *) imp.slot;
return false;
}
return true;
});
if (read_slot != null)
old_read_impl = update_read_slot (on_read);
}
}
~ThreadCountCloaker () {
@@ -153,12 +156,12 @@ namespace Frida {
}
}
#else
public class ThreadCountCloaker : Object {
public sealed class ThreadCountCloaker : Object {
}
#endif
#if LINUX
public class ThreadListCloaker : Object, DirListFilter {
public sealed class ThreadListCloaker : Object, DirListFilter {
private string our_dir_by_pid;
private DirListCloaker cloaker;
@@ -177,7 +180,7 @@ namespace Frida {
}
}
public class FDListCloaker : Object, DirListFilter {
public sealed class FDListCloaker : Object, DirListFilter {
private string our_dir_by_pid;
private DirListCloaker cloaker;
@@ -196,7 +199,7 @@ namespace Frida {
}
}
private class DirListCloaker : Object {
private sealed class DirListCloaker : Object {
public weak DirListFilter filter {
get;
construct;
@@ -212,34 +215,34 @@ namespace Frida {
construct {
var interceptor = Gum.Interceptor.obtain ();
unowned string libc = Gum.Process.query_libc_name ();
var libc = Gum.Process.get_libc_module ();
var open_listener = new OpenDirListener (this);
listeners.add (open_listener);
interceptor.attach ((void *) Gum.Module.find_export_by_name (libc, "opendir"), open_listener);
interceptor.attach ((void *) libc.find_export_by_name ("opendir"), open_listener);
var close_listener = new CloseDirListener (this);
listeners.add (close_listener);
interceptor.attach ((void *) Gum.Module.find_export_by_name (libc, "closedir"), close_listener);
interceptor.attach ((void *) libc.find_export_by_name ("closedir"), close_listener);
var readdir_impl = Gum.Module.find_export_by_name (libc, "readdir");
var readdir_impl = libc.find_export_by_name ("readdir");
var readdir_listener = new ReadDirListener (this, LEGACY);
listeners.add (readdir_listener);
interceptor.attach ((void *) readdir_impl, readdir_listener);
var readdir64_impl = Gum.Module.find_export_by_name (libc, "readdir64");
var readdir64_impl = libc.find_export_by_name ("readdir64");
if (readdir64_impl != 0 && readdir64_impl != readdir_impl) {
var listener = new ReadDirListener (this, MODERN);
listeners.add (listener);
interceptor.attach ((void *) readdir64_impl, listener);
}
var readdir_r_impl = Gum.Module.find_export_by_name (libc, "readdir_r");
var readdir_r_impl = libc.find_export_by_name ("readdir_r");
var readdir_r_listener = new ReadDirRListener (this, LEGACY);
listeners.add (readdir_r_listener);
interceptor.attach ((void *) readdir_r_impl, readdir_r_listener);
var readdir64_r_impl = Gum.Module.find_export_by_name (libc, "readdir64_r");
var readdir64_r_impl = libc.find_export_by_name ("readdir64_r");
if (readdir64_r_impl != 0 && readdir64_r_impl != readdir_r_impl) {
var listener = new ReadDirRListener (this, MODERN);
listeners.add (listener);
@@ -464,10 +467,10 @@ namespace Frida {
public abstract bool matches_file (string name);
}
#else
public class ThreadListCloaker : Object {
public sealed class ThreadListCloaker : Object {
}
public class FDListCloaker : Object {
public sealed class FDListCloaker : Object {
}
#endif
}
+5 -4
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class ExitMonitor : Object, Gum.InvocationListener {
public sealed class ExitMonitor : Object, Gum.InvocationListener {
public weak ExitHandler handler {
get;
construct;
@@ -32,16 +32,17 @@ namespace Frida {
unowned Gum.InvocationListener listener = this;
#if WINDOWS
interceptor.attach ((void *) Gum.Module.find_export_by_name ("kernel32.dll", "ExitProcess"), listener);
interceptor.attach ((void *) Gum.Process.find_module_by_name ("kernel32.dll").find_export_by_name ("ExitProcess"),
listener);
#else
unowned string libc = Gum.Process.query_libc_name ();
var libc = Gum.Process.get_libc_module ();
const string[] apis = {
"exit",
"_exit",
"abort",
};
foreach (var symbol in apis) {
interceptor.attach ((void *) Gum.Module.find_export_by_name (libc, symbol), listener);
interceptor.attach ((void *) libc.find_export_by_name (symbol), listener);
}
#endif
}
+3 -3
View File
@@ -1,6 +1,6 @@
namespace Frida {
#if WINDOWS
public class FileDescriptorGuard : Object {
public sealed class FileDescriptorGuard : Object {
public Gum.MemoryRange agent_range {
get;
construct;
@@ -11,7 +11,7 @@ namespace Frida {
}
}
#else
public class FileDescriptorGuard : Object {
public sealed class FileDescriptorGuard : Object {
public Gum.MemoryRange agent_range {
get;
construct;
@@ -26,7 +26,7 @@ namespace Frida {
construct {
var interceptor = Gum.Interceptor.obtain ();
var close = Gum.Module.find_export_by_name (Gum.Process.query_libc_name (), "close");
var close = Gum.Process.get_libc_module ().find_export_by_name ("close");
close_listener = new CloseListener (this);
interceptor.attach ((void *) close, close_listener);
}
+2 -2
View File
@@ -1,6 +1,6 @@
namespace Frida {
#if WINDOWS
public class FileDescriptorTablePadder {
public sealed class FileDescriptorTablePadder {
public static FileDescriptorTablePadder obtain () {
return new FileDescriptorTablePadder ();
}
@@ -9,7 +9,7 @@ namespace Frida {
}
}
#else
public class FileDescriptorTablePadder {
public sealed class FileDescriptorTablePadder {
private const int MIN_TABLE_SIZE = 32;
private static unowned FileDescriptorTablePadder shared_instance = null;
+18 -12
View File
@@ -1,6 +1,6 @@
namespace Frida {
#if WINDOWS
public class ForkMonitor : Object {
public sealed class ForkMonitor : Object {
public weak ForkHandler handler {
get;
construct;
@@ -11,7 +11,7 @@ namespace Frida {
}
}
#else
public class ForkMonitor : Object, Gum.InvocationListener {
public sealed class ForkMonitor : Object, Gum.InvocationListener {
public weak ForkHandler handler {
get;
construct;
@@ -45,9 +45,9 @@ namespace Frida {
}
static construct {
unowned string libc = Gum.Process.query_libc_name ();
fork_impl = (void *) Gum.Module.find_export_by_name (libc, "fork");
vfork_impl = (void *) Gum.Module.find_export_by_name (libc, "vfork");
var libc = Gum.Process.get_libc_module ();
fork_impl = (void *) libc.find_export_by_name ("fork");
vfork_impl = (void *) libc.find_export_by_name ("vfork");
}
construct {
@@ -61,15 +61,21 @@ namespace Frida {
string cmdline;
FileUtils.get_contents ("/proc/self/cmdline", out cmdline);
if (cmdline == "zygote" || cmdline == "zygote64" || cmdline == "usap32" || cmdline == "usap64") {
var set_argv0 = (void *) Gum.Module.find_export_by_name ("libandroid_runtime.so", "_Z27android_os_Process_setArgV0P7_JNIEnvP8_jobjectP8_jstring");
if (set_argv0 != null) {
interceptor.attach (set_argv0, listener, (void *) HookId.SET_ARGV0);
child_recovery_behavior = DEFERRED_UNTIL_SET_ARGV0;
var runtime = Gum.Process.find_module_by_name ("libandroid_runtime.so");
if (runtime != null) {
var set_argv0 = (void *) runtime.find_export_by_name ("_Z27android_os_Process_setArgV0P7_JNIEnvP8_jobjectP8_jstring");
if (set_argv0 != null) {
interceptor.attach (set_argv0, listener, (void *) HookId.SET_ARGV0);
child_recovery_behavior = DEFERRED_UNTIL_SET_ARGV0;
}
}
var setcontext = (void *) Gum.Module.find_export_by_name ("libselinux.so", "selinux_android_setcontext");
if (setcontext != null)
interceptor.attach (setcontext, listener, (void *) HookId.SET_CTX);
var selinux = Gum.Process.find_module_by_name ("libselinux.so");
if (selinux != null) {
var setcontext = (void *) selinux.find_export_by_name ("selinux_android_setcontext");
if (setcontext != null)
interceptor.attach (setcontext, listener, (void *) HookId.SET_CTX);
}
}
} catch (FileError e) {
}
+18
View File
@@ -25,6 +25,24 @@ frida_run_atexit_handlers (void)
{
}
# ifdef HAVE_ASAN
__attribute__ ((constructor)) static void
frida_init_memory (void)
{
asm volatile ("");
}
# ifndef HAVE_DARWIN
__attribute__ ((destructor)) static void
frida_deinit_memory (void)
{
asm volatile ("");
}
# endif
# endif
#else
#define FRIDA_SHIM_LOCK() gum_spinlock_acquire (&frida_shim_lock)
+1 -1
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class PortalClient : Object, AgentSessionProvider {
public sealed class PortalClient : Object, AgentSessionProvider {
public signal void resume ();
public signal void kill ();
+5 -5
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class ScriptEngine : Object {
public sealed class ScriptEngine : Object {
public signal void message_from_script (AgentScriptId script_id, string json, Bytes? data);
public signal void message_from_debugger (AgentScriptId script_id, string message);
@@ -223,7 +223,7 @@ namespace Frida {
source.attach (Gum.ScriptBackend.get_scheduler ().get_js_context ());
}
public class ScriptInstance : Object, RpcPeer {
public sealed class ScriptInstance : Object, RpcPeer {
public signal void closed ();
public signal void message (string json, Bytes? data);
public signal void debug_message (string message);
@@ -420,7 +420,7 @@ namespace Frida {
var reason_value = new Json.Node.alloc ().init_string (reason.to_nick ());
try {
yield rpc_client.call ("dispose", new Json.Node[] { reason_value }, null);
yield rpc_client.call ("dispose", new Json.Node[] { reason_value }, null, null);
} catch (GLib.Error e) {
}
@@ -467,10 +467,10 @@ namespace Frida {
this.debug_message (message);
}
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
if (script == null)
throw new Error.INVALID_OPERATION ("Script is destroyed");
script.post (json);
script.post (json, data);
}
}
}
+16 -13
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class SpawnMonitor : Object, Gum.InvocationListener {
public sealed class SpawnMonitor : Object, Gum.InvocationListener {
public weak SpawnHandler handler {
get;
construct;
@@ -38,21 +38,24 @@ namespace Frida {
var interceptor = Gum.Interceptor.obtain ();
#if WINDOWS
var create_process_internal = Gum.Module.find_export_by_name ("kernelbase.dll", "CreateProcessInternalW");
if (create_process_internal == 0)
create_process_internal = Gum.Module.find_export_by_name ("kernel32.dll", "CreateProcessInternalW");
var kernelbase = Gum.Process.find_module_by_name ("kernelbase.dll");
var create_process_internal = (kernelbase != null) ? kernelbase.find_export_by_name ("CreateProcessInternalW") : 0;
if (create_process_internal == 0) {
create_process_internal = Gum.Process.find_module_by_name ("kernel32.dll")
.find_export_by_name ("CreateProcessInternalW");
}
assert (create_process_internal != 0);
interceptor.attach ((void *) create_process_internal, this);
#else
unowned string libc = Gum.Process.query_libc_name ();
var libc = Gum.Process.get_libc_module ();
#if DARWIN
posix_spawn = (PosixSpawnFunc) Gum.Module.find_export_by_name (libc, "posix_spawn");
posix_spawnattr_init = (PosixSpawnAttrInitFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_init");
posix_spawnattr_destroy = (PosixSpawnAttrDestroyFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_destroy");
posix_spawnattr_getflags = (PosixSpawnAttrSetFlagsFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_getflags");
posix_spawnattr_setflags = (PosixSpawnAttrSetFlagsFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_setflags");
posix_spawn = (PosixSpawnFunc) libc.find_export_by_name ("posix_spawn");
posix_spawnattr_init = (PosixSpawnAttrInitFunc) libc.find_export_by_name ("posix_spawnattr_init");
posix_spawnattr_destroy = (PosixSpawnAttrDestroyFunc) libc.find_export_by_name ("posix_spawnattr_destroy");
posix_spawnattr_getflags = (PosixSpawnAttrSetFlagsFunc) libc.find_export_by_name ("posix_spawnattr_getflags");
posix_spawnattr_setflags = (PosixSpawnAttrSetFlagsFunc) libc.find_export_by_name ("posix_spawnattr_setflags");
execve = (void *) Gum.Module.find_export_by_name (libc, "execve");
execve = (void *) libc.find_export_by_name ("execve");
interceptor.attach ((void *) posix_spawn, this);
@@ -60,10 +63,10 @@ namespace Frida {
#else
Gum.Address execve = 0;
#if ANDROID
execve = Gum.Module.find_symbol_by_name (libc, "__execve");
execve = libc.find_symbol_by_name ("__execve");
#endif
if (execve == 0)
execve = Gum.Module.find_export_by_name (libc, "execve");
execve = libc.find_export_by_name ("execve");
interceptor.attach ((void *) execve, this);
#endif
#endif
+6 -5
View File
@@ -1,6 +1,6 @@
namespace Frida {
#if DARWIN
public class ThreadSuspendMonitor : Object {
public sealed class ThreadSuspendMonitor : Object {
public weak ProcessInvader invader {
get;
construct;
@@ -26,9 +26,10 @@ namespace Frida {
construct {
var interceptor = Gum.Interceptor.obtain ();
task_threads = (TaskThreadsFunc) Gum.Module.find_export_by_name (LIBSYSTEM_KERNEL, "task_threads");
thread_suspend = (ThreadSuspendFunc) Gum.Module.find_export_by_name (LIBSYSTEM_KERNEL, "thread_suspend");
thread_resume = (ThreadResumeFunc) Gum.Module.find_export_by_name (LIBSYSTEM_KERNEL, "thread_resume");
var kernel = Gum.Process.find_module_by_name (LIBSYSTEM_KERNEL);
task_threads = (TaskThreadsFunc) kernel.find_export_by_name ("task_threads");
thread_suspend = (ThreadSuspendFunc) kernel.find_export_by_name ("thread_suspend");
thread_resume = (ThreadResumeFunc) kernel.find_export_by_name ("thread_resume");
interceptor.replace ((void *) task_threads, (void *) replacement_task_threads, this);
interceptor.replace ((void *) thread_suspend, (void *) replacement_thread_suspend, this);
@@ -130,7 +131,7 @@ namespace Frida {
}
}
#else
public class ThreadSuspendMonitor : Object {
public sealed class ThreadSuspendMonitor : Object {
public weak ProcessInvader invader {
get;
construct;
+19 -11
View File
@@ -55,6 +55,7 @@ struct _FridaUnwindHookState
gpointer set_info_original;
void (* set_info) (gpointer cursor, gint is_return_address);
gpointer (* get_reg) (gpointer cursor, gint reg);
GumInterceptor * interceptor;
};
#if __has_feature (ptrauth_calls)
@@ -97,7 +98,6 @@ _frida_unwind_sitter_hook_libunwind (void)
#if GLIB_SIZEOF_VOID_P == 8
gpointer * set_info_slot;
gpointer get_reg_impl;
GumInterceptor * interceptor;
if (state != NULL)
return;
@@ -121,8 +121,9 @@ _frida_unwind_sitter_hook_libunwind (void)
state->set_info = FRIDA_RESIGN_PTR (state->set_info_original);
state->get_reg = FRIDA_RESIGN_PTR (get_reg_impl);
interceptor = gum_interceptor_obtain ();
if (gum_interceptor_replace (interceptor, state->set_info_original, frida_unwind_cursor_set_info_replacement, NULL, NULL)
state->interceptor = gum_interceptor_obtain ();
if (gum_interceptor_replace (state->interceptor, state->set_info_original, frida_unwind_cursor_set_info_replacement, NULL, NULL)
!= GUM_REPLACE_OK)
goto unsupported_version;
@@ -137,13 +138,12 @@ unsupported_version:
void
_frida_unwind_sitter_unhook_libunwind (void)
{
GumInterceptor * interceptor;
if (state == NULL)
return;
interceptor = gum_interceptor_obtain ();
gum_interceptor_revert (interceptor, state->set_info_original);
gum_interceptor_revert (state->interceptor, state->set_info_original);
g_object_unref (state->interceptor);
g_slice_free (FridaUnwindHookState, state);
state = NULL;
@@ -300,6 +300,7 @@ static gpointer
frida_find_vtable (void)
{
GumAddress result = 0;
GumModule * libunwind;
GumAddress export;
uint64_t address;
G_GNUC_UNUSED cs_err err;
@@ -309,11 +310,15 @@ frida_find_vtable (void)
size_t size;
const size_t max_size = 2048;
export = gum_module_find_export_by_name (FRIDA_LIBUNWIND_PATH, "unw_init_local");
libunwind = gum_process_find_module_by_name (FRIDA_LIBUNWIND_PATH);
if (libunwind == NULL)
goto beach;
export = gum_module_find_export_by_name (libunwind, "unw_init_local");
if (export == 0)
export = gum_module_find_export_by_name (FRIDA_LIBUNWIND_PATH, "_Unwind_RaiseException");
export = gum_module_find_export_by_name (libunwind, "_Unwind_RaiseException");
if (export == 0)
return NULL;
goto beach;
export = gum_strip_code_address (export);
address = export;
@@ -340,7 +345,7 @@ frida_find_vtable (void)
GumMemoryRange bss_range;
bss_range.base_address = 0;
gum_module_enumerate_sections (FRIDA_LIBUNWIND_PATH, (GumFoundSectionFunc) frida_find_bss_range, &bss_range);
gum_module_enumerate_sections (libunwind, (GumFoundSectionFunc) frida_find_bss_range, &bss_range);
while (cs_disasm_iter (capstone, &code, &size, &address, insn))
{
@@ -404,6 +409,9 @@ frida_find_vtable (void)
cs_free (insn, 1);
cs_close (&capstone);
beach:
g_clear_object (&libunwind);
return GSIZE_TO_POINTER (result);
}
+3 -3
View File
@@ -1,6 +1,6 @@
namespace Frida {
#if DARWIN
public class UnwindSitter : Object {
public sealed class UnwindSitter : Object {
public weak ProcessInvader invader {
get;
construct;
@@ -21,7 +21,7 @@ namespace Frida {
var interceptor = Gum.Interceptor.obtain ();
dyld_find_unwind_sections = (DyldFindUnwindSectionsFunc)
Gum.Module.find_export_by_name (LIBDYLD, "_dyld_find_unwind_sections");
Gum.Process.find_module_by_name (LIBDYLD).find_export_by_name ("_dyld_find_unwind_sections");
interceptor.replace ((void *) dyld_find_unwind_sections, (void *) replacement_dyld_find_unwind_sections, this);
@@ -62,7 +62,7 @@ namespace Frida {
public extern static void _unhook_libunwind ();
}
#else
public class UnwindSitter : Object {
public sealed class UnwindSitter : Object {
public weak ProcessInvader invader {
get;
construct;
+2 -2
View File
@@ -1,7 +1,7 @@
#include "pipe-glue.h"
#include "frida-tvos.h"
#include "pipe-glue.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
+2 -2
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class PipeTransport : Object {
public sealed class PipeTransport : Object {
public string local_address {
get;
construct;
@@ -42,7 +42,7 @@ namespace Frida {
}
#if WINDOWS
public class WindowsPipe : IOStream {
public sealed class WindowsPipe : IOStream {
public string address {
get;
construct;
+211 -75
View File
@@ -6,13 +6,17 @@ project('frida-core', 'vala', 'c', 'cpp',
default_options: ['c_std=gnu99,c99', 'cpp_std=c++17'],
)
fs = import('fs')
if not meson.get_compiler('vala').version().endswith('-frida')
error('''Incompatible Vala compiler detected.
Frida currently relies on features not yet upstream. Grab the Frida-optimized
Vala compiler from:
Vala sources from:
https://github.com/frida/vala''')
https://github.com/frida/vala
and compile them with Meson.''')
endif
c_languages = ['c', 'cpp']
@@ -20,7 +24,7 @@ cc = meson.get_compiler('c')
cpp = meson.get_compiler('cpp')
releng = meson.global_source_root() / 'releng'
if not import('fs').exists(releng)
if not fs.exists(releng)
releng = meson.project_source_root() / 'releng'
endif
@@ -92,11 +96,12 @@ else
host_arch = host_machine.cpu_family()
host_abi = host_arch
endif
gumjs_archs = {
'x86': 'ia32',
'x86_64': 'x64',
}
host_arch_gumjs = gumjs_archs.get(host_arch, host_arch)
if cc.sizeof('void *') == 8
host_cpu_mode = '64'
else
host_cpu_mode = '32'
endif
host_docks_mobile_devices = host_os in ['windows', 'macos', 'linux'] and host_cpu_mode == '64'
if host_os_family == 'darwin'
c_languages += ['objc', 'objcpp']
@@ -156,10 +161,12 @@ if host_os_family == 'darwin'
endif
endif
if cc.sizeof('void *') == 8
host_cpu_mode = '64'
else
host_cpu_mode = '32'
if host_machine.endian() == 'big'
if host_abi in ['arm', 'armhf']
host_abi = 'armbe8'
elif host_abi == 'arm64'
host_abi = 'arm64be'
endif
endif
if host_os_family == 'darwin' and host_arch == 'arm64'
@@ -264,12 +271,14 @@ if host_os == 'linux'
#endif
'''
if cc.compiles(glibc_src, name: 'compiling for glibc')
cdata.set('HAVE_GLIBC', 1)
libc = 'glibc'
elif cc.compiles(uclibc_src, name: 'compiling for uClibc')
cdata.set('HAVE_UCLIBC', 1)
libc = 'uclibc'
else
cdata.set('HAVE_MUSL', 1)
libc = 'musl'
endif
cdata.set('HAVE_' + libc.to_upper(), 1)
vala_flags += '--define=' + libc.to_upper()
endif
if get_option('b_sanitize') == 'address'
@@ -347,15 +356,112 @@ else
gio_unix_dep = dependency('gio-unix-2.0')
endif
if host_os == 'android'
minizip_dep = dependency('minizip', required: false, default_options: [
'zlib=enabled',
'lzma=disabled',
])
endif
if host_toolchain == 'microsoft'
lib = find_program('lib')
ar = ''
nm = ''
ranlib = ''
strip = ''
else
lib = ''
ar = find_program('ar')
nm = find_program('nm')
ranlib = find_program('ranlib')
strip = find_program('strip')
endif
if host_os_family != 'windows'
if host_os_family == 'darwin'
readelf = ''
otool = find_program('otool')
libtool = find_program('libtool')
else
readelf = find_program('readelf')
otool = ''
libtool = ''
endif
else
readelf = ''
otool = ''
libtool = ''
endif
if host_os_family == 'darwin'
install_name_tool = find_program('install_name_tool')
lipo = find_program('lipo')
codesign = find_program('codesign')
else
install_name_tool = ''
lipo = ''
codesign = ''
endif
have_local_backend = get_option('local_backend').allowed()
have_fruity_backend = get_option('fruity_backend').allowed()
have_droidy_backend = get_option('droidy_backend').allowed()
have_socket_backend = get_option('socket_backend').allowed()
have_barebone_backend = quickjs_dep.found()
have_compiler_backend = get_option('compiler_backend') \
.disable_if(not have_local_backend, error_message: 'compiler backend requires the local backend for script execution') \
.disable_auto_if(host_os == 'watchos') \
have_fruity_backend = get_option('fruity_backend') \
.disable_auto_if(not host_docks_mobile_devices) \
.allowed()
have_droidy_backend = get_option('droidy_backend') \
.disable_auto_if(not host_docks_mobile_devices) \
.allowed()
have_socket_backend = get_option('socket_backend').allowed()
have_barebone_backend = get_option('barebone_backend') \
.disable_if(not quickjs_dep.found()) \
.disable_auto_if(not host_docks_mobile_devices) \
.allowed()
compiler_backend_opt = get_option('compiler_backend') \
.disable_auto_if(host_os == 'watchos')
have_compiler_backend = false
if compiler_backend_opt.allowed()
go = find_program('go', native: true, required: false)
if go.found()
message('Detecting cgo availability')
detect_output = run_command(
[
python,
files('tools' / 'cgo' / 'detect.py'),
go,
host_os,
host_abi,
shlib_suffix,
cc.get_id(),
'>>>', cc.cmd_array(), '<<<',
'>>>', ar, '<<<',
'>>>', nm, '<<<',
'>>>', ranlib, '<<<',
],
capture: true,
check: true
).stdout()
lines = detect_output.split('\n')
status = lines[0]
if status == 'ok'
have_compiler_backend = true
tokens = lines[1].split(' ')
go_mode = tokens[0]
go_config = tokens[1]
compiler_backend_static_compilation = go_mode == 'c-archive'
if compiler_backend_static_compilation
vala_flags += '--define=COMPILER_BACKEND_STATIC_COMPILATION'
endif
else
error_message = lines[1]
if compiler_backend_opt.enabled()
error(error_message)
else
warning(f'Building without Compiler backend: @error_message@')
endif
endif
elif compiler_backend_opt.enabled()
error('Need Go >= 1.24 to build the Compiler backend powered by ESBuild and typescript-go')
else
warning('Building without Compiler backend: Go >= 1.24 not found')
endif
endif
build_gadget = get_option('gadget') \
.disable_auto_if(meson.is_subproject()) \
@@ -394,7 +500,7 @@ foreach b : [['local', have_local_backend],
endif
endforeach
if have_barebone_backend or have_compiler_backend
if host_os_family == 'darwin' or host_os == 'android' or have_barebone_backend or have_compiler_backend
node = find_program('node', version: '>=18.0.0', native: true, required: false)
if not node.found()
error('Need Node.js >= 18.0.0 to process JavaScript code at build time')
@@ -411,9 +517,8 @@ if gi_dep.found()
else
girdir = get_option('prefix') / get_option('datadir') / 'gir-1.0'
endif
uninstalled_girdir = meson.current_build_dir() / 'src'
vapidir = get_option('datadir') / 'vala' / 'vapi'
vapidir = get_option('prefix') / get_option('datadir') / 'vala' / 'vapi'
gum_vala_args = [
'--pkg=frida-gum-1.0',
@@ -425,18 +530,49 @@ gumjs_inspector_vala_args = ['--pkg=frida-gumjs-inspector-1.0', gum_vala_args]
have_v8 = gumjs_dep.get_variable('gumjs_v8') == 'enabled'
if have_v8
vala_flags += ['--define=HAVE_V8']
v8_mksnapshot = find_program('v8-mksnapshot-@0@-@1@'.format(host_os, host_abi), required: false)
if not v8_mksnapshot.found()
v8_mksnapshot = ''
endif
else
v8_mksnapshot = ''
endif
backend_deps_private = []
backend_reqs_private = []
backend_libs_private = []
openssl_options = [
'cli=disabled',
]
if host_os_family == 'windows' and cc.get_argument_syntax() != 'msvc'
openssl_options += 'asm=disabled'
endif
openssl_dep = dependency('openssl',
required: have_fruity_backend or get_option('connectivity').enabled(),
modules: cc.get_argument_syntax() == 'msvc' ? ['OpenSSL::SSL'] : [],
default_options: openssl_options,
)
if have_fruity_backend
foreach dep : ['libnghttp2', 'libngtcp2', 'libngtcp2_crypto_quictls', 'libusb-1.0']
backend_deps_private += dependency(dep)
backend_reqs_private += dep
endforeach
lwip_options = [
'ipv4=disabled',
'ipv6=enabled',
'dns=disabled',
'arp=disabled',
'ethernet=enabled',
'tcp_mss=4036',
'tcp_snd_buf=65535',
'tcp_wnd=65535',
]
if optimize_for_prod
lwip_options += 'lwip_debug=disabled'
else
lwip_options += 'lwip_debug=enabled'
endif
backend_deps_private += dependency('lwip', default_options: lwip_options)
backend_reqs_private += 'lwip'
endif
if quickjs_dep.found()
backend_deps_private += quickjs_dep
backend_reqs_private += 'quickjs'
@@ -456,8 +592,19 @@ else
termux_elf_cleaner = []
endif
tls_provider_dep = dependency('gioopenssl', required: get_option('connectivity'))
tls_provider_dep = dependency('gioopenssl', required: get_option('connectivity'), default_options: [
'gnutls=disabled',
'openssl=enabled',
'libproxy=disabled',
'gnome_proxy=disabled',
'tests=false',
])
tls_provider_vala_args = []
if tls_provider_dep.found()
tls_provider_vala_args += [
'--pkg=gioopenssl',
'--vapidir=' + tls_provider_dep.get_variable('vapidir'),
]
cdata.set('HAVE_GIOOPENSSL', 1)
vala_flags += ['--define=HAVE_GIOOPENSSL']
backend_deps_private += tls_provider_dep
@@ -473,7 +620,6 @@ nice_dep = dependency('nice', required: get_option('connectivity'), default_opti
'introspection=disabled',
])
if nice_dep.found()
openssl_dep = dependency('openssl')
usrsctp_dep = dependency('usrsctp', default_options: [
'sctp_inet=false',
'sctp_inet6=false',
@@ -489,7 +635,6 @@ if nice_dep.found()
cdata.set('HAVE_SCONN_LEN', 1)
endif
else
openssl_dep = []
usrsctp_dep = []
endif
@@ -506,42 +651,6 @@ if host_os in ['ios', 'tvos']
backend_libs_private += ['-Wl,-framework,CoreGraphics', '-Wl,-framework,UIKit']
endif
if host_toolchain == 'microsoft'
lib = find_program('lib')
ar = ''
nm = ''
strip = ''
else
lib = ''
ar = find_program('ar')
nm = find_program('nm')
strip = find_program('strip')
endif
if host_os_family != 'windows'
if host_os_family == 'darwin'
readelf = ''
otool = find_program('otool')
libtool = find_program('libtool')
else
readelf = find_program('readelf')
otool = ''
libtool = ''
endif
else
readelf = ''
otool = ''
libtool = ''
endif
if host_os_family == 'darwin'
install_name_tool = find_program('install_name_tool')
lipo = find_program('lipo')
codesign = find_program('codesign')
else
install_name_tool = ''
lipo = ''
codesign = ''
endif
if get_option('devkits').length() != 0
if get_option('default_library') != 'static'
error('Devkits can only be generated from static libraries')
@@ -599,6 +708,8 @@ post_process = [
'@INPUT0@',
]
compile_js_agent = files('tools' / 'compile-js-agent.py')
mapper_opt = get_option('mapper')
if mapper_opt.auto()
have_mapper = host_os_family == 'darwin'
@@ -627,25 +738,29 @@ if cc.get_id() == 'gcc' and cc.compiles('#if __GNUC__ >= 5\n#error NOTNEEDED\n#e
add_project_arguments('-w', language: 'c')
endif
vapidir = meson.current_source_dir() / 'vapi'
vala_flags += [
'--vapidir=' + meson.current_source_dir() / 'vapi',
'--vapidir=' + vapidir,
'--pkg', 'config',
]
vala_flags += ['--define=' + host_os_family.to_upper()]
vala_flags += '--define=' + host_os_family.to_upper()
if host_os != host_os_family
vala_flags += ['--define=' + host_os.to_upper()]
vala_flags += '--define=' + host_os.to_upper()
endif
vala_flags += ['--define=' + host_arch.to_upper()]
vala_flags += '--define=' + host_arch.to_upper()
if host_abi != host_arch
vala_flags += ['--define=' + host_abi.to_upper()]
vala_flags += '--define=' + host_abi.to_upper()
endif
vala_flags += '--define=' + host_machine.endian().to_upper() + '_ENDIAN'
add_project_arguments(vala_flags, language: 'vala')
add_project_arguments('-I' + vapidir, language: 'c')
native_vala_flags = [
'--vapidir=' + meson.current_source_dir() / 'vapi',
]
add_project_arguments(native_vala_flags, language: 'vala', native: true)
add_project_arguments('-I' + vapidir, language: 'c', native: true)
subdir('compat')
subdir('tools')
@@ -664,9 +779,30 @@ if build_tests
subdir('tests')
endif
summary(
{
'local': have_local_backend,
'fruity': have_fruity_backend,
'droidy': have_droidy_backend,
'socket': have_socket_backend,
'barebone': have_barebone_backend,
'compiler': have_compiler_backend,
},
section: 'Backends',
bool_yn: true,
)
summary(
{
'compat': compat_summary,
'assets': get_option('assets'),
'mapper': have_mapper,
'connectivity': tls_provider_dep.found(),
'gadget': build_gadget,
'server': build_server,
'portal': build_portal,
'inject': build_inject,
'tests': build_tests,
},
section: 'Features',
bool_yn: true,
)
+16 -20
View File
@@ -37,13 +37,7 @@ option('barebone_backend',
option('compiler_backend',
type: 'feature',
value: 'auto',
description: 'Include frida-compile backend powered by GumJS',
)
option('compiler_snapshot',
type: 'feature',
value: 'auto',
description: 'Speed up compiler startup by using a snapshot'
description: 'Include frida-compile backend powered by ESBuild and typescript-go',
)
option('assets',
@@ -68,13 +62,25 @@ option('compat',
option('helper_modern',
type: 'string',
value: 'auto',
description: 'Prebuilt frida-helper to embed for use on modern systems'
description: 'Prebuilt frida-helper to embed for supporting modern targets'
)
option('helper_legacy',
type: 'string',
value: 'auto',
description: 'Prebuilt frida-helper to embed for use on legacy systems'
description: 'Prebuilt frida-helper to embed for supporting legacy targets'
)
option('helper_emulated_modern',
type: 'string',
value: 'auto',
description: 'Prebuilt frida-helper to embed for supporting modern emulated targets'
)
option('helper_emulated_legacy',
type: 'string',
value: 'auto',
description: 'Prebuilt frida-helper to embed for supporting legacy emulated targets'
)
option('agent_modern',
@@ -101,16 +107,6 @@ option('agent_emulated_legacy',
description: 'Prebuilt agent to embed for use on legacy emulated targets'
)
option('agent_dbghelp_prefix',
type: 'string',
description: 'Location of DbgHelp binaries to embed alongside agent (Windows only)'
)
option('agent_symsrv_prefix',
type: 'string',
description: 'Location of SymSrv binaries to embed alongside agent (Windows only)'
)
option('gadget',
type: 'feature',
value: 'auto',
@@ -137,7 +133,7 @@ option('inject',
option('connectivity',
type: 'feature',
value: 'auto',
value: 'enabled',
description: 'Internet connectivity features (TLS and ICE support)'
)
+1 -1
View File
@@ -20,7 +20,7 @@ if tls_provider_dep.found()
endif
raw_portal = executable('frida-portal-raw', portal_sources,
vala_args: [core_vala_args, '--pkg=posix'],
vala_args: [core_vala_args, tls_provider_vala_args, '--pkg=posix'],
link_args: extra_link_args,
link_depends: extra_link_depends,
dependencies: [core_dep] + extra_deps,
+1 -1
View File
@@ -142,7 +142,7 @@ namespace Frida.Portal {
return application.run ();
}
private class Application : Object {
private sealed class Application : Object {
public signal void ready (bool success);
public PortalService service {
+1 -1
Submodule releng updated: 6bad5eec71...e10baa39a2.
+52 -9
View File
@@ -3,6 +3,7 @@ namespace Frida.Server {
private const string DEFAULT_DIRECTORY = "re.frida.server";
private static bool output_version = false;
private static string? device_id = null;
private static string? listen_address = null;
private static string? certpath = null;
private static string? origin = null;
@@ -30,6 +31,7 @@ namespace Frida.Server {
const OptionEntry[] option_entries = {
{ "version", 0, 0, OptionArg.NONE, ref output_version, "Output version information and exit", null },
{ "device", 0, 0, OptionArg.STRING, ref device_id, "Serve device with the given ID", "ID" },
{ "listen", 'l', 0, OptionArg.STRING, ref listen_address, "Listen on ADDRESS", "ADDRESS" },
{ "certificate", 0, 0, OptionArg.FILENAME, ref certpath, "Enable TLS using CERTIFICATE", "CERTIFICATE" },
{ "origin", 0, 0, OptionArg.STRING, ref origin, "Only accept requests with “Origin” header matching ORIGIN " +
@@ -178,7 +180,7 @@ namespace Frida.Server {
#if DARWIN
var worker = new Thread<int> ("frida-server-main-loop", () => {
var exit_code = run_application (endpoint_params, options, on_ready);
var exit_code = run_application (device_id, endpoint_params, options, on_ready);
_stop_run_loop ();
@@ -190,15 +192,16 @@ namespace Frida.Server {
return exit_code;
#else
return run_application (endpoint_params, options, on_ready);
return run_application (device_id, endpoint_params, options, on_ready);
#endif
}
private static int run_application (EndpointParameters endpoint_params, ControlServiceOptions options, ReadyHandler on_ready) {
private static int run_application (string? device_id, EndpointParameters endpoint_params, ControlServiceOptions options,
ReadyHandler on_ready) {
TemporaryDirectory.always_use ((directory != null) ? directory : DEFAULT_DIRECTORY);
TemporaryDirectory.use_sysroot (options.sysroot);
application = new Application (new ControlService (endpoint_params, options));
application = new Application (device_id, endpoint_params, options);
Posix.signal (Posix.Signal.INT, (sig) => {
application.stop ();
@@ -232,22 +235,39 @@ namespace Frida.Server {
}
#endif
private class Application : Object {
private sealed class Application : Object {
public signal void ready (bool success);
public ControlService service {
public string? device_id {
get;
construct;
}
public EndpointParameters endpoint_params {
get;
construct;
}
public ControlServiceOptions options {
get;
construct;
}
private DeviceManager? manager;
private ControlService? service;
private Cancellable io_cancellable = new Cancellable ();
private MainLoop loop = new MainLoop ();
private int exit_code;
private bool stopping;
public Application (ControlService service) {
Object (service: service);
public Application (string? device_id, EndpointParameters endpoint_params, ControlServiceOptions options) {
Object (
device_id: device_id,
endpoint_params: endpoint_params,
options: options
);
}
public int run () {
@@ -265,6 +285,17 @@ namespace Frida.Server {
private async void start () {
try {
if (device_id != null && device_id != "local") {
manager = new DeviceManager.with_nonlocal_backends_only ();
var device = yield manager.get_device_by_id (device_id, 0, io_cancellable);
device.lost.connect (on_device_lost);
service = yield new ControlService.with_device (device, endpoint_params, options);
} else {
service = new ControlService (endpoint_params, options);
}
yield service.start (io_cancellable);
} catch (GLib.Error e) {
if (e is IOError.CANCELLED)
@@ -297,7 +328,15 @@ namespace Frida.Server {
io_cancellable.cancel ();
try {
yield service.stop ();
if (service != null) {
yield service.stop ();
service = null;
}
if (manager != null) {
yield manager.close ();
manager = null;
}
} catch (GLib.Error e) {
}
@@ -306,6 +345,10 @@ namespace Frida.Server {
return false;
});
}
private void on_device_lost () {
stop ();
}
}
private TlsCertificate? parse_certificate (string? path) throws GLib.Error {
+1 -1
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class AgentContainer : Object, AgentSessionProvider {
public sealed class AgentContainer : Object, AgentSessionProvider {
public DBusConnection connection {
get;
private set;
+91284
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+141723
View File
File diff suppressed because it is too large. Load diff
+174 -39
View File
@@ -1,42 +1,71 @@
from __future__ import annotations
import argparse
import os
from dataclasses import dataclass
from io import StringIO
from pathlib import Path
import re
import sys
from typing import List, Set
import xml.etree.ElementTree as ET
CORE_NAMESPACE = "http://www.gtk.org/introspection/core/1.0"
C_NAMESPACE = "http://www.gtk.org/introspection/c/1.0"
GLIB_NAMESPACE = "http://www.gtk.org/introspection/glib/1.0"
GIR_NAMESPACES = {
"": CORE_NAMESPACE,
"c": C_NAMESPACE,
"glib": GLIB_NAMESPACE,
}
CORE_TAG_IMPLEMENTS = f"{{{CORE_NAMESPACE}}}implements"
CORE_TAG_FIELD = f"{{{CORE_NAMESPACE}}}field"
CORE_TAG_CONSTRUCTOR = f"{{{CORE_NAMESPACE}}}constructor"
CORE_TAG_METHOD = f"{{{CORE_NAMESPACE}}}method"
OBJECT_TYPE_PATTERN = re.compile(r"\bpublic\s+(sealed )?(class|interface)\s+(\w+)\b")
def main():
parser = argparse.ArgumentParser(description="Generate refined Frida API definitions")
parser.add_argument('--output', dest='output_type', choices=['bundle', 'header', 'gir', 'vapi', 'vapi-stamp'], default='bundle')
parser.add_argument('frida_version', metavar='frida-version', type=str)
parser.add_argument('frida_major_version', metavar='frida-major-version', type=str)
parser.add_argument('frida_minor_version', metavar='frida-minor-version', type=str)
parser.add_argument('frida_micro_version', metavar='frida-micro-version', type=str)
parser.add_argument('frida_nano_version', metavar='frida-nano-version', type=str)
parser.add_argument('api_version', metavar='api-version', type=str)
parser.add_argument('core_header', metavar='/path/to/frida-core.h', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('core_gir', metavar='/path/to/Frida-x.y.gir', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('core_vapi', metavar='/path/to/frida-core.vapi', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('core_header', metavar='/path/to/frida-core.h', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('base_vapi', metavar='/path/to/frida-base.vapi', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('base_header', metavar='/path/to/frida-base.h', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('base_gir', metavar='/path/to/FridaBase-x.y.gir', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('base_vapi', metavar='/path/to/frida-base.vapi', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('output_dir', metavar='/output/dir')
args = parser.parse_args()
output_type = args.output_type
frida_version = args.frida_version
frida_version_components = (
args.frida_major_version,
args.frida_minor_version,
args.frida_micro_version,
args.frida_nano_version,
)
api_version = args.api_version
core_header = args.core_header.read()
core_gir = args.core_gir.read()
core_vapi = args.core_vapi.read()
core_header = args.core_header.read()
base_vapi = args.base_vapi.read()
base_header = args.base_header.read()
base_gir = args.base_gir.read()
base_vapi = args.base_vapi.read()
output_dir = Path(args.output_dir)
if output_type == 'gir':
(output_dir / f"Frida-{api_version}.gir").write_text(core_gir, encoding='utf-8')
return
if output_type == 'vapi-stamp':
(output_dir / f"frida-core-{api_version}.vapi.stamp").write_bytes(b"")
return
toplevel_names = [
"frida.vala",
"package-manager.vala",
"control-service.vala",
"portal-service.vala",
"file-monitor.vala",
@@ -45,33 +74,58 @@ def main():
toplevel_sources = []
src_dir = Path(__file__).parent.parent.resolve()
for name in toplevel_names:
with open(src_dir / name, 'r', encoding='utf-8') as f:
toplevel_sources.append(f.read())
toplevel_sources.append((src_dir / name).read_text(encoding='utf-8'))
toplevel_code = "\n".join(toplevel_sources)
enable_header = False
enable_gir = False
enable_vapi = False
if output_type == 'bundle':
enable_header = True
enable_gir = True
enable_vapi = True
elif output_type == 'header':
enable_header = True
elif output_type == 'gir':
enable_gir = True
elif output_type == 'vapi':
enable_vapi = True
api = parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, base_header)
api = parse_api(frida_version, frida_version_components, api_version, toplevel_code, core_header, core_vapi, base_header, base_vapi)
if enable_header:
emit_header(api, output_dir)
if enable_gir:
emit_gir(api, core_gir, base_gir, output_dir)
if enable_vapi:
emit_vapi(api, output_dir)
def emit_header(api, output_dir):
with open(output_dir / 'frida-core.h', 'w', encoding='utf-8') as output_header_file:
with OutputFile(output_dir / 'frida-core.h') as output_header_file:
output_header_file.write("#ifndef __FRIDA_CORE_H__\n#define __FRIDA_CORE_H__\n\n")
output_header_file.write("#include <glib.h>\n#include <glib-object.h>\n#include <gio/gio.h>\n#include <json-glib/json-glib.h>\n")
output_header_file.write("#include <glib.h>\n#include <glib-object.h>\n#include <gio/gio.h>\n#include <json-glib/json-glib.h>\n\n")
output_header_file.write(f"#define FRIDA_VERSION \"{api.frida_version}\"\n\n")
for name, value in zip(['MAJOR', 'MINOR', 'MICRO', 'NANO'], api.frida_version_components):
output_header_file.write(f"#define FRIDA_{name}_VERSION {value}\n")
output_header_file.write("""
#define FRIDA_CHECK_VERSION(maj, min, mic) \\
(FRIDA_CURRENT_VERSION >= FRIDA_VERSION_ENCODE ((maj), (min), (mic)))
#define FRIDA_CURRENT_VERSION \\
FRIDA_VERSION_ENCODE ( \\
FRIDA_MAJOR_VERSION, \\
FRIDA_MINOR_VERSION, \\
FRIDA_MICRO_VERSION)
#define FRIDA_VERSION_ENCODE(maj, min, mic) \\
(((maj) * 1000000U) + ((min) * 1000U) + (mic))
""")
output_header_file.write("\nG_BEGIN_DECLS\n")
@@ -79,7 +133,6 @@ def emit_header(api, output_dir):
output_header_file.write("\ntypedef struct _%s %s;" % (object_type.c_name, object_type.c_name))
if object_type.c_iface_definition is not None:
output_header_file.write("\ntypedef struct _%sIface %sIface;" % (object_type.c_name, object_type.c_name))
output_header_file.write("\ntypedef struct _FridaHostSession FridaHostSession;")
for enum in api.enum_types:
output_header_file.write("\n\n" + enum.c_definition)
@@ -150,8 +203,64 @@ def emit_header(api, output_dir):
output_header_file.write("\n\n#endif\n")
def emit_gir(api: ApiSpec, core_gir: str, base_gir: str, output_dir: Path) -> str:
ET.register_namespace("", CORE_NAMESPACE)
ET.register_namespace("c", C_NAMESPACE)
ET.register_namespace("glib", GLIB_NAMESPACE)
core_tree = ET.ElementTree(ET.fromstring(core_gir))
base_tree = ET.ElementTree(ET.fromstring(base_gir))
core_root = core_tree.getroot()
base_root = base_tree.getroot()
merged_root = ET.Element(core_root.tag, core_root.attrib)
for elem in core_root.findall("include", GIR_NAMESPACES):
name = elem.get("name")
if name in {"GLib", "GObject", "Gio"}:
merged_root.append(elem)
for tag in ["package", "c:include"]:
for elem in core_root.findall(tag, GIR_NAMESPACES):
merged_root.append(elem)
core_namespace = core_root.find("namespace", GIR_NAMESPACES)
merged_namespace = ET.SubElement(merged_root, core_namespace.tag, core_namespace.attrib)
object_type_names = {obj.name for obj in api.object_types}
enum_type_names = {enum.name for enum in api.enum_types}
error_type_names = {error.name for error in api.error_types}
def merge_and_transform_elements(tag_name: str, spec_set: Set[str]):
core_elements = filter_elements(core_root.findall(f".//{tag_name}", GIR_NAMESPACES), spec_set)
base_elements = filter_elements(base_root.findall(f".//{tag_name}", GIR_NAMESPACES), spec_set)
for elem in core_elements + base_elements:
if tag_name == "class":
for child in list(elem):
if (child.tag == CORE_TAG_IMPLEMENTS and child.get("name") == "FridaBase.AgentMessageSink") \
or child.tag == CORE_TAG_FIELD \
or child.get("name").startswith("_"):
elem.remove(child)
merged_namespace.append(elem)
merge_and_transform_elements("class", object_type_names)
merge_and_transform_elements("interface", object_type_names)
merge_and_transform_elements("enumeration", enum_type_names | error_type_names)
ET.indent(merged_root, space=" ")
result = ET.tostring(merged_root,
encoding="unicode",
xml_declaration=True)
result = result.replace("FridaBase.", "Frida.")
with OutputFile(output_dir / f"Frida-{api.version}.gir") as output_gir:
output_gir.write(result)
def filter_elements(elements: List[ET.Element], spec_set: Set[str]):
return [elem for elem in elements if elem.get("name") in spec_set]
def emit_vapi(api, output_dir):
with open(output_dir / "frida-core-{0}.vapi".format(api.version), "w", encoding='utf-8') as output_vapi_file:
with OutputFile(output_dir / f"frida-core-{api.version}.vapi") as output_vapi_file:
output_vapi_file.write("[CCode (cheader_filename = \"frida-core.h\", cprefix = \"Frida\", lower_case_cprefix = \"frida_\")]")
output_vapi_file.write("\nnamespace Frida {")
output_vapi_file.write("\n\tpublic static void init ();")
@@ -189,12 +298,12 @@ def emit_vapi(api, output_dir):
output_vapi_file.write("\n}\n")
with open(output_dir / "frida-core-{0}.deps".format(api.version), "w", encoding='utf-8') as output_deps_file:
with OutputFile(output_dir / f"frida-core-{api.version}.deps") as output_deps_file:
output_deps_file.write("glib-2.0\n")
output_deps_file.write("gobject-2.0\n")
output_deps_file.write("gio-2.0\n")
def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, base_header):
def parse_api(frida_version, frida_version_components, api_version, toplevel_code, core_header, core_vapi, base_header, base_vapi):
all_headers = core_header + "\n" + base_header
all_enum_names = [m.group(1) for m in re.finditer(r"^\t+public\s+enum\s+(\w+)\s+", toplevel_code + "\n" + base_vapi, re.MULTILINE)]
@@ -217,12 +326,18 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
"StaticAuthenticationService": "AuthenticationService",
}
internal_type_prefixes = [
"AgentMessageKind",
"Fruity",
"HostSession",
"MessageType",
"PeerSetup",
"PortConflictBehavior",
"ResultCode",
"SpawnStartState",
"State",
"StringTerminator",
"UnloadPolicy",
"WebService",
"Winjector"
]
seen_enum_names = set()
@@ -287,8 +402,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
method_cname_lc = object_type.c_name_lc + '_' + method_name
if method_cname_lc not in seen_cfunctions:
seen_cfunctions.add(method_cname_lc)
if method_name not in ('construct', 'construct_with_host_session', 'get_main_context', 'get_provider', 'get_session') \
and not (object_type.name in ("Session", "Script") and method_name == 'get_id'):
if method_name != 'construct':
if (object_type.c_name + '*') in m.group(0):
if method_name == 'new' or method_name.startswith('new_'):
object_type.c_constructors.append(method_cprototype)
@@ -305,7 +419,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
if delegate_cname not in seen_cdelegates:
seen_cdelegates.add(delegate_cname)
object_type.c_delegate_typedefs.append(beautify_cprototype(d.group(0)))
if object_type.kind == 'interface' and object_type.name != "Injector":
if object_type.kind == 'interface':
for m in re.finditer("^(struct _" + object_type.c_name + "Iface {[^}]+};)$", all_headers, re.MULTILINE):
object_type.c_iface_definition = beautify_cinterface(m.group(1))
@@ -327,8 +441,10 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
if stripped_line == "}":
ignoring = False
else:
if stripped_line.startswith("public abstract") or stripped_line.startswith("public class Promise") \
or stripped_line.startswith("public interface Future"):
if stripped_line.startswith("public abstract") \
or stripped_line.startswith("public class Promise") \
or stripped_line.startswith("public interface Future") \
or stripped_line.startswith("public class CF"):
ignoring = True
elif stripped_line.startswith("public enum") or stripped_line.startswith("public errordomain"):
name = re.match(r"^public (?:enum|errordomain) (\w+) ", stripped_line).group(1)
@@ -340,8 +456,8 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
current_enum.vapi_declaration = stripped_line
else:
ignoring = True
elif stripped_line.startswith("public class") or stripped_line.startswith("public interface"):
name = re.match(r"^public (class|interface) (\w+) ", stripped_line).group(2)
elif (match := OBJECT_TYPE_PATTERN.match(stripped_line)) is not None:
name = match.group(3)
if name not in object_type_by_name:
ignoring = True
else:
@@ -360,8 +476,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
current_object_type.vapi_signals.append(stripped_line)
elif "{ get" in stripped_line:
name = re.match(r".+?(\w+)\s+{", stripped_line).group(1)
if name not in ('main_context', 'provider', 'session'):
current_object_type.vapi_properties.append(stripped_line)
current_object_type.vapi_properties.append(stripped_line)
else:
m = re.match(r".+?(\w+)\s+\(", stripped_line)
if m is not None:
@@ -381,7 +496,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
m = re.search(r"^[\w\*]+ frida_{}.+?;".format(f.name), all_headers, re.MULTILINE | re.DOTALL)
f.c_prototype = beautify_cprototype(m.group(0))
return ApiSpec(api_version, object_types, functions, enum_types, error_types)
return ApiSpec(frida_version, frida_version_components, api_version, object_types, functions, enum_types, error_types)
def function_is_public(name):
return not name.startswith("_") and \
@@ -395,22 +510,25 @@ def function_is_public(name):
"parse_control_address",
"parse_cluster_address",
"parse_socket_address",
"negotiate_connection"
"negotiate_connection",
"check_kernel_version",
]
def parse_vala_object_types(source):
return [ApiObjectType(m.group(2), m.group(1)) for m in re.finditer(r"^\t+public\s+(class|interface)\s+(\w+)\s+", source, re.MULTILINE)]
def parse_vala_object_types(source) -> List[ApiObjectType]:
return [ApiObjectType(m.group(3), m.group(2)) for m in OBJECT_TYPE_PATTERN.finditer(source, re.MULTILINE)]
def parse_vapi_functions(vapi):
def parse_vapi_functions(vapi) -> List[ApiFunction]:
return [ApiFunction(m.group(1), m.group(0)) for m in re.finditer(r"^\tpublic static .+ (\w+) \(.+;", vapi, re.MULTILINE)]
@dataclass
class ApiSpec:
def __init__(self, version, object_types, functions, enum_types, error_types):
self.version = version
self.object_types = object_types
self.functions = functions
self.enum_types = enum_types
self.error_types = error_types
frida_version: str
frida_version_components: List[int]
version: str
object_types: List[ApiObjectType]
functions: List[ApiFunction]
enum_types: List[ApiEnum]
error_types: List[ApiEnum]
class ApiEnum:
def __init__(self, name):
@@ -512,6 +630,23 @@ def fuzzysort(items, keys):
result.extend(remaining)
return result
class OutputFile:
def __init__(self, output_path):
self._output_path = output_path
self._io = StringIO()
def __enter__(self):
return self._io
def __exit__(self, *exc):
result = self._io.getvalue()
if self._output_path.exists():
existing_contents = self._output_path.read_text(encoding='utf-8')
if existing_contents == result:
return False
self._output_path.write_text(result, encoding='utf-8')
return False
if __name__ == '__main__':
main()
+42 -48
View File
@@ -1,55 +1,50 @@
fs = import('fs')
generate_api = [python, files('generate.py')]
generate_api_args = [
frida_version,
frida_major_version.to_string(),
frida_minor_version.to_string(),
frida_micro_version.to_string(),
frida_nano_version.to_string(),
api_version,
core_build_dir / 'frida-core.h',
core_build_dir / core_gir_name,
core_build_dir / 'frida-core.vapi',
core_build_dir / 'frida-core.h',
base_build_dir / f'frida-base-@[email protected]',
base_build_dir / 'frida-base.h',
base_build_dir / base_gir_name,
base_build_dir / f'frida-base-@[email protected]',
meson.current_build_dir(),
]
core_public_h = custom_target('frida-core-header',
input: [core, base],
output: ['frida-core.h'],
command: [
generate_api,
'--output=header',
generate_api_args,
],
install: true,
install_dir: header_install_dir,
)
core_public_gir = custom_target('frida-core-gir',
input: [core, base],
output: [core_gir_name],
command: [
generate_api,
'--output=gir',
generate_api_args,
],
install: true,
install_dir: girdir,
)
core_public_vapi = custom_target('frida-core-vapi',
core_api = custom_target('frida-core-api',
input: [core, base],
output: [
'frida-core.h',
core_gir_name,
f'frida-core-@[email protected]',
f'frida-core-@[email protected]',
],
command: [
generate_api,
'--output=vapi',
'--output=bundle',
generate_api_args,
],
install: true,
install_dir: vapidir,
install_dir: [header_install_dir, girdir, vapidir, vapidir],
)
core_public_vapi_stamp = custom_target('frida-core-vapi-stamp',
core_public_h = core_api[0]
core_public_gir = core_api[1]
core_public_vapi = [core_api[2], core_api[3]]
install_glib_girs = not gi_dep.found() and not fs.exists(girdir / 'GLib-2.0.gir')
glib_gir = fs.copyfile('GLib-2.0.gir', install: install_glib_girs, install_dir: girdir)
gobject_gir = fs.copyfile('GObject-2.0.gir', install: install_glib_girs, install_dir: girdir)
gio_gir = fs.copyfile('Gio-2.0.gir', install: install_glib_girs, install_dir: girdir)
core_public_vapi_stamp = custom_target('frida-core-vapi-stamp',
input: core_public_vapi,
output: f'frida-core-@[email protected]',
command: [
@@ -76,8 +71,6 @@ core_public_lib = custom_target('frida-core-library',
install_dir: get_option('libdir'),
)
fs = import('fs')
core_public_extra_headers = []
if host_os == 'android'
core_public_extra_headers += fs.copyfile(frida_selinux_h)
@@ -88,19 +81,28 @@ if build_machine.system() == 'windows'
else
uninstalled_incdir = meson.current_build_dir()
endif
uninstalled_girdir = uninstalled_incdir
uninstalled_vapidir = uninstalled_incdir
uninstalled_variables = {
'frida_includedir': uninstalled_incdir,
'frida_girdir': uninstalled_girdir,
'frida_vapidir': uninstalled_vapidir,
}
installed_variables = {
'frida_includedir': '${includedir}',
'frida_girdir': girdir,
'frida_vapidir': vapidir,
}
core_public_dep = declare_dependency(
sources: [core_public_h, core_public_gir, core_public_vapi_stamp, core_public_extra_headers],
sources: [core_public_h, core_public_gir, glib_gir, gobject_gir, gio_gir, core_public_vapi_stamp, core_public_extra_headers],
include_directories: include_directories('.'),
link_args: backend_libs_private,
link_with: core_public_lib,
dependencies: core_deps,
variables: {
'frida_includedir': uninstalled_incdir,
'frida_girdir': uninstalled_girdir,
'frida_vapidir': uninstalled_vapidir,
},
variables: uninstalled_variables,
)
pkg = import('pkgconfig')
@@ -115,16 +117,8 @@ pkg.generate(
libraries: core_public_lib,
libraries_private: backend_libs_private,
extra_cflags: ['-I${frida_includedir}'],
variables: {
'frida_includedir': '${includedir}',
'frida_girdir': girdir,
'frida_vapidir': vapidir,
},
uninstalled_variables: {
'frida_includedir': uninstalled_incdir,
'frida_girdir': uninstalled_girdir,
'frida_vapidir': uninstalled_vapidir,
},
variables: installed_variables,
uninstalled_variables: uninstalled_variables,
)
meson.override_dependency(f'frida-core-@api_version@', core_public_dep)
+1 -1
View File
@@ -17,7 +17,7 @@ namespace Frida.Barebone {
public abstract async void deallocate (Cancellable? cancellable) throws Error, IOError;
}
public class SimpleAllocator : Object, Allocator {
public sealed class SimpleAllocator : Object, Allocator {
public size_t page_size {
get { return _page_size; }
}
+1 -1
View File
@@ -1,6 +1,6 @@
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
namespace Frida.Barebone {
public class ArmMachine : Object, Machine {
public sealed class ArmMachine : Object, Machine {
public override GDB.Client gdb {
get;
set;
+1 -1
View File
@@ -1,6 +1,6 @@
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
namespace Frida.Barebone {
public class Arm64Machine : Object, Machine {
public sealed class Arm64Machine : Object, Machine {
public override GDB.Client gdb {
get;
set;
+1 -1
View File
@@ -1,6 +1,6 @@
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
namespace Frida.Barebone {
public class UnknownMachine : Object, Machine {
public sealed class UnknownMachine : Object, Machine {
public GDB.Client gdb {
get;
set;
+1 -1
View File
@@ -1,6 +1,6 @@
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
namespace Frida.Barebone {
public class IA32Machine : Object, Machine {
public sealed class IA32Machine : Object, Machine {
public override GDB.Client gdb {
get;
set;
+1 -1
View File
@@ -1,6 +1,6 @@
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
namespace Frida.Barebone {
public class X64Machine : Object, Machine {
public sealed class X64Machine : Object, Machine {
public override GDB.Client gdb {
get;
set;
+46 -6
View File
@@ -1,5 +1,5 @@
namespace Frida {
public class BareboneHostSessionBackend : Object, HostSessionBackend {
public sealed class BareboneHostSessionBackend : Object, HostSessionBackend {
private BareboneHostSessionProvider? provider;
private const uint16 DEFAULT_PORT = 3333;
@@ -30,7 +30,7 @@ namespace Frida {
}
}
public class BareboneHostSessionProvider : Object, HostSessionProvider {
public sealed class BareboneHostSessionProvider : Object, HostSessionProvider {
public string id {
get { return "barebone"; }
}
@@ -141,12 +141,35 @@ namespace Frida {
return yield this.host_session.link_agent_session (id, sink, cancellable);
}
public void unlink_agent_session (HostSession host_session, AgentSessionId id) {
if (host_session != this.host_session)
return;
this.host_session.unlink_agent_session (id);
}
public async IOStream link_channel (HostSession host_session, ChannelId id, Cancellable? cancellable)
throws Error, IOError {
throw new Error.NOT_SUPPORTED ("Channels are not supported by this backend");
}
public void unlink_channel (HostSession host_session, ChannelId id) {
}
public async ServiceSession link_service_session (HostSession host_session, ServiceSessionId id, Cancellable? cancellable)
throws Error, IOError {
throw new Error.NOT_SUPPORTED ("Services are not supported by this backend");
}
public void unlink_service_session (HostSession host_session, ServiceSessionId id) {
}
private void on_agent_session_detached (AgentSessionId id, SessionDetachReason reason, CrashInfo crash) {
agent_session_detached (id, reason, crash);
}
}
public class BareboneHostSession : Object, HostSession {
public sealed class BareboneHostSession : Object, HostSession {
public Barebone.Services services {
get;
construct;
@@ -260,6 +283,14 @@ namespace Frida {
return session;
}
public void unlink_agent_session (AgentSessionId id) {
BareboneAgentSession? session = agent_sessions[id];
if (session == null)
return;
session.message_sink = null;
}
public async InjectorPayloadId inject_library_file (uint pid, string path, string entrypoint, string data,
Cancellable? cancellable) throws Error, IOError {
throw_not_supported ();
@@ -270,6 +301,14 @@ namespace Frida {
throw_not_supported ();
}
public async ChannelId open_channel (string address, Cancellable? cancellable) throws Error, IOError {
throw new Error.NOT_SUPPORTED ("Channels are not supported by this backend");
}
public async ServiceSessionId open_service (string address, Cancellable? cancellable) throws Error, IOError {
throw new Error.NOT_SUPPORTED ("Services are not supported by this backend");
}
private void on_agent_session_closed (BareboneAgentSession session) {
AgentSessionId id = session.id;
@@ -282,7 +321,7 @@ namespace Frida {
}
}
private class BareboneAgentSession : Object, AgentSession {
private sealed class BareboneAgentSession : Object, AgentSession {
public signal void closed ();
public AgentSessionId id {
@@ -426,7 +465,8 @@ namespace Frida {
public async void load_script (AgentScriptId script_id, Cancellable? cancellable) throws Error, IOError {
check_open ();
get_script (script_id).load ();
var script = get_script (script_id);
yield script.load (cancellable);
}
public async void eternalize_script (AgentScriptId script_id, Cancellable? cancellable) throws Error, IOError {
@@ -525,7 +565,7 @@ namespace Frida {
}
namespace Barebone {
public class Services : Object {
public sealed class Services : Object {
public Machine machine {
get;
construct;
+1 -1
View File
@@ -1,6 +1,6 @@
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
namespace Frida.Barebone {
public class Callback : Object {
public sealed class Callback : Object {
private uint64 code;
private CallbackHandler handler;
private Machine machine;
-36
View File
@@ -1,36 +0,0 @@
from pathlib import Path
import shutil
import subprocess
import sys
def main(argv):
output_dir, priv_dir, input_dir, npm = [Path(d).resolve() for d in argv[1:]]
try:
generate_runtime(output_dir, priv_dir, input_dir, npm)
except Exception as e:
print(e, file=sys.stderr)
sys.exit(1)
def generate_runtime(output_dir, priv_dir, input_dir, npm):
priv_dir.mkdir(exist_ok=True)
shutil.copy(input_dir / "package.json", priv_dir)
shutil.copy(input_dir / "package-lock.json", priv_dir)
runtime_reldir = Path("script-runtime")
runtime_srcdir = input_dir / runtime_reldir
runtime_intdir = priv_dir / runtime_reldir
if runtime_intdir.exists():
shutil.rmtree(runtime_intdir)
shutil.copytree(runtime_srcdir, runtime_intdir)
subprocess.run([npm, "install"], capture_output=True, cwd=priv_dir, check=True)
shutil.copy(priv_dir / "script-runtime.js", output_dir)
if __name__ == "__main__":
main(sys.argv)
+1 -1
View File
@@ -1,6 +1,6 @@
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
namespace Frida.Barebone {
public class Interceptor : Object {
public sealed class Interceptor : Object {
public Machine machine {
get;
construct;
+3 -3
View File
@@ -29,11 +29,11 @@ barebone_script_runtime = custom_target('frida-barebone-script-runtime',
],
command: [
python,
files('generate-script-runtime.py'),
meson.current_build_dir(),
compile_js_agent,
'@OUTPUT@',
'@PRIVATE_DIR@',
meson.current_source_dir(),
npm,
'@INPUT@',
],
)
backend_sources += custom_target('frida-data-barebone',
+451 -442
View File
@@ -1,494 +1,503 @@
{
"name": "frida-barebone-runtime",
"name": "frida-barebone-script-runtime",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "frida-barebone-runtime",
"name": "frida-barebone-script-runtime",
"version": "1.0.0",
"devDependencies": {
"@types/frida-gum": "^18.3.2",
"frida-compile": "^16.2.1"
"@types/frida-gum": "^19.0.0",
"esbuild": "^0.25.5",
"typescript": "^5.8.3"
}
},
"node_modules/@frida/assert": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@frida/assert/-/assert-3.0.2.tgz",
"integrity": "sha512-JXJq5SbXGrM5EkjrZKfRmB29zOoEOix02NC6A5TSJ+C1GE/X051EinJJsuOO2pEOx7KZwpvAHvS0WXW0+levKg==",
"dev": true
},
"node_modules/@frida/base64-js": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@frida/base64-js/-/base64-js-2.0.3.tgz",
"integrity": "sha512-2w0F+1TynOTCZ/v7du9LdHPWwq0lJhazjo2fF9upMyQmA1zHetT14fLuQ1v/6T0qPgyeEGkiSrybstU8EsgeUA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/@frida/buffer": {
"version": "7.0.4",
"resolved": "https://registry.npmjs.org/@frida/buffer/-/buffer-7.0.4.tgz",
"integrity": "sha512-RxQ1lZRRiCJj7nhcCiD8xeJx0NsLpGGnjqsmTg7jShGmbnVFMN5W7+J+3gqdPSQhc/IxNBIWc6zRXVp4+qnYHg==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz",
"integrity": "sha512-9o3TMmpmftaCMepOdA5k/yDw8SfInyzWWTjYTFCX3kPSDJMROQTb8jg+h9Cnwnmm1vOzvxN7gIfB5V2ewpjtGA==",
"cpu": [
"ppc64"
],
"dependencies": {
"base64-js": "^1.5.1",
"ieee754": "^1.2.1"
}
},
"node_modules/@frida/crosspath": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@frida/crosspath/-/crosspath-3.0.0.tgz",
"integrity": "sha512-bNdO1spIPD2P40XtK89N49oZpJhstdlnkJZcD4yJ17jrdkm9Ctu0sd9MIEX6Z8Tm8ydhVJBAOMEKl9/R27onAQ==",
"dev": true,
"dependencies": {
"@types/node": "^17.0.36"
},
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=14.9.0"
"node": ">=18"
}
},
"node_modules/@frida/diagnostics_channel": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@frida/diagnostics_channel/-/diagnostics_channel-1.0.0.tgz",
"integrity": "sha512-mYX1jp/5Bpk24tHArJNx65iCk7qSuV8YJkdU0gFNVtJUXxfV8BG5WuPa4mL+ynxsbWWpsg/cwKZbLAepYKTdQQ==",
"dev": true
},
"node_modules/@frida/events": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/@frida/events/-/events-4.0.4.tgz",
"integrity": "sha512-qJVQ6VWHf9sjUKuiJzoCAC00frbpcwxeYfvQ+PP9LU/d70j+QvjWgYe98Qa3ekLaBU6r/AvWm8ThKCDUCLWrQQ==",
"node_modules/@esbuild/android-arm": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.5.tgz",
"integrity": "sha512-AdJKSPeEHgi7/ZhuIPtcQKr5RQdo6OO2IL87JkianiMYMPbCtot9fxPbrMiBADOWWm3T2si9stAiVsGbTQFkbA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=0.8.x"
"node": ">=18"
}
},
"node_modules/@frida/http": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@frida/http/-/http-4.0.2.tgz",
"integrity": "sha512-cvkc7ex7GmVXVOWqtjXKBWUUbYEBgpNRKZbEEoMeI8KiIs8zejKwg+N7rx7296Ao+EP3+xcUr4wBVr3xLaUVfQ==",
"node_modules/@esbuild/android-arm64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.5.tgz",
"integrity": "sha512-VGzGhj4lJO+TVGV1v8ntCZWJktV7SGCs3Pn1GRWI1SBFtRALoomm8k5E9Pmwg3HOAal2VDc2F9+PM/rEY6oIDg==",
"cpu": [
"arm64"
],
"dev": true,
"dependencies": {
"http-parser-js": "^0.5.3"
}
},
"node_modules/@frida/http-parser-js": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@frida/http-parser-js/-/http-parser-js-1.0.0.tgz",
"integrity": "sha512-2nMrNXt/OeTlWbqnE8AH4Sfz4I2+BGoN206dzKEyC/g2svtn83Xu+zuv/V3TkwrA27s26Mcy84ZwsXeNlqNxUQ==",
"dev": true
},
"node_modules/@frida/https": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@frida/https/-/https-1.0.0.tgz",
"integrity": "sha512-OiqQ6qsALcWOktRLq07oJ0i6sH8eX6MXb/MdZS1qVKDRf6wchH4Pjn6fiLB+pt/OlYbggk+DOfpHwSdjTwuHMQ==",
"dev": true
},
"node_modules/@frida/ieee754": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/@frida/ieee754/-/ieee754-2.0.2.tgz",
"integrity": "sha512-wlcUebnne4ENN7GDr5pTH598ZDLMVOsh0FjenxeVOe6u7ewZkz9gGRnLnZKJAm9kl5G6XhdxhI0cSXVQK/rQUw==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/@frida/net": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@frida/net/-/net-4.0.2.tgz",
"integrity": "sha512-qQRe7hQ+ZfCcG/SE3P1TRqQ9bmuK/T7wPCYaT4z56rBPWAxsaQbQHpX4fR6OrFaSDr7X0xJLsTbdIp9hGhhLZg==",
"dev": true
},
"node_modules/@frida/os": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@frida/os/-/os-1.0.2.tgz",
"integrity": "sha512-3ISAiGNiyIya3QN2EHBCz1wqP0enTdSxP99wUeroeh8+AQRmgoOr/5TRnrVry8pe378anay3fmV/tdUMMSkehQ==",
"dev": true
},
"node_modules/@frida/path": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@frida/path/-/path-2.0.3.tgz",
"integrity": "sha512-2RQy36QatoC846fzBhBhV8sXMsSOBGoYvwTHeaE1zUdz7F4RNScP4QEekTTooBYWYX/XjiF36KQpYAzc9OYFtg==",
"dev": true
},
"node_modules/@frida/process": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@frida/process/-/process-1.2.1.tgz",
"integrity": "sha512-nvCu22DstFW2ttGFtOKekHM7vnjbZm+XgtvavOt427GNT6uV7k0JYK9tnMbcLMRWv57DG6udAmuJlWs8Paq1ag==",
"dev": true
},
"node_modules/@frida/punycode": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@frida/punycode/-/punycode-3.0.0.tgz",
"integrity": "sha512-XVSDY2KamDs1D5/fTVgHcOSNxdU4kTboxzqJMBbTjcQC7XScIT9c0EfbwKCq7Kci6gWQdsHSCr7lU+9Oc4KAdg==",
"dev": true
},
"node_modules/@frida/querystring": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@frida/querystring/-/querystring-1.0.0.tgz",
"integrity": "sha512-15m1fOZPmoO/vWlgPJrG/J9/BJDz6a2/JpVGpS8ynNzo+fBhTznaStX5nHxUs24mVTqh/OqLo0EiYJM5WWHXxg==",
"dev": true
},
"node_modules/@frida/readable-stream": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/@frida/readable-stream/-/readable-stream-4.1.3.tgz",
"integrity": "sha512-ntGUFmi+CryRGRJIK13a/VST2Ad19uivbln8Xd92vKPAARq+6vMIASDyZIqyl5BLRccfiyCHdYgrgQ6RI5rUig==",
"dev": true
},
"node_modules/@frida/reserved-words": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@frida/reserved-words/-/reserved-words-1.0.0.tgz",
"integrity": "sha512-2yG/XxJlsGlk/mm6eZTb4OAaQEhkTI2qaFfZFtAsrA/XuCpuMWkS4y/guyBlsRu4hAuhK2HPmNM8+OLLK1zM9Q==",
"dev": true
},
"node_modules/@frida/stream": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@frida/stream/-/stream-1.0.2.tgz",
"integrity": "sha512-4OuaC1ztmEKgTq3WeBhsy8Oq+AwW9n9cYnvLklcC9jwD93AEwgbWpecLlxJCVuALvTMdhKPg0nQVfyGYP/i9Bw==",
"dev": true,
"dependencies": {
"@frida/readable-stream": "^4.1.3"
}
},
"node_modules/@frida/string_decoder": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@frida/string_decoder/-/string_decoder-2.0.0.tgz",
"integrity": "sha512-in371tYZMHQiW9HF5MS3JDw6Ao6tyBoq34UWy2rzOswYyMG1rpizh85ofi/yVkxDiaqybEZefxzkVittpPGT6g==",
"dev": true
},
"node_modules/@frida/terser": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@frida/terser/-/terser-1.0.0.tgz",
"integrity": "sha512-59h9WuNzD1Rx/zwoWqQ/FW/4Y/Q3R91Eng2hEwdHapqiTDvtKbZ08F6CynCR7ZVinrh4tLYsF46AtVPTz1ys9g==",
"dev": true,
"dependencies": {
"@jridgewell/source-map": "^0.3.2",
"acorn": "^8.5.0",
"commander": "^2.20.0",
"source-map-support": "~0.5.20"
},
"bin": {
"terser": "bin/terser"
},
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=10"
"node": ">=18"
}
},
"node_modules/@frida/terser/node_modules/commander": {
"version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
"dev": true
},
"node_modules/@frida/timers": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@frida/timers/-/timers-3.0.0.tgz",
"integrity": "sha512-3b+0igv10aT8TMxefrTAd06rActqbxJLY2Xkkq9vYcPBffB/yHszl0NYIp/5ko8WC3ecDYPU6bQiY6fjs72zTA==",
"dev": true
},
"node_modules/@frida/tty": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@frida/tty/-/tty-1.0.0.tgz",
"integrity": "sha512-p/kjLnKYxEAB1MdYP8+5rKv9CsHzyA+0jg9BcGETzjQVKHHcroHDULRxDYUh+DC7qs6cpX8QdDQh9E+a6ydgsQ==",
"dev": true
},
"node_modules/@frida/url": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@frida/url/-/url-1.0.2.tgz",
"integrity": "sha512-ZKunbKJHMr8w2Eb/5K1avy0MzK1B998S17wYXNv3RmzBGxMm8S5T0F3qEpRxkU7/72P8m4izyQU87fWl+FjQsQ==",
"node_modules/@esbuild/android-x64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.5.tgz",
"integrity": "sha512-D2GyJT1kjvO//drbRT3Hib9XPwQeWd9vZoBJn+bu/lVsOZ13cqNdDeqIF/xQ5/VmWvMduP6AmXvylO/PIc2isw==",
"cpu": [
"x64"
],
"dev": true,
"dependencies": {
"@frida/punycode": "^3.0.0",
"@frida/querystring": "^1.0.0"
}
},
"node_modules/@frida/util": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@frida/util/-/util-1.0.3.tgz",
"integrity": "sha512-htcG3uDiRXv89ERVNNYhfase39kJ2X75ZARfrYcYEtJLFEsSk0nemM1YnEIR4CjrHvdvkWHrwgKkS+acOyoNEg==",
"dev": true
},
"node_modules/@frida/vm": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@frida/vm/-/vm-2.0.0.tgz",
"integrity": "sha512-7fsjLWscZT5odNIBtg6qbLNI+vAk1xmii6H5W2kaYkMYt0vRohQEcDSUWacA+eaWlu5SvMjZI82Yibj/3G9pJw==",
"dev": true
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz",
"integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==",
"dev": true,
"dependencies": {
"@jridgewell/set-array": "^1.0.1",
"@jridgewell/sourcemap-codec": "^1.4.10",
"@jridgewell/trace-mapping": "^0.3.9"
},
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=6.0.0"
"node": ">=18"
}
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz",
"integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==",
"node_modules/@esbuild/darwin-arm64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.5.tgz",
"integrity": "sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=6.0.0"
"node": ">=18"
}
},
"node_modules/@jridgewell/set-array": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz",
"integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==",
"node_modules/@esbuild/darwin-x64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.5.tgz",
"integrity": "sha512-1iT4FVL0dJ76/q1wd7XDsXrSW+oLoquptvh4CLR4kITDtqi2e/xwXwdCVH8hVHU43wgJdsq7Gxuzcs6Iq/7bxQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=6.0.0"
"node": ">=18"
}
},
"node_modules/@jridgewell/source-map": {
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.3.tgz",
"integrity": "sha512-b+fsZXeLYi9fEULmfBrhxn4IrPlINf8fiNarzTof004v3lFdntdwa9PF7vFJqm3mg7s+ScJMxXaE3Acp1irZcg==",
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.5.tgz",
"integrity": "sha512-nk4tGP3JThz4La38Uy/gzyXtpkPW8zSAmoUhK9xKKXdBCzKODMc2adkB2+8om9BDYugz+uGV7sLmpTYzvmz6Sw==",
"cpu": [
"arm64"
],
"dev": true,
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.0",
"@jridgewell/trace-mapping": "^0.3.9"
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.4.15",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz",
"integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==",
"dev": true
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.18",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.18.tgz",
"integrity": "sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA==",
"node_modules/@esbuild/freebsd-x64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.5.tgz",
"integrity": "sha512-PrikaNjiXdR2laW6OIjlbeuCPrPaAl0IwPIaRv+SMV8CiM8i2LqVUHFC1+8eORgWyY7yhQY+2U2fA55mBzReaw==",
"cpu": [
"x64"
],
"dev": true,
"dependencies": {
"@jridgewell/resolve-uri": "3.1.0",
"@jridgewell/sourcemap-codec": "1.4.14"
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec": {
"version": "1.4.14",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz",
"integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==",
"dev": true
"node_modules/@esbuild/linux-arm": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.5.tgz",
"integrity": "sha512-cPzojwW2okgh7ZlRpcBEtsX7WBuqbLrNXqLU89GxWbNt6uIg78ET82qifUy3W6OVww6ZWobWub5oqZOVtwolfw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.5.tgz",
"integrity": "sha512-Z9kfb1v6ZlGbWj8EJk9T6czVEjjq2ntSYLY2cw6pAZl4oKtfgQuS4HOq41M/BcoLPzrUbNd+R4BXFyH//nHxVg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.5.tgz",
"integrity": "sha512-sQ7l00M8bSv36GLV95BVAdhJ2QsIbCuCjh/uYrWiMQSUuV+LpXwIqhgJDcvMTj+VsQmqAHL2yYaasENvJ7CDKA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.5.tgz",
"integrity": "sha512-0ur7ae16hDUC4OL5iEnDb0tZHDxYmuQyhKhsPBV8f99f6Z9KQM02g33f93rNH5A30agMS46u2HP6qTdEt6Q1kg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.5.tgz",
"integrity": "sha512-kB/66P1OsHO5zLz0i6X0RxlQ+3cu0mkxS3TKFvkb5lin6uwZ/ttOkP3Z8lfR9mJOBk14ZwZ9182SIIWFGNmqmg==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.5.tgz",
"integrity": "sha512-UZCmJ7r9X2fe2D6jBmkLBMQetXPXIsZjQJCjgwpVDz+YMcS6oFR27alkgGv3Oqkv07bxdvw7fyB71/olceJhkQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.5.tgz",
"integrity": "sha512-kTxwu4mLyeOlsVIFPfQo+fQJAV9mh24xL+y+Bm6ej067sYANjyEw1dNHmvoqxJUCMnkBdKpvOn0Ahql6+4VyeA==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.5.tgz",
"integrity": "sha512-K2dSKTKfmdh78uJ3NcWFiqyRrimfdinS5ErLSn3vluHNeHVnBAFWC8a4X5N+7FgVE1EjXS1QDZbpqZBjfrqMTQ==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.5.tgz",
"integrity": "sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.5.tgz",
"integrity": "sha512-pwHtMP9viAy1oHPvgxtOv+OkduK5ugofNTVDilIzBLpoWAM16r7b/mxBvfpuQDpRQFMfuVr5aLcn4yveGvBZvw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.5.tgz",
"integrity": "sha512-WOb5fKrvVTRMfWFNCroYWWklbnXH0Q5rZppjq0vQIdlsQKuw6mdSihwSo4RV/YdQ5UCKKvBy7/0ZZYLBZKIbwQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.5.tgz",
"integrity": "sha512-7A208+uQKgTxHd0G0uqZO8UjK2R0DDb4fDmERtARjSHWxqMTye4Erz4zZafx7Di9Cv+lNHYuncAkiGFySoD+Mw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.5.tgz",
"integrity": "sha512-G4hE405ErTWraiZ8UiSoesH8DaCsMm0Cay4fsFWOOUcz8b8rC6uCvnagr+gnioEjWn0wC+o1/TAHt+It+MpIMg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.5.tgz",
"integrity": "sha512-l+azKShMy7FxzY0Rj4RCt5VD/q8mG/e+mDivgspo+yL8zW7qEwctQ6YqKX34DTEleFAvCIUviCFX1SDZRSyMQA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.5.tgz",
"integrity": "sha512-O2S7SNZzdcFG7eFKgvwUEZ2VG9D/sn/eIiz8XRZ1Q/DO5a3s76Xv0mdBzVM5j5R639lXQmPmSo0iRpHqUUrsxw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.5.tgz",
"integrity": "sha512-onOJ02pqs9h1iMJ1PQphR+VZv8qBMQ77Klcsqv9CNW2w6yLqoURLcgERAIurY6QE63bbLuqgP9ATqajFLK5AMQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.5.tgz",
"integrity": "sha512-TXv6YnJ8ZMVdX+SXWVBo/0p8LTcrUYngpWjvm91TMjjBQii7Oz11Lw5lbDV5Y0TzuhSJHwiH4hEtC1I42mMS0g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@types/frida-gum": {
"version": "18.3.2",
"resolved": "https://registry.npmjs.org/@types/frida-gum/-/frida-gum-18.3.2.tgz",
"integrity": "sha512-bso8bJRxrhchNRrOMmT18st/THIdjzxFdcMtJ/gGSYSknJeerQ8ArBwBtlWt/f3pqVVs1Mz1Fg6lvUdjXswa+g==",
"dev": true
},
"node_modules/@types/node": {
"version": "17.0.45",
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.45.tgz",
"integrity": "sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==",
"dev": true
},
"node_modules/acorn": {
"version": "8.8.2",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz",
"integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==",
"version": "19.0.0",
"resolved": "https://registry.npmjs.org/@types/frida-gum/-/frida-gum-19.0.0.tgz",
"integrity": "sha512-qViK1KwvPEAkajwSUv0wpZvZLiX8xO4JFFCh8dfYZfzSyOEfoE0KliCP/nJSKIKG6N3hXnPowrvPufjs5fLKAA==",
"dev": true,
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.25.5",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.5.tgz",
"integrity": "sha512-P8OtKZRv/5J5hhz0cUAdu/cLuPIKXpQl1R9pZtvmHWQvrAUVd0UNIPT4IB4W3rNOqVO0rlqHmCIbSwxh/c9yUQ==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"dev": true
},
"node_modules/commander": {
"version": "9.5.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",
"integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",
"dev": true,
"engines": {
"node": "^12.20.0 || >=14"
}
},
"node_modules/frida-compile": {
"version": "16.2.1",
"resolved": "https://registry.npmjs.org/frida-compile/-/frida-compile-16.2.1.tgz",
"integrity": "sha512-be/U5h8l0cb0b+fWeZclhfw1s2xER8fPOjnTU4rZF8oh5GkB0BeAEaApwfGrdmeZkVNdUhDLXud7DqEljHRWmA==",
"dev": true,
"dependencies": {
"@frida/assert": "^3.0.1",
"@frida/base64-js": "^2.0.3",
"@frida/buffer": "^7.0.4",
"@frida/crosspath": "^3.0.0",
"@frida/diagnostics_channel": "^1.0.0",
"@frida/events": "^4.0.4",
"@frida/http": "^4.0.2",
"@frida/http-parser-js": "^1.0.0",
"@frida/https": "^1.0.0",
"@frida/ieee754": "^2.0.2",
"@frida/net": "^4.0.1",
"@frida/os": "^1.0.0",
"@frida/path": "^2.0.3",
"@frida/process": "^1.2.1",
"@frida/punycode": "^3.0.0",
"@frida/querystring": "^1.0.0",
"@frida/readable-stream": "^4.1.3",
"@frida/reserved-words": "^1.0.0",
"@frida/stream": "^1.0.2",
"@frida/string_decoder": "^2.0.0",
"@frida/terser": "^1.0.0",
"@frida/timers": "^3.0.0",
"@frida/tty": "^1.0.0",
"@frida/url": "^1.0.2",
"@frida/util": "^1.0.3",
"@frida/vm": "^2.0.0",
"commander": "^9.4.0",
"frida-fs": "^5.2.3",
"typed-emitter": "^2.1.0"
"node": ">=18"
},
"bin": {
"frida-compile": "dist/cli.js"
}
},
"node_modules/frida-fs": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/frida-fs/-/frida-fs-5.2.3.tgz",
"integrity": "sha512-jJhtNI86UqDkOtB72XR7Ia9KHudQUxIFIbZadS9kxrDU6Io1jLhoMNp++iW7n7MaDgFQLRR8VgNj9VViGzaydA==",
"dev": true
},
"node_modules/http-parser-js": {
"version": "0.5.8",
"resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.8.tgz",
"integrity": "sha512-SGeBX54F94Wgu5RH3X5jsDtf4eHyRogWX1XGT3b4HuW3tQPM4AaBzoUji/4AAJNXCEOWZ5O0DgZmJw1947gD5Q==",
"dev": true
},
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/rxjs": {
"version": "7.8.1",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz",
"integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==",
"dev": true,
"optional": true,
"dependencies": {
"tslib": "^2.1.0"
}
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"dev": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/source-map-support": {
"version": "0.5.21",
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
"integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
"dev": true,
"dependencies": {
"buffer-from": "^1.0.0",
"source-map": "^0.6.0"
}
},
"node_modules/tslib": {
"version": "2.5.2",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.2.tgz",
"integrity": "sha512-5svOrSA2w3iGFDs1HibEVBGbDrAY82bFQ3HZ3ixB+88nsbsWQoKqDRb5UBYAUPEzbBn6dAp5gRNXglySbx1MlA==",
"dev": true,
"optional": true
},
"node_modules/typed-emitter": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/typed-emitter/-/typed-emitter-2.1.0.tgz",
"integrity": "sha512-g/KzbYKbH5C2vPkaXGu8DJlHrGKHLsM25Zg9WuC9pMGfuvT+X25tZQWo5fK1BjBm8+UrVE9LDCvaY0CQk+fXDA==",
"dev": true,
"optionalDependencies": {
"rxjs": "*"
"@esbuild/aix-ppc64": "0.25.5",
"@esbuild/android-arm": "0.25.5",
"@esbuild/android-arm64": "0.25.5",
"@esbuild/android-x64": "0.25.5",
"@esbuild/darwin-arm64": "0.25.5",
"@esbuild/darwin-x64": "0.25.5",
"@esbuild/freebsd-arm64": "0.25.5",
"@esbuild/freebsd-x64": "0.25.5",
"@esbuild/linux-arm": "0.25.5",
"@esbuild/linux-arm64": "0.25.5",
"@esbuild/linux-ia32": "0.25.5",
"@esbuild/linux-loong64": "0.25.5",
"@esbuild/linux-mips64el": "0.25.5",
"@esbuild/linux-ppc64": "0.25.5",
"@esbuild/linux-riscv64": "0.25.5",
"@esbuild/linux-s390x": "0.25.5",
"@esbuild/linux-x64": "0.25.5",
"@esbuild/netbsd-arm64": "0.25.5",
"@esbuild/netbsd-x64": "0.25.5",
"@esbuild/openbsd-arm64": "0.25.5",
"@esbuild/openbsd-x64": "0.25.5",
"@esbuild/sunos-x64": "0.25.5",
"@esbuild/win32-arm64": "0.25.5",
"@esbuild/win32-ia32": "0.25.5",
"@esbuild/win32-x64": "0.25.5"
}
},
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
+7 -4
View File
@@ -2,12 +2,15 @@
"name": "frida-barebone-script-runtime",
"version": "1.0.0",
"description": "Script runtime used by Frida's Barebone backend",
"type": "module",
"scripts": {
"prepare": "npm run build",
"build": "frida-compile script-runtime/entrypoint.ts -o script-runtime.js -c"
"build": "esbuild script-runtime/entrypoint.ts --outfile=script-runtime.js --bundle --platform=node --target=es2022 --minify",
"check": "tsc",
"watch": "tsc -w"
},
"devDependencies": {
"@types/frida-gum": "^18.3.2",
"frida-compile": "^16.2.1"
"@types/frida-gum": "^19.0.0",
"esbuild": "^0.25.5",
"typescript": "^5.8.3"
}
}
+5 -21
View File
@@ -1,6 +1,6 @@
[CCode (gir_namespace = "FridaBarebone", gir_version = "1.0")]
namespace Frida.Barebone {
private class RustModule : Object {
private sealed class RustModule : Object {
public signal void console_output (string message);
public Gee.List<Export> exports {
@@ -208,7 +208,10 @@ namespace Frida.Barebone {
}
~CompilationAssets () {
rmtree (workdir);
try {
FS.rmtree (workdir);
} catch (Error e) {
}
}
private static string make_main_rs (string code, Machine machine) {
@@ -428,23 +431,4 @@ namespace Frida.Barebone {
yield file.replace_contents_async (content.data, null, false, FileCreateFlags.NONE, cancellable, null);
return file;
}
private void rmtree (File dir) {
try {
var enumerator = dir.enumerate_children (FileAttribute.STANDARD_NAME, NOFOLLOW_SYMLINKS);
FileInfo? info;
File? child;
while (enumerator.iterate (out info, out child) && info != null) {
if (info == null)
continue;
if (info.get_file_type () == DIRECTORY)
rmtree (child);
else
child.delete ();
}
dir.delete ();
} catch (GLib.Error e) {
}
}
}
+16 -20
View File
@@ -210,24 +210,6 @@ Object.defineProperties(globalThis, {
}
}
},
ObjC: {
enumerable: true,
value: {
available: false
}
},
Swift: {
enumerable: true,
value: {
available: false
}
},
Java: {
enumerable: true,
value: {
available: false
}
},
console: {
enumerable: true,
value: new Console()
@@ -278,6 +260,8 @@ Object.defineProperties(Process, {
base: NULL,
size: 0x1000,
path: "/kernel",
ensureInitialized() {
},
enumerateImports() {
return [];
},
@@ -290,11 +274,23 @@ Object.defineProperties(Process, {
enumerateRanges() {
return [];
},
enumerateSections() {
return [];
},
enumerateDependencies() {
return [];
},
findExportByName() {
return null;
},
getExportByName(exportName) {
throw new Error(`unable to find export '${exportName}'`);
getExportByName(name) {
throw new Error(`unable to find export '${name}'`);
},
findSymbolByName() {
return null;
},
getSymbolByName(name) {
throw new Error(`unable to find symbol '${name}'`);
}
}
];
+166 -40
View File
@@ -1,5 +1,5 @@
namespace Frida {
private class BareboneScript : Object {
private sealed class BareboneScript : Object {
public signal void message (string json, Bytes? data);
public AgentScriptId id {
@@ -72,7 +72,7 @@ namespace Frida {
private QuickJS.Value int64_func = QuickJS.Undefined;
private QuickJS.Value uint64_func = QuickJS.Undefined;
private Gee.ArrayList<QuickJS.Value?> entrypoints = new Gee.ArrayList<QuickJS.Value?> ();
private Gee.Queue<Entrypoint> entrypoints = new Gee.ArrayQueue<Entrypoint> ();
private Gee.Map<string, Asset> assets = new Gee.HashMap<string, Asset> ();
private Cancellable io_cancellable = new Cancellable ();
@@ -328,6 +328,8 @@ namespace Frida {
foreach (var val in values)
ctx.free_value (val);
entrypoints.clear ();
QuickJS.Atom atoms[] = {
address_key,
base_key,
@@ -376,51 +378,70 @@ namespace Frida {
yield;
}
public void load () {
foreach (QuickJS.Value? entrypoint in entrypoints) {
var result = ctx.eval_function (entrypoint);
if (result.is_exception ())
public async void load (Cancellable? cancellable) throws IOError {
Entrypoint? entrypoint;
while ((entrypoint = entrypoints.poll ()) != null) {
var result = ctx.eval_function (ctx.dup_value (entrypoint.callable));
if (result.is_exception ()) {
catch_and_emit ();
ctx.free_value (result);
if (runtime_obj.is_undefined ()) {
runtime_obj = global.get_property_str (ctx, "$rt");
if (!runtime_obj.is_undefined ()) {
dispatch_exception_func = runtime_obj.get_property_str (ctx, "dispatchException");
assert (!dispatch_exception_func.is_undefined ());
dispatch_message_func = runtime_obj.get_property_str (ctx, "dispatchMessage");
assert (!dispatch_message_func.is_undefined ());
var native_pointer_instance = global.get_property_str (ctx, "NULL");
assert (!native_pointer_instance.is_undefined ());
var native_pointer_proto = native_pointer_instance.get_prototype (ctx);
var ir_proto = ctx.make_object_proto (native_pointer_proto);
add_cfunc (ir_proto, "replace", on_invocation_retval_replace, 1);
ctx.set_class_proto (invocation_retval_class, ir_proto);
ctx.free_value (native_pointer_proto);
ctx.free_value (native_pointer_instance);
ptr_func = global.get_property_str (ctx, "ptr");
assert (!ptr_func.is_undefined ());
int64_func = global.get_property_str (ctx, "int64");
assert (!int64_func.is_undefined ());
uint64_func = global.get_property_str (ctx, "uint64");
assert (!uint64_func.is_undefined ());
}
continue;
}
if (entrypoint.kind == ESM) {
var op = new PromiseWaitOperation (this, result);
var r = yield op.perform (cancellable);
if (!r.error.is_null ())
on_unhandled_exception (r.error);
} else {
ctx.free_value (result);
}
maybe_bind_runtime ();
}
perform_pending_io ();
}
private void maybe_bind_runtime () {
if (!runtime_obj.is_undefined ())
return;
runtime_obj = global.get_property_str (ctx, "$rt");
if (runtime_obj.is_undefined ())
return;
dispatch_exception_func = runtime_obj.get_property_str (ctx, "dispatchException");
assert (!dispatch_exception_func.is_undefined ());
dispatch_message_func = runtime_obj.get_property_str (ctx, "dispatchMessage");
assert (!dispatch_message_func.is_undefined ());
var native_pointer_instance = global.get_property_str (ctx, "NULL");
assert (!native_pointer_instance.is_undefined ());
var native_pointer_proto = native_pointer_instance.get_prototype (ctx);
var ir_proto = ctx.make_object_proto (native_pointer_proto);
add_cfunc (ir_proto, "replace", on_invocation_retval_replace, 1);
ctx.set_class_proto (invocation_retval_class, ir_proto);
ctx.free_value (native_pointer_proto);
ctx.free_value (native_pointer_instance);
ptr_func = global.get_property_str (ctx, "ptr");
assert (!ptr_func.is_undefined ());
int64_func = global.get_property_str (ctx, "int64");
assert (!int64_func.is_undefined ());
uint64_func = global.get_property_str (ctx, "uint64");
assert (!uint64_func.is_undefined ());
}
public void post (string json, Bytes? data) {
var json_val = ctx.make_string (json);
invoke_void (dispatch_message_func, { json_val }, runtime_obj);
var data_val = (data != null) ? ctx.make_array_buffer (data.get_data ()) : QuickJS.Null;
invoke_void (dispatch_message_func, { json_val, data_val }, runtime_obj);
ctx.free_value (data_val);
ctx.free_value (json_val);
perform_pending_io ();
@@ -493,7 +514,7 @@ namespace Frida {
throw_malformed_package ();
var val = compile_module (entrypoint);
entrypoints.add (val);
entrypoints.offer (new Entrypoint (this, val, ESM));
string rest = raw_assets[assets_offset:];
if (rest.has_prefix (delimiter_marker))
@@ -505,7 +526,7 @@ namespace Frida {
}
} else {
var val = compile_script (source, name);
entrypoints.add (val);
entrypoints.offer (new Entrypoint (this, val, PLAIN));
}
}
@@ -706,6 +727,111 @@ namespace Frida {
}
}
private class Entrypoint {
private weak BareboneScript script;
public QuickJS.Value callable;
public Kind kind;
public enum Kind {
PLAIN,
ESM
}
public Entrypoint (BareboneScript script, QuickJS.Value callable, Kind kind) {
this.script = script;
this.callable = callable;
this.kind = kind;
}
~Entrypoint () {
script.ctx.free_value (callable);
}
}
private class PromiseWaitOperation {
private BareboneScript script;
private QuickJS.Value promise;
private enum Magic {
ON_SUCCESS,
ON_FAILURE,
}
public PromiseWaitOperation (BareboneScript script, QuickJS.Value promise) {
this.script = script;
this.promise = promise;
}
~PromiseWaitOperation () {
script.ctx.free_value (promise);
}
public async Result perform (Cancellable? cancellable) throws IOError {
var res = new Result (script, perform.callback);
unowned QuickJS.Context ctx = script.ctx;
var data = ctx.make_object ();
data.set_opaque (res);
var on_success = ctx.make_cfunction_data (on_settled, 1, Magic.ON_SUCCESS, { data });
var on_failure = ctx.make_cfunction_data (on_settled, 1, Magic.ON_FAILURE, { data });
var then_func = promise.get_property_str (ctx, "then");
var catch_func = promise.get_property_str (ctx, "catch");
ctx.free_value (then_func.call (ctx, promise, { on_success }));
ctx.free_value (catch_func.call (ctx, promise, { on_failure }));
ctx.free_value (catch_func);
ctx.free_value (then_func);
ctx.free_value (on_failure);
ctx.free_value (on_success);
script.perform_pending_io ();
yield;
return res;
}
private static QuickJS.Value on_settled (QuickJS.Context ctx, QuickJS.Value this_val, QuickJS.Value[] argv, int magic,
QuickJS.Value[] data) {
QuickJS.ClassID cid;
unowned Result res = (Result) data[0].get_any_opaque (out cid);
if (magic == Magic.ON_SUCCESS)
res.val = ctx.dup_value (argv[0]);
else
res.error = ctx.dup_value (argv[0]);
var source = new IdleSource ();
source.set_callback ((owned) res.on_complete);
source.attach (MainContext.get_thread_default ());
return QuickJS.Undefined;
}
public class Result {
public BareboneScript script;
public SourceFunc on_complete;
public QuickJS.Value val = QuickJS.Null;
public QuickJS.Value error = QuickJS.Null;
public Result (BareboneScript script, owned SourceFunc on_complete) {
this.script = script;
this.on_complete = (owned) on_complete;
}
~Result () {
unowned QuickJS.Context ctx = script.ctx;
ctx.free_value (val);
ctx.free_value (error);
}
}
}
private class NativeCallbackHandler : Object, Barebone.CallbackHandler {
public uint arity {
get { return _arity; }
+10
View File
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "Node16",
"strict": true,
"noEmit": true
},
"include": ["script-runtime/**/*.ts"]
}
-469
View File
@@ -1,469 +0,0 @@
import * as crosspath from "@frida/crosspath";
import type * as backend from "frida-compile";
import {
makeDefaultCompilerOptions,
build as _build,
watch as _watch,
queryDefaultAssets as _queryDefaultAssets,
} from "frida-compile";
import ts from "frida-compile/ext/typescript.js";
import fridaFs from "frida-fs";
import fs from "fs";
const { DiagnosticCategory, FileWatcherEventKind } = ts;
const { S_IFDIR } = fs.constants;
export const compilerRoot = "/frida-compile";
export const compilerNodeModules = compilerRoot + "/node_modules";
export const agentDirectories = new Set<string>(__agentDirectories__);
export const agentFiles = new Map<string, string>(__agentFiles__);
const cachedSourceFiles = new Map<string, ts.SourceFile>();
declare const __agentDirectories__: string[];
declare const __agentFiles__: [string, string][];
const pendingDiagnostics: ts.Diagnostic[] = [];
const fileWatchers = new Map<WatcherId, WatcherCallback>();
let nextWatcherId: WatcherId = 1;
populateSourceFileCache();
function populateSourceFileCache() {
const config = makeDefaultCompilerOptions();
for (const [name, contents] of agentFiles) {
if (name.endsWith(".d.ts")) {
const sf = ts.createSourceFile(name, contents, config.target!);
ts.prebindSourceFile(sf, config);
cachedSourceFiles.set(name, sf);
}
}
}
export function init(): void {
function onChange(message: WatchChangeMessage): void {
const callback = fileWatchers.get(message.id);
callback?.(fileWatcherEventKindFromFileState(message.state));
recv("watch:change", onChange);
}
recv("watch:change", onChange);
const origCreateCompilerHostFromProgramHost = (ts as any).createCompilerHostFromProgramHost;
(ts as any).createCompilerHostFromProgramHost = (...args: any[]): ts.CompilerHost => {
const host = origCreateCompilerHostFromProgramHost(...args);
patchCompilerHost(host);
return host;
};
}
export function build(projectRoot: string, entrypoint: string, sourceMaps: backend.SourceMaps, compression: backend.Compression): string {
const system = new FridaSystem(projectRoot);
const assets = _queryDefaultAssets(projectRoot, system);
try {
return _build({
projectRoot,
entrypoint,
assets,
system,
sourceMaps,
compression,
onDiagnostic,
onCompilerHostCreated: patchCompilerHost,
});
} finally {
flushDiagnostics();
}
}
export function watch(projectRoot: string, entrypoint: string, sourceMaps: backend.SourceMaps, compression: backend.Compression): void {
const system = new FridaSystem(projectRoot);
const assets = _queryDefaultAssets(projectRoot, system);
_watch({
projectRoot,
entrypoint,
assets,
system,
sourceMaps,
compression,
onDiagnostic,
})
.on("compilationStarting", () => {
send(["watch:compilation-starting"]);
})
.on("compilationFinished", () => {
send(["watch:compilation-finished"]);
})
.on("bundleUpdated", bundle => {
send(["watch:bundle-updated", bundle]);
});
}
function patchCompilerHost(host: ts.CompilerHost) {
const origGetSourceFile = host.getSourceFile;
host.getSourceFile = (fileName, ...args) => {
const compilerPath = nativePathToCompilerPath(fileName);
if (compilerPath !== null) {
const sf = cachedSourceFiles.get(compilerPath);
if (sf !== undefined) {
return sf;
}
} else {
const startPos = fileName.indexOf("/node_modules/@types/");
if (startPos !== -1) {
const builtinsPath = fileName.substring(startPos);
const sf = cachedSourceFiles.get(builtinsPath);
if (sf !== undefined) {
let allowCache = true;
if (builtinsPath.startsWith("/node_modules/@types/frida-gum/")) {
try {
const hashOnDisk = Checksum.compute("sha256", File.readAllText(fileName));
const hashInCache = Checksum.compute("sha256", agentFiles.get(sf.fileName)!);
allowCache = hashOnDisk === hashInCache;
} catch (e) {
}
}
if (allowCache) {
return sf;
}
}
}
}
return origGetSourceFile(fileName, ...args);
};
}
export { _build, _watch, _queryDefaultAssets };
type DiagnosticFile = [path: string, line: number, character: number];
function onDiagnostic(diagnostic: ts.Diagnostic): void {
pendingDiagnostics.push(diagnostic);
if (pendingDiagnostics.length === 1) {
Script.nextTick(flushDiagnostics);
}
}
function flushDiagnostics(): void {
const pending = pendingDiagnostics.splice(0, pendingDiagnostics.length);
if (pending.length === 0) {
return;
}
send([
"diagnostics",
pending.map(({
category,
code,
file: tsFile,
start,
messageText
}) => {
let file: DiagnosticFile | null = null;
if (tsFile !== undefined) {
const { line, character } = ts.getLineAndCharacterOfPosition(tsFile, start!);
file = [tsFile.fileName, line, character];
}
return [
diagnosticCategoryToString(category),
code,
file,
ts.flattenDiagnosticMessageText(messageText, "\n")
];
}),
]);
}
function diagnosticCategoryToString(category: ts.DiagnosticCategory): string {
switch (category) {
case DiagnosticCategory.Warning:
return "warning";
case DiagnosticCategory.Error:
return "error";
case DiagnosticCategory.Suggestion:
return "suggestion";
case DiagnosticCategory.Message:
return "message";
}
}
class FridaSystem implements ts.System {
args = [];
newLine = "\n";
useCaseSensitiveFileNames = true;
#projectRoot: string;
#projectNodeModules: string;
constructor(projectRoot: string) {
this.#projectRoot = crosspath.ensurePosix(projectRoot);
this.#projectNodeModules = crosspath.join(this.#projectRoot, "node_modules");
}
write(s: string): void {
}
writeOutputIsTTY(): boolean {
return true;
}
readFile(path: string, encoding?: string): string | undefined {
let result: string | undefined;
if (path.startsWith(this.#projectRoot)) {
try {
result = File.readAllText(path);
} catch (e) {
}
}
if (result === undefined) {
const agentZipPath = this.#nativePathToAgentZipPath(path);
if (agentZipPath !== null) {
result = agentFiles.get(agentZipPath);
}
}
return result;
}
getFileSize(path: string): number {
throw new Error("not implemented");
}
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void {
File.writeAllText(path, data);
}
watchFile(path: string, callback: ts.FileWatcherCallback, pollingInterval?: number, options?: ts.WatchOptions): ts.FileWatcher {
if (path.startsWith(compilerRoot)) {
return makeDummyWatcher();
}
return makeFileWatcher(path, "file", pollingInterval ?? 0, kind => {
callback(path, kind);
});
}
watchDirectory(path: string, callback: ts.DirectoryWatcherCallback, recursive?: boolean, options?: ts.WatchOptions): ts.FileWatcher {
if (path.startsWith(compilerRoot)) {
return makeDummyWatcher();
}
return makeFileWatcher(path, "directory", 0, kind => {
callback(path);
});
}
resolvePath(path: string): string {
return path;
}
fileExists(path: string): boolean {
if (path.startsWith(this.#projectRoot)) {
try {
const st = fs.statSync(path);
return !st.isDirectory();
} catch (e) {
}
}
const agentZipPath = this.#nativePathToAgentZipPath(path);
if (agentZipPath === null) {
return false;
}
return agentFiles.has(agentZipPath);
}
directoryExists(path: string): boolean {
if (path === compilerNodeModules) {
return true;
}
if (path.startsWith(this.#projectRoot)) {
try {
const st = fs.statSync(path);
return st.isDirectory();
} catch (e) {
}
}
const agentZipPath = this.#nativePathToAgentZipPath(path);
if (agentZipPath === null) {
return false;
}
return agentDirectories.has(agentZipPath);
}
createDirectory(path: string): void {
throw new Error("not implemented");
}
getExecutingFilePath(): string {
return [compilerRoot, "ext", "typescript.js"].join("/");
}
getCurrentDirectory(): string {
return this.#projectRoot;
}
getDirectories(path: string): string[] {
const result = new Set<string>();
if (path.startsWith(this.#projectRoot)) {
try {
for (const entry of fridaFs.list(path).filter(entry => entry.type === S_IFDIR)) {
result.add(entry.name);
}
} catch (e) {
}
}
const agentZipPath = this.#nativePathToAgentZipPath(path);
if (agentZipPath !== null) {
for (const dir of agentDirectories) {
const slashIndex = dir.lastIndexOf("/");
const parent = dir.substring(0, slashIndex);
if (parent === agentZipPath) {
const basename = dir.substring(slashIndex + 1);
result.add(basename);
}
}
}
return Array.from(result);
}
readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[] {
return [];
}
getModifiedTime(path: string): Date | undefined {
return undefined;
}
setModifiedTime(path: string, time: Date): void {
}
deleteFile(path: string): void {
}
createHash(data: string): string {
return this.createSHA256Hash(data);
}
createSHA256Hash(data: string): string {
return Checksum.compute("sha256", data);
}
getMemoryUsage(): number {
return Frida.heapSize;
}
exit(exitCode?: number): void {
}
realpath(path: string): string {
return path;
}
getEnvironmentVariable(name: string): string {
return "";
}
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any {
return setTimeout(callback);
}
clearTimeout(timeoutId: any): void {
return clearTimeout(timeoutId);
}
clearScreen(): void {
}
base64decode(input: string): string {
throw new Error("not implemented");
}
base64encode(input: string): string {
throw new Error("not implemented");
}
#nativePathToAgentZipPath(path: string): string | null {
const compilerPath = nativePathToCompilerPath(path);
if (compilerPath !== null) {
return compilerPath;
}
if (path.startsWith(this.#projectNodeModules)) {
return "/node_modules" + path.substring(this.#projectNodeModules.length);
}
return null;
}
}
function nativePathToCompilerPath(path: string): string | null {
if (!path.startsWith(compilerRoot)) {
return null;
}
const subPath = path.substring(compilerRoot.length);
if (subPath.startsWith("/node_modules")) {
return subPath;
}
return "/node_modules/frida-compile" + subPath;
}
type WatcherId = number;
type WatcherCallback = (eventKind: ts.FileWatcherEventKind) => void;
type FileState = "pristine" | "modified" | "deleted";
interface WatchChangeMessage {
id: WatcherId;
state: FileState;
}
function makeFileWatcher(path: string, type: "file" | "directory", pollingInterval: number, callback: WatcherCallback): ts.FileWatcher {
if (nextWatcherId === 0xffffffff) {
nextWatcherId = 1;
}
let id: WatcherId = nextWatcherId++;
while (fileWatchers.has(id)) {
id = nextWatcherId++;
}
fileWatchers.set(id, callback);
send(["watch:add", id, path, type, pollingInterval ?? 0]);
return {
close() {
send(["watch:remove", id]);
fileWatchers.delete(id);
}
};
}
function makeDummyWatcher(): ts.FileWatcher {
return {
close() {
}
};
}
function fileWatcherEventKindFromFileState(state: FileState): ts.FileWatcherEventKind {
switch (state) {
case "pristine": return FileWatcherEventKind.Created;
case "modified": return FileWatcherEventKind.Changed;
case "deleted": return FileWatcherEventKind.Deleted;
}
}
-5
View File
@@ -1,5 +0,0 @@
const { init, build, watch } = FridaCompilerAgentCore;
init();
rpc.exports = { build, watch };
-222
View File
@@ -1,222 +0,0 @@
const {
compilerRoot,
compilerNodeModules,
agentDirectories,
agentFiles,
_build,
_queryDefaultAssets,
} = FridaCompilerAgentCore;
const projectRoot = '/agent';
const projectNodeModules = '/agent/node_modules';
const entrypoint = 'index.ts';
const sourceMaps = 'included';
const compression = 'none';
const hashes = new Map();
let nextHashId = 1;
function main() {
const system = new StubSystem();
const assets = _queryDefaultAssets(projectRoot, system);
_build({
projectRoot,
entrypoint,
assets,
system,
sourceMaps,
compression,
onDiagnostic,
});
}
function onDiagnostic(diagnostic) {
throwNotImplemented('diagnostic', ts.flattenDiagnosticMessageText(diagnostic, '\n'));
}
class StubSystem {
args = [];
newLine = '\n';
useCaseSensitiveFileNames = true;
write(s) {
}
writeOutputIsTTY() {
return true;
}
readFile(path, encoding) {
if (path === '/agent/tsconfig.json')
return '{}';
if (path === '/agent/index.ts')
return 'Interceptor.attach(ptr(1234), { onEnter(args) {} });'
const agentZipPath = this.#nativePathToAgentZipPath(path);
if (agentZipPath !== null) {
return agentFiles.get(agentZipPath);
}
throwNotImplemented('readFile', path);
}
getFileSize(path) {
throwNotImplemented('getFileSize');
}
writeFile(path, data, writeByteOrderMark) {
throwNotImplemented('writeFile');
}
watchFile(path, callback, pollingInterval, options) {
throwNotImplemented('watchFile');
}
watchDirectory(path, callback, recursive, options) {
throwNotImplemented('watchDirectory');
}
resolvePath(path) {
throwNotImplemented('resolvePath');
}
fileExists(path) {
if (path === '/package.json' || path === '/agent/package.json')
return false;
const agentZipPath = this.#nativePathToAgentZipPath(path);
if (agentZipPath !== null)
return agentFiles.has(agentZipPath);
throwNotImplemented('fileExists', path);
}
directoryExists(path) {
if (path === '/' || path === projectRoot || path === compilerNodeModules)
return true;
const agentZipPath = this.#nativePathToAgentZipPath(path);
if (agentZipPath !== null)
return agentDirectories.has(agentZipPath);
if (path === '/node_modules/@types' || path === '/node_modules')
return false;
throwNotImplemented('directoryExists', path);
}
createDirectory(path) {
throwNotImplemented('createDirectory');
}
getExecutingFilePath() {
return [compilerRoot, 'ext', 'typescript.js'].join('/');
}
getCurrentDirectory() {
return '/';
}
getDirectories(path) {
const agentZipPath = this.#nativePathToAgentZipPath(path);
if (agentZipPath !== null) {
const result = [];
for (const dir of agentDirectories) {
const slashIndex = dir.lastIndexOf('/');
const parent = dir.substring(0, slashIndex);
if (parent === agentZipPath) {
const basename = dir.substring(slashIndex + 1);
result.push(basename);
}
}
return result;
}
throwNotImplemented('getDirectories', path);
}
readDirectory(path, extensions, exclude, include, depth) {
if (!extensions.includes('.ts'))
throwNotImplemented('readDirectory', path, extensions);
return ['index.ts'];
}
getModifiedTime(path) {
}
setModifiedTime(path, time) {
}
deleteFile(path) {
}
createHash(data) {
let hash = hashes.get(data);
if (hash === undefined) {
hash = 'hash' + nextHashId++;
hashes.set(data, hash);
}
return hash;
}
createSHA256Hash(data) {
throwNotImplemented('createSHA256Hash');
}
getMemoryUsage() {
throwNotImplemented('getMemoryUsage');
}
exit(exitCode) {
}
realpath(path) {
return path;
}
getEnvironmentVariable(name) {
return '';
}
setTimeout(callback, ms, ...args) {
throwNotImplemented('setTimeout');
}
clearTimeout(timeoutId) {
throwNotImplemented('clearTimeout');
}
clearScreen() {
}
base64decode(input) {
throwNotImplemented('base64decode');
}
base64encode(input) {
throwNotImplemented('base64encode');
}
#nativePathToAgentZipPath(path) {
if (path.startsWith(compilerRoot)) {
const subPath = path.substring(compilerRoot.length);
if (subPath.startsWith('/node_modules')) {
return subPath;
}
return '/node_modules/frida-compile' + subPath;
}
if (path.startsWith(projectNodeModules)) {
return '/node_modules' + path.substring(projectNodeModules.length);
}
return null;
}
}
function throwNotImplemented(operation, ...details) {
throw new Error('not implemented: ' + operation + ((details.length > 0) ? ` (${details.join(' ')})` : ''));
}
main();
+28
View File
@@ -0,0 +1,28 @@
#ifdef _MSC_VER
#include <glib.h>
#ifdef HAVE_ARM64
# define FRIDA_CGO_INIT_FUNC _st0_arm64_windows_lib
#elif GLIB_SIZEOF_VOID_P == 8
# define FRIDA_CGO_INIT_FUNC _st0_amd64_windows_lib
#else
# define FRIDA_CGO_INIT_FUNC st0_386_windows_lib
#endif
extern void FRIDA_CGO_INIT_FUNC ();
void
_frida_compiler_backend_init_go_runtime (void)
{
FRIDA_CGO_INIT_FUNC ();
}
#else
void
_frida_compiler_backend_init_go_runtime (void)
{
}
#endif
+816
View File
@@ -0,0 +1,816 @@
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"
)
type BuildOptions struct {
ProjectRoot string
Entrypoint string
OutputFormat OutputFormat
BundleFormat BundleFormat
DisableTypeCheck bool
SourceMap bool
Compress bool
}
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
path string
line, character int
text string
}
type BuildEventCallbacks struct {
OnStart BuildStartCallback
OnEnd BuildEndCallback
OnOutput BuildOutputCallback
OnDiagnostic BuildDiagnosticCallback
OnConfigChange ConfigChangeCallback
}
type BuildStartCallback func()
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,
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,
}
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,
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,
}
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 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) {
bundle = b
},
OnDiagnostic: onDiagnostic,
}
ctx, err := makeContext(options, callbacks)
if err != nil {
return
}
defer ctx.Dispose()
result := ctx.Rebuild()
if len(result.Errors) != 0 {
err = fmt.Errorf("Compilation failed")
}
return
}
type WatchSession struct {
mu sync.Mutex
options BuildOptions
callbacks BuildEventCallbacks
ctx esbuild.BuildContext
onDispose SessionDisposeHandler
}
type SessionDisposeHandler func()
func NewWatchSession(opts BuildOptions, onDispose SessionDisposeHandler, callbacks BuildEventCallbacks) (session *WatchSession, err error) {
cbs := BuildEventCallbacks{
OnStart: callbacks.OnStart,
OnEnd: callbacks.OnEnd,
OnOutput: callbacks.OnOutput,
OnDiagnostic: callbacks.OnDiagnostic,
OnConfigChange: func() {
if callbacks.OnConfigChange != nil {
callbacks.OnConfigChange()
}
session.onConfigChange()
},
}
ctx, err := makeContext(opts, cbs)
if err != nil {
return
}
ctx.Watch(esbuild.WatchOptions{})
session = &WatchSession{
options: opts,
callbacks: cbs,
ctx: ctx,
onDispose: onDispose,
}
return
}
func (s *WatchSession) Dispose() {
s.mu.Lock()
defer s.mu.Unlock()
if s.ctx != nil {
s.ctx.Dispose()
s.ctx = nil
}
s.onDispose()
}
func (s *WatchSession) onConfigChange() {
go func() {
s.mu.Lock()
defer s.mu.Unlock()
if s.ctx != nil {
s.ctx.Dispose()
s.ctx = nil
}
ctx, err := makeContext(s.options, s.callbacks)
if err != nil {
return
}
s.ctx = ctx
ctx.Watch(esbuild.WatchOptions{})
}()
}
func makeContext(options BuildOptions, callbacks BuildEventCallbacks) (ctx esbuild.BuildContext, err error) {
var e error
var projectRoot string
if projectRoot, e = filepath.EvalSymlinks(options.ProjectRoot); e != nil {
err = fmt.Errorf("Failed to resolve project root: %w", e)
return
}
var entrypoint string
if filepath.IsAbs(options.Entrypoint) {
entrypoint = options.Entrypoint
} else {
entrypoint = filepath.Join(projectRoot, options.Entrypoint)
}
if entrypoint, e = filepath.EvalSymlinks(entrypoint); e != nil {
err = fmt.Errorf("Failed to resolve entrypoint: %w", e)
return
}
rel, e := filepath.Rel(projectRoot, entrypoint)
if e != nil {
err = fmt.Errorf("Could not compute entrypoint path relative to project root: %w", e)
return
}
if strings.HasPrefix(rel, "..") {
err = fmt.Errorf("Entrypoint must be inside the project root")
return
}
isTS := strings.HasSuffix(entrypoint, ".ts")
var tsconfigCache *TSConfigCache
var tsconfigText string
var tsCompiler *TSCompiler
if isTS {
tsconfigCache = NewTSConfigCache(projectRoot, options.SourceMap, callbacks.OnConfigChange)
tsCompiler = NewTSCompiler(projectRoot, entrypoint, tsconfigCache.GetCompilerOptions)
_, tsconfigText, err = tsconfigCache.GetCompilerOptions(tsCompiler)
if err != nil {
err = fmt.Errorf("Failed to load tsconfig options: %w", err)
return
}
}
sourcemapOption := esbuild.SourceMapNone
if options.SourceMap {
if options.BundleFormat == BundleFormatESM {
sourcemapOption = esbuild.SourceMapExternal
} else {
sourcemapOption = esbuild.SourceMapInline
}
}
minifyWhitespace := false
minifyIdentifiers := false
minifySyntax := false
if options.Compress {
minifyWhitespace = true
minifyIdentifiers = true
minifySyntax = true
}
var format esbuild.Format
if options.BundleFormat == BundleFormatESM {
format = esbuild.FormatESModule
} else {
format = esbuild.FormatIIFE
}
plugins := []esbuild.Plugin{
makeBuildObserverPlugin(projectRoot, entrypoint, options, callbacks),
}
if isTS && !options.DisableTypeCheck {
plugins = append(plugins, makeTypeScriptPlugin(tsCompiler))
}
plugins = append(plugins, makeFridaShimsPlugin())
buildOpts := esbuild.BuildOptions{
Sourcemap: sourcemapOption,
SourcesContent: esbuild.SourcesContentExclude,
Target: esbuild.ES2022,
MinifyWhitespace: minifyWhitespace,
MinifyIdentifiers: minifyIdentifiers,
MinifySyntax: minifySyntax,
LegalComments: esbuild.LegalCommentsNone,
Bundle: true,
Outdir: projectRoot,
AbsWorkingDir: projectRoot,
Platform: esbuild.PlatformNode,
Format: format,
Inject: []string{"frida-builtins:///node-globals.js"},
EntryPoints: []string{entrypoint},
Write: false,
Plugins: plugins,
}
if isTS {
buildOpts.TsconfigRaw = tsconfigText
}
if buildCtx, ctxErr := esbuild.Context(buildOpts); ctxErr == nil {
ctx = buildCtx
} else {
for _, e := range ctxErr.Errors {
emitDiagnostic("error", e, callbacks.OnDiagnostic)
}
err = fmt.Errorf("Failed to create ESBuild context")
}
return
}
func emitDiagnostic(category string, message esbuild.Message, onDiagnostic BuildDiagnosticCallback) {
d := Diagnostic{
category: category,
code: -1,
text: message.Text,
}
l := message.Location
if l != nil {
d.path = l.File
d.line = l.Line
d.character = l.Column
}
if message.PluginName == "frida-custom-ts" && len(message.Notes) == 2 {
d.category = message.Notes[0].Text
fmt.Sscan(message.Notes[1].Text, &d.code)
}
onDiagnostic(d)
}
func changeToJS(p string) string {
ext := path.Ext(p)
base := p[:len(p)-len(ext)]
return base + ".js"
}
func makeBuildObserverPlugin(projectRoot, entrypoint string, options BuildOptions, callbacks BuildEventCallbacks) esbuild.Plugin {
return esbuild.Plugin{
Name: "frida-build-observer",
Setup: func(build esbuild.PluginBuild) {
if callbacks.OnStart != nil {
build.OnStart(func() (esbuild.OnStartResult, error) {
callbacks.OnStart()
return esbuild.OnStartResult{}, nil
})
}
build.OnEnd(func(result *esbuild.BuildResult) (esbuild.OnEndResult, error) {
if len(result.Errors) == 0 {
var output string
if options.BundleFormat == BundleFormatESM {
output = makeESMBundle(result.OutputFiles, projectRoot, entrypoint)
} else {
output = string(result.OutputFiles[0].Contents)
}
switch options.OutputFormat {
case OutputFormatHexBytes:
output = encodeStringToHexBytes(output)
case OutputFormatCString:
output = encodeStringToCString(output)
}
callbacks.OnOutput(output)
} else {
for _, e := range result.Errors {
emitDiagnostic("error", e, callbacks.OnDiagnostic)
}
for _, e := range result.Warnings {
emitDiagnostic("warning", e, callbacks.OnDiagnostic)
}
}
if callbacks.OnEnd != nil {
callbacks.OnEnd()
}
return esbuild.OnEndResult{}, nil
})
},
}
}
func makeESMBundle(files []esbuild.OutputFile, projectRoot, entrypoint string) string {
entrypointJS, entrypointMap := outputForEntrypoint(projectRoot, entrypoint)
relEntryp, err := filepath.Rel(projectRoot, entrypoint)
if err != nil {
panic(fmt.Sprintf("Cannot compute entrypoint relative path: %v", err))
}
entrySubDir := filepath.Dir(relEntryp)
entryIndexJS := -1
entryIndexMap := -1
for i, of := range files {
if of.Path == entrypointJS {
entryIndexJS = i
}
if of.Path == entrypointMap {
entryIndexMap = i
}
}
if entryIndexJS < 0 {
panic(fmt.Sprintf("Entrypoint JS %q not found in files", entrypointJS))
}
orderedFiles := make([]esbuild.OutputFile, 0, len(files))
orderedFiles = append(orderedFiles, files[entryIndexJS])
if entryIndexMap >= 0 {
orderedFiles = append(orderedFiles, files[entryIndexMap])
}
for i, of := range files {
if i == entryIndexJS || i == entryIndexMap {
continue
}
orderedFiles = append(orderedFiles, of)
}
var sb strings.Builder
sb.WriteString("📦\n")
for _, of := range orderedFiles {
size := len(of.Contents)
relPath, _ := filepath.Rel(projectRoot, of.Path)
withSub := filepath.Join(entrySubDir, relPath)
sb.WriteString(fmt.Sprintf("%d /%s\n", size, filepath.ToSlash(withSub)))
}
sb.WriteString("✄\n")
for i, of := range orderedFiles {
sb.Write(of.Contents)
if i < len(orderedFiles)-1 {
sb.WriteString("\n✄\n")
}
}
return sb.String()
}
func outputForEntrypoint(projectRoot, entrypoint string) (jsOut, mapOut string) {
jsOut = filepath.Join(projectRoot, changeToJS(filepath.Base(entrypoint)))
mapOut = jsOut + ".map"
return
}
func encodeStringToHexBytes(s string) string {
n := len(s)
if n == 0 {
return ""
}
totalLen := n*4 + (n-1)*2 + 1
buf := make([]byte, 0, totalLen)
hexDigits := "0123456789abcdef"
for i := 0; i < n; i++ {
b := s[i]
buf = append(buf, '0', 'x')
buf = append(buf,
hexDigits[b>>4],
hexDigits[b&0xF],
)
if i < n-1 {
if (i+1)%12 == 0 {
buf = append(buf, ',', '\n')
} else {
buf = append(buf, ',', ' ')
}
}
}
buf = append(buf, '\n')
return string(buf)
}
func encodeStringToCString(s string) string {
n := len(s)
if n == 0 {
return `""`
}
hexDigits := "0123456789abcdef"
var bldr strings.Builder
openLiteral := func() {
bldr.WriteByte('"')
}
closeLiteral := func() {
bldr.WriteByte('"')
}
inLiteral := false
for i := 0; i < n; i++ {
c := s[i]
if !inLiteral {
openLiteral()
inLiteral = true
}
if c == '\n' {
bldr.WriteByte('\\')
bldr.WriteByte('n')
closeLiteral()
inLiteral = false
if i < n-1 {
bldr.WriteByte('\n')
openLiteral()
inLiteral = true
}
continue
}
switch c {
case '"':
bldr.WriteByte('\\')
bldr.WriteByte('"')
case '\\':
bldr.WriteByte('\\')
bldr.WriteByte('\\')
case '\a':
bldr.WriteByte('\\')
bldr.WriteByte('a')
case '\b':
bldr.WriteByte('\\')
bldr.WriteByte('b')
case '\t':
bldr.WriteByte('\\')
bldr.WriteByte('t')
case '\v':
bldr.WriteByte('\\')
bldr.WriteByte('v')
case '\f':
bldr.WriteByte('\\')
bldr.WriteByte('f')
case '\r':
bldr.WriteByte('\\')
bldr.WriteByte('r')
default:
isPrintableExceptQuoteAndBackslash := c >= 0x20 && c <= 0x7E
if isPrintableExceptQuoteAndBackslash {
bldr.WriteByte(c)
} else {
bldr.WriteByte('\\')
bldr.WriteByte('x')
bldr.WriteByte(hexDigits[c>>4])
bldr.WriteByte(hexDigits[c&0xF])
}
}
}
if inLiteral {
closeLiteral()
}
bldr.WriteByte('\n')
return bldr.String()
}
func makeTypeScriptPlugin(compiler *TSCompiler) esbuild.Plugin {
return esbuild.Plugin{
Name: "frida-custom-ts",
Setup: func(build esbuild.PluginBuild) {
build.OnStart(func() (esbuild.OnStartResult, error) {
compiler.EnsureProgramUpToDate()
return esbuild.OnStartResult{}, nil
})
build.OnEnd(func(result *esbuild.BuildResult) (esbuild.OnEndResult, error) {
if len(result.Errors) == 0 {
compiler.CommitPendingInputs()
} else {
compiler.DropPendingInputs()
}
return esbuild.OnEndResult{}, nil
})
build.OnLoad(esbuild.OnLoadOptions{Filter: "\\.ts$"}, func(args esbuild.OnLoadArgs) (esbuild.OnLoadResult, error) {
compiledJS, tsDiagnostics, err := compiler.Compile(args.Path)
result := esbuild.OnLoadResult{
WatchFiles: compiler.WatchFiles(),
WatchDirs: compiler.WatchDirs(),
}
var esbuildMessages []esbuild.Message
for _, d := range tsDiagnostics {
f := d.File()
pos := d.Pos()
line, column := tsscanner.GetLineAndCharacterOfPosition(f, pos)
esbuildMessages = append(esbuildMessages, esbuild.Message{
Text: d.Message(),
Location: &esbuild.Location{
File: f.FileName(),
Line: line,
Column: column,
Length: d.Len(),
LineText: f.Text()[pos:d.End()],
},
Notes: []esbuild.Note{
{Text: d.Category().Name()},
{Text: fmt.Sprintf("%d", d.Code())},
},
})
}
if err != nil {
mainErr := esbuild.Message{Text: err.Error()}
result.Errors = append([]esbuild.Message{mainErr}, esbuildMessages...)
return result, nil
}
if len(esbuildMessages) > 0 {
result.Errors = esbuildMessages
return result, nil
}
result.Contents = &compiledJS
result.Loader = esbuild.LoaderJS
return result, nil
})
},
}
}
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() {}
+7
View File
@@ -0,0 +1,7 @@
{
global:
_frida_compiler_backend_*;
local:
*;
};
+375
View File
@@ -0,0 +1,375 @@
import base64
import json
import os
import shutil
import struct
import subprocess
import sys
from pathlib import Path
from typing import List
def main(argv):
go_config = json.loads(base64.b64decode(argv[1]).decode("utf-8"))
output_dir, priv_dir, go, npm, *inputs = [Path(d).resolve() for d in argv[2:]]
try:
build_backend(go_config, inputs, output_dir, priv_dir, go, npm)
except subprocess.CalledProcessError as e:
print(e, file=sys.stderr)
print(
"Output:\n\t| " + "\n\t| ".join(e.output.strip().split("\n")),
file=sys.stderr,
)
sys.exit(2)
except Exception as e:
print(e, file=sys.stderr)
sys.exit(1)
def build_backend(
config: dict,
inputs: List[Path],
output_dir: Path,
priv_dir: Path,
go: Path,
npm: Path,
):
base_dir = min(inputs, key=lambda p: len(p.parts)).parent
for f in inputs:
dest = priv_dir / f.relative_to(base_dir)
dest.parent.mkdir(exist_ok=True)
shutil.copy(f, dest)
go_sources = [str(f.relative_to(base_dir)) for f in inputs if f.suffix == ".go"]
def run(*args):
return subprocess.run(
args,
cwd=priv_dir,
env=config["env"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding="utf-8",
check=True,
)
run(npm, "install")
# run(npm, "link", "/home/oleavr/src/frida-fs")
mode = config["mode"]
backend_stem = "frida-compiler-backend"
if mode == "c-shared":
backend_stem += "-raw"
backend_a = priv_dir / f"{backend_stem}.a"
backend_shlib = priv_dir / (f"{backend_stem}" + config["shlib_suffix"])
backend_h = priv_dir / f"{backend_stem}.h"
extra_go_args = config["extra_go_args"].copy()
if mode == "c-shared":
version_script = priv_dir / "backend.version"
extra_go_args.append(f"-ldflags=-linkmode=external -extldflags=-Wl,--version-script={version_script}")
run(
go,
"build",
f"-buildmode={mode}",
"-o",
backend_a.name if mode == "c-archive" else backend_shlib.name,
"-buildvcs=false",
*extra_go_args,
*go_sources,
)
if mode == "c-archive":
symbols_to_scramble = detect_conflictful_symbols_in_archive(backend_a, config["nm"])
scramble_symbols_in_archive(backend_a, symbols_to_scramble, config["ranlib"])
if (mingw := config.get("mingw")) is not None and (abi := config["abi"]) in {
"x86",
"x86_64",
}:
prefix = Path(mingw["prefix"])
ar = config["ar"]
libmingwex_a = prefix / "lib" / "libmingwex.a"
if not libmingwex_a.exists():
libmingwex_a = prefix / mingw["triplet"] / "lib" / "libmingwex.a"
libgcc_objects = [
"_chkstk_ms.o",
]
run(*ar, "x", mingw["libcc"], *libgcc_objects)
gwex_objflavor = "64" if abi == "x86_64" else "32"
gwex_objects = [
f"lib{gwex_objflavor}_libmingwex_a-{name}.o"
for name in [
"dmisc",
"gdtoa",
"gmisc",
"mingw_fprintf",
"mingw_pformat",
"misc",
]
]
run(*ar, "x", libmingwex_a, *gwex_objects)
extra_objects = []
if abi == "x86_64":
run(*ar, "x", backend_a.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)
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_h.name, output_dir / backend_h.name)
def detect_conflictful_symbols_in_archive(
archive: Path, nm_cmd_array: List[str]
) -> List[str]:
result = []
for line in subprocess.run(
[*nm_cmd_array, str(archive)], capture_output=True, encoding="utf-8", check=True
).stdout.splitlines():
tokens = line.lstrip().split(" ")
if len(tokens) >= 3 and tokens[1] in {"S", "T"}:
symbol = tokens[2]
if all(sub not in symbol for sub in ("/", ".", ":", "frida")):
result.append(symbol)
return result
def scramble_symbols_in_archive(
archive: Path, symbols: List[str], ranlib_cmd_array: List[str]
):
data = archive.read_bytes()
for old_sym in symbols:
new_sym = roll_first_alpha(old_sym)
data = data.replace(old_sym.encode("ascii"), new_sym.encode("ascii"))
archive.write_bytes(data)
subprocess.run([*ranlib_cmd_array, str(archive)], check=True)
def roll_first_alpha(s: str) -> str:
chars = list(s)
for i, c in enumerate(chars):
if c.isalpha():
if c == "z":
chars[i] = "a"
elif c == "Z":
chars[i] = "A"
else:
chars[i] = chr(ord(c) + 1)
break
return "".join(chars)
# Work around the Go toolchain's almost-MSVC-compatible object files
# until our patch is merged upstream:
# https://go-review.googlesource.com/c/go/+/678795
def sort_pdata_in_object(object_file: Path):
data = bytearray(object_file.read_bytes())
# --- Parse COFF File Header (IMAGE_FILE_HEADER) ---
# Format: WORD Machine; WORD NumberOfSections;
# DWORD TimeDateStamp; DWORD PointerToSymbolTable;
# DWORD NumberOfSymbols; WORD SizeOfOptionalHeader;
# WORD Characteristics;
IMAGE_FILE_HEADER_FMT = "<HHLLLHH"
IMAGE_FILE_HEADER_SIZE = struct.calcsize(IMAGE_FILE_HEADER_FMT)
if len(data) < IMAGE_FILE_HEADER_SIZE:
print("Error: File too small to be a valid COFF object", file=sys.stderr)
return
(
machine,
number_of_sections,
time_date_stamp,
pointer_to_symbol_table,
number_of_symbols,
size_of_optional_header,
characteristics,
) = struct.unpack(IMAGE_FILE_HEADER_FMT, data[0:IMAGE_FILE_HEADER_SIZE])
# --- Parse Section Headers to find .pdata ---
# Each IMAGE_SECTION_HEADER is 40 bytes: Name[8], Misc(VirtualSize), VirtualAddress,
# SizeOfRawData, PointerToRawData, PointerToRelocations, PointerToLinenumbers,
# NumberOfRelocations, NumberOfLinenumbers, Characteristics
SECTION_HEADER_FMT = "<8sLLLLLLHHI"
SECTION_HEADER_SIZE = struct.calcsize(SECTION_HEADER_FMT)
section_table_offset = IMAGE_FILE_HEADER_SIZE + size_of_optional_header
pdata_section_index = None
pdata_pointer_to_raw = None
pdata_size_of_raw = None
pdata_pointer_to_relocs = None
pdata_number_of_relocs = None
# Keep all section headers for rewriting relocation entries later if needed
section_headers = []
for i in range(number_of_sections):
offset = section_table_offset + i * SECTION_HEADER_SIZE
section_data = data[offset : offset + SECTION_HEADER_SIZE]
(
name,
virtual_size,
virtual_address,
size_of_raw_data,
pointer_to_raw_data,
pointer_to_relocations,
pointer_to_linenumbers,
number_of_relocations,
number_of_linenumbers,
sec_characteristics,
) = struct.unpack(SECTION_HEADER_FMT, section_data)
section_name = name.rstrip(b"\x00").decode("utf-8")
section_headers.append(
{
"name": section_name,
"offset": offset,
"virtual_size": virtual_size,
"virtual_address": virtual_address,
"size_of_raw_data": size_of_raw_data,
"pointer_to_raw_data": pointer_to_raw_data,
"pointer_to_relocations": pointer_to_relocations,
"number_of_relocations": number_of_relocations,
}
)
if section_name == ".pdata":
pdata_section_index = i
pdata_pointer_to_raw = pointer_to_raw_data
pdata_size_of_raw = size_of_raw_data
pdata_pointer_to_relocs = pointer_to_relocations
pdata_number_of_relocs = number_of_relocations
if pdata_section_index is None:
print("Error: No .pdata section found in the object file", file=sys.stderr)
return
# --- Parse Symbol Table ---
# Each IMAGE_SYMBOL is 18 bytes: Name[8], Value (4 bytes), SectionNumber (2 bytes),
# Type (2 bytes), StorageClass (1 byte), NumberOfAuxSymbols (1 byte)
SYMBOL_TABLE_ENTRY_SIZE = 18
symbols = []
for sym_index in range(number_of_symbols):
sym_offset = pointer_to_symbol_table + sym_index * SYMBOL_TABLE_ENTRY_SIZE
entry = data[sym_offset : sym_offset + SYMBOL_TABLE_ENTRY_SIZE]
if len(entry) < SYMBOL_TABLE_ENTRY_SIZE:
print("Error: Truncated symbol table entry", file=sys.stderr)
return
# Unpack: Name (8s), Value (L), SectionNumber (h), Type (H), StorageClass (B), NumberOfAuxSymbols (B)
name_bytes, value, section_number, sym_type, storage_class, num_aux = (
struct.unpack("<8sLhHBB", entry)
)
# Decode name: if name_bytes[0:4] are zeros, use string from offset in string table
if name_bytes[:4] == b"\x00\x00\x00\x00":
str_table_offset = struct.unpack("<L", name_bytes[4:])[0]
# String table starts immediately after symbol table: size (4 bytes) + NUL-terminated strings
str_tab_start = (
pointer_to_symbol_table + number_of_symbols * SYMBOL_TABLE_ENTRY_SIZE
)
# Fetch the name from string table
str_offset = str_tab_start + str_table_offset
name_end = data.find(b"\x00", str_offset)
symbol_name = data[str_offset:name_end].decode("utf-8")
else:
symbol_name = name_bytes.partition(b"\x00")[0].decode("utf-8")
symbols.append(
{"name": symbol_name, "value": value, "section_number": section_number}
)
# --- Read original .pdata section raw data ---
pdata_data = data[pdata_pointer_to_raw : pdata_pointer_to_raw + pdata_size_of_raw]
if len(pdata_data) % 12 != 0:
print("Error: .pdata size is not a multiple of 12 bytes", file=sys.stderr)
return
num_entries = len(pdata_data) // 12
# --- Read relocation entries for .pdata ---
# Each IMAGE_RELOCATION is 10 bytes: VirtualAddress (4), SymbolTableIndex (4), Type (2)
RELOC_ENTRY_SIZE = 10
reloc_entries = []
reloc_table_start = pdata_pointer_to_relocs
for rindex in range(pdata_number_of_relocs):
reloff = reloc_table_start + rindex * RELOC_ENTRY_SIZE
entry = data[reloff : reloff + RELOC_ENTRY_SIZE]
if len(entry) < RELOC_ENTRY_SIZE:
print("Error: Truncated relocation entry", file=sys.stderr)
return
va, sym_index, rtype = struct.unpack("<LLH", entry)
reloc_entries.append(
{"virtual_address": va, "symbol_index": sym_index, "type": rtype}
)
# There should be 3 relocations per .pdata entry
if len(reloc_entries) != num_entries * 3:
print(
"Warning: Expected {} relocations but found {}".format(
num_entries * 3, len(reloc_entries)
),
file=sys.stderr,
)
# --- Associate each entry with its relocations and sorting key ---
entries = []
for i in range(num_entries):
entry_bytes = pdata_data[i * 12 : (i + 1) * 12]
entry_relocs = reloc_entries[i * 3 : i * 3 + 3]
# Sorting key: use symbol.Value of first relocation"s symbol index
sym_idx = entry_relocs[0]["symbol_index"]
if sym_idx < 0 or sym_idx >= number_of_symbols:
key = 0
else:
key = symbols[sym_idx]["value"]
entries.append({"entry_bytes": entry_bytes, "relocs": entry_relocs, "key": key})
# --- Sort entries by computed key ---
entries.sort(key=lambda x: x["key"])
# --- Build new .pdata data buffer ---
sorted_pdata = bytearray()
for e in entries:
sorted_pdata.extend(e["entry_bytes"])
# --- Build new relocation table buffer ---
new_reloc_buf = bytearray()
for new_i, e in enumerate(entries):
for reloc in e["relocs"]:
field_offset = reloc["virtual_address"] % 12
new_va = new_i * 12 + field_offset
packed = struct.pack("<LLH", new_va, reloc["symbol_index"], reloc["type"])
new_reloc_buf.extend(packed)
# --- Write back sorted .pdata and new relocations into data buffer ---
# Replace .pdata raw data
data[pdata_pointer_to_raw : pdata_pointer_to_raw + pdata_size_of_raw] = sorted_pdata
# Replace relocation entries
data[pdata_pointer_to_relocs : pdata_pointer_to_relocs + len(new_reloc_buf)] = (
new_reloc_buf
)
# --- Emit the fixed object file ---
object_file.write_bytes(data)
if __name__ == "__main__":
main(sys.argv)
@@ -1,3 +1,2 @@
[resource-compiler]
namespace = Frida.Data.Compiler
compress = *.js:text:7; *.bin:generic:7
-3
View File
@@ -1,3 +0,0 @@
[resource-compiler]
namespace = Frida.Data.Compiler
compress = *.js:text:11; *.bin:generic:11
+291 -341
View File
@@ -1,63 +1,56 @@
namespace Frida {
public class Compiler : Object {
public sealed class Compiler : Object {
public signal void starting ();
public signal void finished ();
public signal void output (string bundle);
public signal void diagnostics (Variant diagnostics);
public DeviceManager manager {
get;
construct;
private size_t watch_session_handle = 0;
private Gee.Queue<Diagnostic> pending_diagnostics = new Gee.ArrayQueue<Diagnostic> ();
private MainContext main_context;
// TODO: Remove the DeviceManager parameter.
public Compiler (DeviceManager? manager = null) {
Object ();
}
#if HAVE_COMPILER_BACKEND
private Promise<Agent>? load_request;
private Gee.Map<uint, MonitorEntry> monitors = new Gee.HashMap<uint, MonitorEntry> ();
private Gee.Set<MonitorEntry> dirty_monitors = new Gee.HashSet<MonitorEntry> ();
private TimeoutSource? monitor_flush_timer;
private Cancellable io_cancellable = new Cancellable ();
#endif
public Compiler (DeviceManager manager) {
Object (manager: manager);
static construct {
CompilerBackend.init ();
}
#if HAVE_COMPILER_BACKEND
public override void dispose () {
if (load_request != null)
close.begin ();
base.dispose ();
construct {
main_context = Frida.get_main_context ();
}
private async void close () {
try {
var agent = yield get_agent (null);
yield agent.close (null);
} catch (GLib.Error e) {
}
load_request = null;
if (monitor_flush_timer != null) {
monitor_flush_timer.destroy ();
monitor_flush_timer = null;
}
foreach (var entry in monitors.values)
detach_monitor_entry (entry);
monitors.clear ();
~Compiler () {
cancel_watch ();
}
#endif
public async string build (string entrypoint, BuildOptions? options = null, Cancellable? cancellable = null)
throws Error, IOError {
#if HAVE_COMPILER_BACKEND
var agent = yield get_agent (cancellable);
CompilerBackend.check_available ();
BuildOptions opts = (options != null) ? options : new BuildOptions ();
string project_root = compute_project_root (entrypoint, opts);
starting ();
try {
string bundle = yield agent.build (entrypoint, options, cancellable);
string? bundle = null;
string? error_message = null;
CompilerBackend.BuildCompleteFunc on_complete = (b, e) => {
bundle = b;
error_message = e;
schedule_on_frida_thread (build.callback);
};
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), (owned) on_complete, on_diagnostic);
yield;
if (error_message != null)
throw new Error.INVALID_ARGUMENT ("%s", error_message);
output (bundle);
@@ -65,9 +58,6 @@ namespace Frida {
} finally {
finished ();
}
#else
throw_not_supported ();
#endif
}
public string build_sync (string entrypoint, BuildOptions? options = null, Cancellable? cancellable = null)
@@ -89,13 +79,38 @@ namespace Frida {
public async void watch (string entrypoint, WatchOptions? options = null, Cancellable? cancellable = null)
throws Error, IOError {
#if HAVE_COMPILER_BACKEND
var agent = yield get_agent (cancellable);
CompilerBackend.check_available ();
yield agent.watch (entrypoint, options, cancellable);
#else
throw_not_supported ();
#endif
WatchOptions opts = (options != null) ? options : new WatchOptions ();
string project_root = compute_project_root (entrypoint, opts);
cancel_watch ();
size_t session_handle = 0;
string? error_message = null;
CompilerBackend.WatchReadyFunc on_ready = (h, e) => {
session_handle = h;
error_message = e;
schedule_on_frida_thread (watch.callback);
};
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), (owned) on_ready, on_starting, on_finished,
on_output, on_diagnostic);
yield;
if (error_message != null)
throw new Error.INVALID_ARGUMENT ("%s", error_message);
watch_session_handle = session_handle;
}
private void cancel_watch () {
if (watch_session_handle != 0) {
CompilerBackend.WatchSession.dispose (watch_session_handle);
watch_session_handle = 0;
}
}
public void watch_sync (string entrypoint, WatchOptions? options = null, Cancellable? cancellable = null)
@@ -115,343 +130,238 @@ namespace Frida {
}
}
#if HAVE_COMPILER_BACKEND
private void on_watch_add (uint id, string path, string type, int64 polling_interval) {
var file = File.parse_name (path);
private void on_starting () {
schedule_on_frida_thread (() => {
starting ();
return Source.REMOVE;
});
}
GLib.FileMonitor monitor;
try {
if (type == "file")
monitor = file.monitor_file (FileMonitorFlags.SEND_MOVED, io_cancellable);
else if (type == "directory")
monitor = file.monitor_directory (FileMonitorFlags.NONE, io_cancellable);
else
assert_not_reached ();
} catch (GLib.Error e) {
return;
private void on_finished () {
schedule_on_frida_thread (() => {
finished ();
return Source.REMOVE;
});
}
private void on_output (owned string bundle) {
schedule_on_frida_thread (() => {
output (bundle);
return Source.REMOVE;
});
}
private void on_diagnostic (owned string category, int code, owned string? path, int line, int character,
owned string text) {
var diag = new Diagnostic () {
category = category,
code = code,
path = path,
line = line,
character = character,
text = text,
};
bool schedule_emit = false;
lock (pending_diagnostics) {
schedule_emit = pending_diagnostics.is_empty;
pending_diagnostics.add (diag);
}
if (polling_interval != 0)
monitor.rate_limit = (int) polling_interval;
var entry = new MonitorEntry (id, monitor);
entry.file_changed.connect (on_file_changed);
monitors[id] = entry;
}
private void on_watch_remove (uint id) {
MonitorEntry? entry;
if (monitors.unset (id, out entry))
detach_monitor_entry (entry);
}
private void detach_monitor_entry (MonitorEntry entry) {
dirty_monitors.remove (entry);
entry.file_changed.disconnect (on_file_changed);
entry.destroy ();
}
private void on_file_changed (MonitorEntry entry) {
dirty_monitors.add (entry);
if (monitor_flush_timer == null) {
var source = new TimeoutSource (50);
source.set_callback (on_monitor_flush_tick);
source.attach (MainContext.get_thread_default ());
monitor_flush_timer = source;
if (schedule_emit) {
schedule_on_frida_thread (() => {
emit_pending_diagnostics ();
return Source.REMOVE;
});
}
}
private bool on_monitor_flush_tick () {
var settled = new Gee.ArrayList<MonitorEntry> ();
var now = get_monotonic_time ();
settled.add_all_iterator (dirty_monitors.filter (m => now - m.last_change >= 50000));
Agent agent = load_request.future.value;
foreach (var entry in settled) {
agent.notify_file_changed (entry.id, entry.state, io_cancellable);
dirty_monitors.remove (entry);
private void emit_pending_diagnostics () {
var batch = new Gee.ArrayList<Diagnostic> ();
lock (pending_diagnostics) {
batch.add_all (pending_diagnostics);
pending_diagnostics.clear ();
}
if (!dirty_monitors.is_empty)
return Source.CONTINUE;
var builder = new VariantBuilder (new VariantType.array (VariantType.VARDICT));
monitor_flush_timer = null;
return Source.REMOVE;
}
private async Agent get_agent (Cancellable? cancellable) throws Error, IOError {
Future<Agent> future;
if (load_request != null) {
future = load_request.future;
} else {
load_request = new Promise<Agent> ();
future = load_request.future;
load_agent.begin ();
foreach (var d in batch) {
builder.open (VariantType.VARDICT);
builder.add ("{sv}", "category", new Variant.string (d.category));
builder.add ("{sv}", "code", new Variant.int64 (d.code));
if (d.path != null) {
var b = new VariantBuilder (VariantType.VARDICT);
b.add ("{sv}", "path", new Variant.string (d.path));
b.add ("{sv}", "line", new Variant.int64 (d.line));
b.add ("{sv}", "character", new Variant.int64 (d.character));
builder.add ("{sv}", "file", b.end ());
}
builder.add ("{sv}", "text", new Variant.string (d.text));
builder.close ();
}
return yield future.wait_async (cancellable);
diagnostics (builder.end ());
}
private async void load_agent () {
try {
var device = yield manager.get_device_by_type (LOCAL, 0, io_cancellable);
var session = yield device.get_host_session (io_cancellable);
var agent = new Agent (this, (BaseDBusHostSession) session);
load_request.resolve (agent);
} catch (GLib.Error e) {
if ((e is Error || e is IOError.CANCELLED))
e = new Error.NOT_SUPPORTED ("%s", e.message);
load_request.reject (e);
load_request = null;
}
}
#else
[NoReturn]
private void throw_not_supported () throws Error {
throw new Error.NOT_SUPPORTED ("Compiler backend disabled at build-time");
}
#endif
private T create<T> () {
return Object.new (typeof (T), parent: this);
}
protected void schedule_on_frida_thread (owned SourceFunc function) {
var source = new IdleSource ();
source.set_callback ((owned) function);
source.attach (main_context);
}
private class Diagnostic {
public string category;
public int code;
public string? path;
public int line;
public int character;
public string text;
}
private abstract class CompilerTask<T> : AsyncTask<T> {
public weak Compiler parent {
get;
construct;
}
}
}
namespace CompilerBackend {
private void init () {
#if HAVE_COMPILER_BACKEND
private class Agent : InternalAgent {
public weak Compiler parent {
get;
construct;
}
private Promise<string> source_request = new Promise<string> ();
private Promise<Bytes?> snapshot_request = new Promise<Bytes?> ();
public Agent (Compiler parent, BaseDBusHostSession host_session) {
Object (
parent: parent,
host_session: host_session,
#if HAVE_V8
script_runtime: ScriptRuntime.V8
#if COMPILER_BACKEND_STATIC_COMPILATION
_init_go_runtime ();
build = (BuildFunc) _build;
watch = (WatchFunc) _watch;
WatchSession.dispose = (WatchSession.DisposeFunc) WatchSession._dispose;
#else
script_runtime: ScriptRuntime.DEFAULT
#endif
);
}
unowned uint8[] backend_so = Frida.Data.Compiler.get_frida_compiler_backend_so_blob ().data;
construct {
load_resources ();
}
FileDescriptor fd;
if (MemoryFileDescriptor.is_supported ()) {
fd = MemoryFileDescriptor.from_bytes ("frida-compiler-backend.so", new Bytes.static (backend_so));
} else {
string name_used;
try {
fd = new FileDescriptor (FileUtils.open_tmp ("frida-compiler-backend-XXXXXX.so", out name_used));
FileUtils.unlink (name_used);
private void load_resources () {
new Thread<void> ("compiler-agent-loader", () => {
var agent_js_blob = Data.Compiler.get_agent_js_blob ();
Bytes agent_js_bytes = decompress (agent_js_blob.data, agent_js_blob.uncompressed_size);
source_request.resolve ((string) agent_js_bytes.get_data ());
var output = new UnixOutputStream (fd.handle, false);
output.write_all (backend_so, null);
var snapshot_blob = Data.Compiler.get_snapshot_bin_blob ();
Bytes snapshot = decompress (snapshot_blob.data, snapshot_blob.uncompressed_size);
snapshot_request.resolve ((snapshot.get_size () != 0) ? snapshot : null);
});
}
public async string build (string entrypoint, BuildOptions? options, Cancellable? cancellable)
throws Error, IOError {
BuildOptions opts = (options != null) ? options : new BuildOptions ();
Json.Node bundle = yield call ("build", new Json.Node[] {
new Json.Node.alloc ().init_string (compute_project_root (entrypoint, opts)),
new Json.Node.alloc ().init_string (entrypoint),
new Json.Node.alloc ().init_string (opts.source_maps.to_nick ()),
new Json.Node.alloc ().init_string (opts.compression.to_nick ()),
}, cancellable);
return bundle.get_string ();
}
public async void watch (string entrypoint, WatchOptions? options, Cancellable? cancellable)
throws Error, IOError {
WatchOptions opts = (options != null) ? options : new WatchOptions ();
yield call ("watch", new Json.Node[] {
new Json.Node.alloc ().init_string (compute_project_root (entrypoint, opts)),
new Json.Node.alloc ().init_string (entrypoint),
new Json.Node.alloc ().init_string (opts.source_maps.to_nick ()),
new Json.Node.alloc ().init_string (opts.compression.to_nick ()),
}, cancellable);
}
private static string compute_project_root (string entrypoint, CompilerOptions options) {
string? project_root = options.project_root;
if (project_root != null)
return project_root;
if (Path.is_absolute (entrypoint))
return Path.get_dirname (entrypoint);
return Environment.get_current_dir ();
}
public void notify_file_changed (uint id, FileState state, Cancellable? cancellable) {
var notification = new Json.Builder ();
notification
.begin_object ()
.set_member_name ("type")
.add_string_value ("watch:change")
.set_member_name ("id")
.add_int_value (id)
.set_member_name ("state")
.add_string_value (Marshal.enum_to_nick<FileState> (state))
.end_object ();
post.begin (notification.get_root (), cancellable);
}
protected override async uint get_target_pid (Cancellable? cancellable) throws Error, IOError {
return 0;
}
protected override async string? load_source (Cancellable? cancellable) throws Error, IOError {
return yield source_request.future.wait_async (cancellable);
}
protected override async Bytes? load_snapshot (Cancellable? cancellable, out SnapshotTransport transport)
throws Error, IOError {
transport = SHARED_MEMORY;
return yield snapshot_request.future.wait_async (cancellable);
}
protected override void on_event (string type, Json.Array event) {
if (type == "diagnostics") {
on_build_diagnostics (event.get_array_element (1));
} else if (type == "watch:compilation-starting") {
parent.starting ();
} else if (type == "watch:compilation-finished") {
parent.finished ();
} else if (type == "watch:bundle-updated") {
on_watch_bundle_updated (event.get_string_element (1));
} else if (type == "watch:add") {
parent.on_watch_add ((uint) event.get_int_element (1), event.get_string_element (2),
event.get_string_element (3), event.get_int_element (4));
} else if (type == "watch:remove") {
parent.on_watch_remove ((uint) event.get_int_element (1));
} else {
Posix.lseek (fd.handle, 0, Posix.SEEK_SET);
} catch (GLib.Error e) {
assert_not_reached ();
}
}
private void on_build_diagnostics (Json.Array diagnostics) {
uint n = diagnostics.get_length ();
var builder = new VariantBuilder (new VariantType.array (VariantType.VARDICT));
for (uint i = 0; i != n; i++) {
var diag = diagnostics.get_array_element (i);
builder.open (VariantType.VARDICT);
builder.add ("{sv}", "category", new Variant.string (diag.get_string_element (0)));
builder.add ("{sv}", "code", new Variant.int64 (diag.get_int_element (1)));
if (!diag.get_null_element (2)) {
var file = diag.get_array_element (2);
var b = new VariantBuilder (VariantType.VARDICT);
b.add ("{sv}", "path", new Variant.string (file.get_string_element (0)));
b.add ("{sv}", "line", new Variant.int64 (file.get_int_element (1)));
b.add ("{sv}", "character", new Variant.int64 (file.get_int_element (2)));
builder.add ("{sv}", "file", b.end ());
}
builder.add ("{sv}", "text", new Variant.string (diag.get_string_element (3)));
builder.close ();
}
parent.diagnostics (builder.end ());
}
private void on_watch_bundle_updated (string bundle) {
parent.output (bundle);
}
private static Bytes decompress (uint8[] data, uint uncompressed_size) {
var decoder = new Brotli.Decoder ();
decoder.set_parameter (LARGE_WINDOW, 1);
uint8[] uncompressed_data = new uint8[uncompressed_size + 1];
size_t available_in = data.length;
size_t available_out = uncompressed_size;
uint8 * next_in = data;
uint8 * next_out = uncompressed_data;
decoder.decompress_stream (&available_in, &next_in, &available_out, &next_out);
uncompressed_data.length = (int) (next_out - (uint8 *) uncompressed_data);
return new Bytes.take ((owned) uncompressed_data);
Module backend;
try {
backend = new Module ("/proc/self/fd/%d".printf (fd.handle), LOCAL);
} catch (ModuleError e) {
assert_not_reached ();
}
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");
#endif
#endif
}
private class MonitorEntry : Object {
public signal void file_changed ();
public uint id;
public GLib.FileMonitor monitor;
public FileState state = PRISTINE;
public int64 last_change = -1;
public MonitorEntry (uint id, GLib.FileMonitor monitor) {
this.id = id;
this.monitor = monitor;
monitor.changed.connect (on_file_changed);
}
public void destroy () {
monitor.changed.disconnect (on_file_changed);
monitor.cancel ();
}
private void on_file_changed (File file, File? other_file, FileMonitorEvent event) {
switch (event) {
case CREATED:
state = PRISTINE;
break;
case CHANGED:
if (state != PRISTINE)
state = MODIFIED;
break;
case DELETED:
case MOVED:
state = DELETED;
break;
default:
return;
}
last_change = get_monotonic_time ();
file_changed ();
}
private void check_available () throws Error {
if (build == null)
throw new Error.NOT_SUPPORTED ("Compiler backend disabled at build-time");
}
private enum FileState {
PRISTINE,
MODIFIED,
DELETED,
private BuildFunc? build;
private WatchFunc? watch;
[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,
owned BuildCompleteFunc on_complete, DiagnosticFunc on_diagnostic);
[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,
owned WatchReadyFunc on_ready, StartingFunc on_starting, FinishedFunc on_finished, OutputFunc on_output,
DiagnosticFunc on_diagnostic);
#if COMPILER_BACKEND_STATIC_COMPILATION
private extern void _init_go_runtime ();
private extern void _build ();
private extern void _watch ();
#endif
namespace WatchSession {
[CCode (has_target = false)]
private delegate void DisposeFunc (size_t handle);
private DisposeFunc? dispose;
#if COMPILER_BACKEND_STATIC_COMPILATION
private extern void _dispose ();
#endif
}
private delegate void BuildCompleteFunc (owned string? bundle, owned string? error_message);
private delegate void WatchReadyFunc (size_t session_handle, owned string? error_message);
private delegate void StartingFunc ();
private delegate void FinishedFunc ();
private delegate void OutputFunc (owned string bundle);
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) {
void * address;
if (!m.symbol (name, out address))
assert_not_reached ();
return (T) address;
}
#endif
}
private string compute_project_root (string entrypoint, CompilerOptions options) {
string? project_root = options.project_root;
if (project_root != null)
return project_root;
if (Path.is_absolute (entrypoint))
return Path.get_dirname (entrypoint);
return Environment.get_current_dir ();
}
public class CompilerOptions : Object {
public string? project_root {
get;
set;
}
public OutputFormat output_format {
get;
set;
default = UNESCAPED;
}
public BundleFormat bundle_format {
get;
set;
default = ESM;
}
public TypeCheckMode type_check {
get;
set;
default = FULL;
}
public SourceMaps source_maps {
get;
set;
@@ -465,10 +375,50 @@ namespace Frida {
}
}
public class BuildOptions : CompilerOptions {
public sealed class BuildOptions : CompilerOptions {
}
public class WatchOptions : CompilerOptions {
public sealed class WatchOptions : CompilerOptions {
}
public enum OutputFormat {
UNESCAPED,
HEX_BYTES,
C_STRING;
public static OutputFormat from_nick (string nick) throws Error {
return Marshal.enum_from_nick<OutputFormat> (nick);
}
public string to_nick () {
return Marshal.enum_to_nick<OutputFormat> (this);
}
}
public enum BundleFormat {
ESM,
IIFE;
public static BundleFormat from_nick (string nick) throws Error {
return Marshal.enum_from_nick<BundleFormat> (nick);
}
public string to_nick () {
return Marshal.enum_to_nick<BundleFormat> (this);
}
}
public enum TypeCheckMode {
FULL,
NONE;
public static TypeCheckMode from_nick (string nick) throws Error {
return Marshal.enum_from_nick<TypeCheckMode> (nick);
}
public string to_nick () {
return Marshal.enum_to_nick<TypeCheckMode> (this);
}
}
public enum SourceMaps {
-91
View File
@@ -1,91 +0,0 @@
from pathlib import Path
import shutil
import subprocess
import sys
INPUTS = [
"agent-entrypoint.js",
"agent-core.ts",
"agent-warmup.js",
"package.json",
"package-lock.json",
"tsconfig.json",
"rollup.config.agent-core.ts",
"rollup.config.typescript.ts",
]
def main(argv):
output_dir, priv_dir, input_dir, npm, v8_mksnapshot = [Path(d).resolve() if d else None for d in argv[1:6]]
host_os_family, host_arch, host_cpu_mode = argv[6:9]
try:
generate_agent(output_dir, priv_dir, input_dir, npm, v8_mksnapshot, host_os_family, host_arch, host_cpu_mode)
except subprocess.CalledProcessError as e:
print(e, file=sys.stderr)
print("Output:\n\t| " + "\n\t| ".join(e.output.strip().split("\n")), file=sys.stderr)
sys.exit(2)
except Exception as e:
print(e, file=sys.stderr)
sys.exit(1)
def generate_agent(output_dir, priv_dir, input_dir, npm, v8_mksnapshot, host_os_family, host_arch, host_cpu_mode):
entrypoint = input_dir / "agent-entrypoint.js"
priv_dir.mkdir(exist_ok=True)
for name in INPUTS:
if name == "agent-entrypoint.js":
continue
shutil.copy(input_dir / name, priv_dir / name)
run_kwargs = {
"cwd": priv_dir,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"encoding": "utf-8",
"check": True,
}
subprocess.run([npm, "install"], **run_kwargs)
#subprocess.run([npm, "link", "/Users/oleavr/src/frida-compile"], **run_kwargs)
components = ["typescript", "agent-core"]
for component in components:
subprocess.run([
npm, "run", "build:" + component,
"--",
"--environment", f"FRIDA_HOST_OS_FAMILY:{host_os_family},FRIDA_HOST_ARCH:{host_arch},FRIDA_HOST_CPU_MODE:{host_cpu_mode}",
"--silent",
],
**run_kwargs)
chunks = []
for component in components:
script = (priv_dir / f"{component}.js").read_text(encoding="utf-8")
chunks.append(script)
components_source = "\n".join(chunks)
agent = output_dir / "agent.js"
snapshot = output_dir / "snapshot.bin"
if v8_mksnapshot is not None:
shutil.copy(entrypoint, agent)
(priv_dir / "embed.js").write_text(components_source, encoding="utf-8")
subprocess.run([
v8_mksnapshot,
"--turbo-instruction-scheduling",
f"--startup-blob={snapshot}",
"embed.js",
input_dir / "agent-warmup.js",
],
**run_kwargs)
else:
agent.write_text("\n".join([
components_source,
entrypoint.read_text(encoding="utf-8"),
]), encoding="utf-8")
snapshot.write_bytes(b"")
if __name__ == "__main__":
main(sys.argv)
+14
View File
@@ -0,0 +1,14 @@
module github.com/frida/frida-core-compiler
go 1.24.3
require (
github.com/evanw/esbuild v0.25.5
github.com/frida/typescript-go v0.0.0-20250601212135-a4721f45f19c
)
require (
github.com/dlclark/regexp2 v1.11.5 // indirect
github.com/go-json-experiment/json v0.0.0-20250517221953-25912455fbc8 // indirect
golang.org/x/sys v0.33.0 // indirect
)
+17
View File
@@ -0,0 +1,17 @@
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/evanw/esbuild v0.25.5 h1:E+JpeY5S/1LFmnX1vtuZqUKT7qDVcfXdhzMhM3uIKFs=
github.com/evanw/esbuild v0.25.5/go.mod h1:D2vIQZqV/vIf/VRHtViaUtViZmG7o+kKmlBfVQuRi48=
github.com/frida/typescript-go v0.0.0-20250601212135-a4721f45f19c h1:IWBI9AwSFLWymI4enx1jrAw0E4H2E+qHwsihv+AxSoE=
github.com/frida/typescript-go v0.0.0-20250601212135-a4721f45f19c/go.mod h1:L4RMzD/pFBl7CqIf9XTrX41RO2xcok3OOVVcowv0H4k=
github.com/go-json-experiment/json v0.0.0-20250517221953-25912455fbc8 h1:o8UqXPI6SVwQt04RGsqKp3qqmbOfTNMqDrWsc4O47kk=
github.com/go-json-experiment/json v0.0.0-20250517221953-25912455fbc8/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/peter-evans/patience v0.3.0 h1:rX0JdJeepqdQl1Sk9c9uvorjYYzL2TfgLX1adqYm9cA=
github.com/peter-evans/patience v0.3.0/go.mod h1:Kmxu5sY1NmBLFSStvXjX1wS9mIv7wMcP/ubucyMOAu0=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
+45 -47
View File
@@ -1,67 +1,65 @@
compiler_sources = files(
'compiler.vala',
'backend-glue.c',
)
if have_compiler_backend
if get_option('compiler_snapshot').auto()
# Generating our snapshot with V8's CPU simulator takes a very long time.
use_snapshot = meson.can_run_host_binaries()
else
use_snapshot = get_option('compiler_snapshot').enabled()
endif
compiler_mksnapshot = use_snapshot ? v8_mksnapshot : ''
compiler_agent = custom_target('frida-compiler-agent',
compiler_backend = custom_target('frida-compiler-backend',
input: [
'agent-entrypoint.js',
'agent-core.ts',
'agent-warmup.js',
'go.mod',
'go.sum',
'backend.go',
'backend.version',
'tscompiler.go',
'tsconfig.go',
'shims.go',
'package.json',
'package-lock.json',
'tsconfig.json',
'rollup.config.agent-core.ts',
'rollup.config.typescript.ts',
],
output: [
'agent.js',
'snapshot.bin',
'frida-compiler-backend' + (compiler_backend_static_compilation ? '.a' : ('-raw' + shlib_suffix)),
'frida-compiler-backend.h',
],
command: [
python,
files('generate-agent.py'),
files('build-backend.py'),
go_config,
meson.current_build_dir(),
'@PRIVATE_DIR@',
meson.current_source_dir(),
go,
npm,
compiler_mksnapshot,
host_os_family,
host_arch_gumjs,
host_cpu_mode,
'@INPUT@',
],
)
compiler_data = custom_target('frida-data-compiler',
input: [
'compiler.resources.' + frida_profile,
compiler_agent,
],
output: [
'frida-data-compiler.vapi',
'frida-data-compiler.h',
'frida-data-compiler.c',
'frida-data-compiler-blob' + resource_blob_extension,
'frida-data-compiler-agent.js.br',
'frida-data-compiler-snapshot.bin.br',
],
command: [
resource_compiler_cmd_array,
'-c', '@INPUT0@',
'-o', meson.current_build_dir() / 'frida-data-compiler',
'@INPUT1@',
'@INPUT2@',
],
)
compiler_sources += compiler_data
if compiler_backend_static_compilation
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'],
)
backend_vala_args_private += '--pkg=libbrotlidec'
backend_deps_private += brotlidec_dep
compiler_data = custom_target('frida-data-compiler',
input: [
'compiler.resources',
compiler_backend_shlib,
],
output: [
'frida-data-compiler.vapi',
'frida-data-compiler.h',
'frida-data-compiler.c',
'frida-data-compiler-blob' + resource_blob_extension,
],
command: [
resource_compiler_cmd_array,
'-c', '@INPUT0@',
'-o', meson.current_build_dir() / 'frida-data-compiler',
'@INPUT1@',
],
)
backend_sources += compiler_data
endif
endif
+105 -1745
View File
File diff suppressed because it is too large. Load diff
+31 -22
View File
@@ -1,27 +1,36 @@
{
"name": "frida-compiler-agent",
"name": "frida-compiler-shims",
"version": "1.0.0",
"description": "Agent used by Frida's compiler",
"main": "agent.ts",
"scripts": {
"build:typescript": "rollup --config rollup.config.typescript.ts --configPlugin typescript",
"build:agent-core": "rollup --config rollup.config.agent-core.ts --configPlugin typescript"
},
"description": "Shims used by Frida's compiler",
"private": true,
"dependencies": {
"@frida/crosspath": "3.0.0",
"frida-compile": "16.4.1",
"frida-fs": "5.2.5"
},
"devDependencies": {
"@frida/rollup-plugin-node-polyfills": "^1.0.3",
"@rollup/plugin-node-resolve": "^14.1.0",
"@rollup/plugin-replace": "^4.0.0",
"@rollup/plugin-typescript": "^8.3.4",
"@types/frida-gum": "18.7.0",
"@types/glob": "^8.0.0",
"@types/node": "18.7.23",
"glob": "^8.0.3",
"rollup": "^2.79.1",
"rollup-plugin-terser": "^7.0.2"
"@frida/assert": "^3.0.2",
"@frida/base64-js": "^2.0.3",
"@frida/buffer": "^7.0.4",
"@frida/crypto": "^1.0.1",
"@frida/diagnostics_channel": "^1.0.0",
"@frida/events": "^4.0.4",
"@frida/http": "^4.0.2",
"@frida/http-parser-js": "^1.0.0",
"@frida/https": "^1.0.0",
"@frida/ieee754": "^2.0.2",
"@frida/net": "^5.0.0",
"@frida/os": "^1.0.2",
"@frida/path": "^2.0.3",
"@frida/process": "^1.2.1",
"@frida/punycode": "^3.0.0",
"@frida/querystring": "^1.0.0",
"@frida/readable-stream": "^4.1.3",
"@frida/reserved-words": "^1.0.0",
"@frida/stream": "^1.0.2",
"@frida/string_decoder": "^2.0.0",
"@frida/timers": "^3.0.0",
"@frida/tty": "^1.0.0",
"@frida/url": "^1.0.2",
"@frida/util": "^1.0.3",
"@frida/vm": "^2.0.0",
"@types/frida-gum": "19.0.0",
"@types/node": "18.19.103",
"frida-fs": "7.0.0"
}
}
-184
View File
@@ -1,184 +0,0 @@
import crosspath from "@frida/crosspath";
import fs from "fs";
import { sync as glob } from "glob";
import replace from "@rollup/plugin-replace";
import resolve from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";
import polyfills from "@frida/rollup-plugin-node-polyfills";
import { terser } from "rollup-plugin-terser";
import { defineConfig } from "rollup";
import type rollup from "rollup";
export default defineConfig({
input: "agent-core.ts",
output: {
file: "agent-core.js",
format: "umd",
name: "FridaCompilerAgentCore",
generatedCode: {
preset: "es2015",
},
strict: false,
interop: "default",
globals: {
"typescript": "ts",
},
},
plugins: [
typescript(),
replace({
preventAssignment: true,
values: computeSubstitutionValues(),
}),
stubTsImportPlugin(),
polyfills(),
resolve(),
/*
terser({
ecma: 2020,
compress: {
module: true,
global_defs: {
"process.env.FRIDA_COMPILE": true
},
},
mangle: {
module: true,
},
}),
*/
],
});
function computeSubstitutionValues() {
const hostOsFamily = process.env.FRIDA_HOST_OS_FAMILY;
if (hostOsFamily === undefined) {
throw new Error("missing FRIDA_HOST_OS_FAMILY");
}
const hostArch = process.env.FRIDA_HOST_ARCH;
if (hostArch === undefined) {
throw new Error("missing FRIDA_HOST_ARCH");
}
const hostCpuMode = process.env.FRIDA_HOST_CPU_MODE;
if (hostCpuMode === undefined) {
throw new Error("missing FRIDA_HOST_CPU_MODE");
}
const outputDir = __dirname;
const compilerDir = crosspath.join(__dirname, "node_modules", "frida-compile");
let usingLinkedCompiler = false;
try {
usingLinkedCompiler = fs.statSync(crosspath.join(compilerDir, "node_modules")).isDirectory();
} catch (e) {
}
const assetParentDir = usingLinkedCompiler ? compilerDir : outputDir;
const assetModulesDir = crosspath.join(assetParentDir, "node_modules");
const shimDirs = [
["@frida", "assert"],
["@frida", "base64-js"],
["@frida", "buffer"],
["@frida", "crypto"],
["@frida", "diagnostics_channel"],
["@frida", "events"],
["@frida", "http"],
["@frida", "http-parser-js"],
["@frida", "https"],
["@frida", "ieee754"],
["@frida", "net"],
["@frida", "os"],
["@frida", "path"],
["@frida", "process"],
["@frida", "punycode"],
["@frida", "querystring"],
["@frida", "readable-stream"],
["@frida", "stream"],
["@frida", "string_decoder"],
["@frida", "timers"],
["@frida", "tty"],
["@frida", "url"],
["@frida", "util"],
["@frida", "vm"],
["frida-fs"],
];
const typeDirs = [
["@types", "node"],
["@types", "frida-gum"],
];
const assets: string[] = [];
for (const shimDir of shimDirs) {
assets.push(...glob(crosspath.join(assetModulesDir, ...shimDir, "package.json")));
assets.push(...glob(crosspath.join(assetModulesDir, ...shimDir, "**", "*.js")));
}
for (const typeDir of typeDirs) {
assets.push(...glob(crosspath.join(assetModulesDir, ...typeDir, "package.json")));
assets.push(...glob(crosspath.join(assetModulesDir, ...typeDir, "**", "*.d.ts")));
}
assets.push(...glob(crosspath.join(compilerDir, "ext", "lib.es*.d.ts")));
assets.push(...glob(crosspath.join(compilerDir, "ext", "lib.decorators*.d.ts")));
const ignoredAssetFiles = new Set([
"@frida/process/browser.js",
]);
const agentDirectories = new Set<string>();
const agentFiles = new Map<string, string>();
for (const assetPath of assets) {
let assetRelpath = assetPath.substring(assetParentDir.length);
if (usingLinkedCompiler && assetRelpath.startsWith("/ext/")) {
assetRelpath = crosspath.join("/", "node_modules", "frida-compile", assetRelpath.substring(1));
}
const identifier = assetRelpath.split("/").slice(2).join("/");
if (ignoredAssetFiles.has(identifier)) {
continue;
}
let currentDir = crosspath.dirname(assetRelpath);
do {
agentDirectories.add(currentDir);
currentDir = crosspath.dirname(currentDir);
} while (currentDir !== "/");
agentFiles.set(assetRelpath, fs.readFileSync(assetPath, "utf-8"));
}
const orderedAgentDirectories = Array.from(agentDirectories);
orderedAgentDirectories.sort();
const orderedAgentFiles = Array.from(agentFiles);
orderedAgentFiles.sort((a, b) => a[0].localeCompare(b[0]));
return {
"Frida.version": "'0.0.0'",
"Process.id": "1",
"Process.platform": `'${hostOsFamily}'`,
"Process.arch": `'${hostArch}'`,
"Process.pointerSize": (hostCpuMode === "64") ? "8" : "4",
"__agentDirectories__": JSON.stringify(orderedAgentDirectories, null, 4),
"__agentFiles__": JSON.stringify(orderedAgentFiles, null, 4),
};
}
function stubTsImportPlugin(): rollup.Plugin {
return {
name: "stub-ts-import",
async resolveId(source, importer, options) {
if (crosspath.basename(source) === "typescript.js") {
return {
id: "typescript",
external: true,
meta: {},
moduleSideEffects: false,
syntheticNamedExports: false
};
}
return this.resolve(source, importer, { skipSelf: true, ...options });
}
};
}
-15
View File
@@ -1,15 +0,0 @@
import path from "path";
import { defineConfig } from "rollup";
export default defineConfig({
input: path.join("node_modules", "frida-compile", "ext", "typescript.js"),
output: {
file: "typescript.js",
format: "umd",
name: "ts",
generatedCode: {
preset: "es2015",
},
strict: false,
},
});
+196
View File
@@ -0,0 +1,196 @@
package main
import (
"embed"
"encoding/json"
"fmt"
"path/filepath"
"strings"
esbuild "github.com/evanw/esbuild/pkg/api"
)
var nodeGlobals = `
export { Buffer } from 'node:buffer';
export { default as process } from 'node:process';
`
//go:embed node_modules/@frida/*/package.json
//go:embed node_modules/@frida/*/*.js
//go:embed node_modules/@frida/*/*/*.js
//go:embed node_modules/@frida/*/*/*/*.js
//go:embed node_modules/frida-fs/package.json
//go:embed node_modules/frida-fs/*/*.js
var embeddedShims embed.FS
func makeFridaShimsPlugin() esbuild.Plugin {
const (
nsBuiltins = "frida-builtins"
nsShim = "frida-shim"
)
const (
builtinFilter = `^frida-builtins://(.+)$`
shimFilter = `^(assert|base64-js|buffer|crypto|diagnostics_channel|events|fs|http|https|http-parser-js|ieee754|net|os|path|process|punycode|querystring|readable-stream|stream|string_decoder|timers|tty|url|util|vm)$`
shimNodePrefixFilter = `^node:(assert|buffer|crypto|diagnostics_channel|events|fs|http|https|net|os|path|process|punycode|querystring|stream|string_decoder|timers|tty|url|util|vm)$`
)
return esbuild.Plugin{
Name: "frida-custom-shims",
Setup: func(build esbuild.PluginBuild) {
build.OnResolve(esbuild.OnResolveOptions{Filter: builtinFilter},
func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) {
return esbuild.OnResolveResult{
Path: strings.TrimPrefix(args.Path, "frida-builtins://"),
Namespace: nsBuiltins,
SideEffects: esbuild.SideEffectsFalse,
}, nil
})
build.OnLoad(esbuild.OnLoadOptions{Filter: ".*", Namespace: nsBuiltins},
func(args esbuild.OnLoadArgs) (esbuild.OnLoadResult, error) {
if args.Path != "/node-globals.js" {
return esbuild.OnLoadResult{
Errors: []esbuild.Message{{Text: "Unexpected path: " + args.Path}},
}, nil
}
return esbuild.OnLoadResult{
Contents: &nodeGlobals,
Loader: esbuild.LoaderJS,
}, nil
})
registerShimResolve := func(pattern string) {
build.OnResolve(esbuild.OnResolveOptions{Filter: pattern},
func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) {
return makeResolveResult(nsShim, args.Path)
})
}
registerShimResolve(shimFilter)
registerShimResolve(shimNodePrefixFilter)
build.OnResolve(esbuild.OnResolveOptions{Filter: ".*", Namespace: nsShim},
func(args esbuild.OnResolveArgs) (esbuild.OnResolveResult, error) {
if strings.HasPrefix(args.Path, ".") {
abs := filepath.ToSlash(filepath.Join(filepath.Dir(args.Importer), args.Path))
return esbuild.OnResolveResult{
Path: abs,
Namespace: nsShim,
SideEffects: esbuild.SideEffectsFalse,
}, nil
}
return makeResolveResult(nsShim, args.Path)
})
build.OnLoad(esbuild.OnLoadOptions{Filter: ".*", Namespace: nsShim},
func(args esbuild.OnLoadArgs) (esbuild.OnLoadResult, error) {
data, err := embeddedShims.ReadFile(filepath.ToSlash(args.Path))
if err != nil {
return esbuild.OnLoadResult{
Errors: []esbuild.Message{{
Text: fmt.Sprintf("Error reading shim file %q: %v", args.Path, err),
}},
}, nil
}
content := string(data)
return esbuild.OnLoadResult{
Contents: &content,
Loader: loaderFor(args.Path),
}, nil
})
},
}
}
func makeResolveResult(ns string, module string) (esbuild.OnResolveResult, error) {
path, errs := resolveShim(module)
if len(errs) > 0 {
return esbuild.OnResolveResult{Errors: errs}, nil
}
return esbuild.OnResolveResult{
Path: path,
Namespace: ns,
SideEffects: esbuild.SideEffectsFalse,
}, nil
}
func loaderFor(path string) esbuild.Loader {
switch ext := filepath.Ext(path); ext {
case ".js", ".mjs", ".cjs":
return esbuild.LoaderJS
case ".json":
return esbuild.LoaderJSON
default:
panic(fmt.Sprintf("frida-shims: unsupported file type %q", ext))
}
}
var shimMap = map[string]string{
"assert": "@frida/assert",
"base64-js": "@frida/base64-js",
"buffer": "@frida/buffer",
"crypto": "@frida/crypto",
"diagnostics_channel": "@frida/diagnostics_channel",
"events": "@frida/events",
"fs": "frida-fs",
"http": "@frida/http",
"https": "@frida/https",
"http-parser-js": "@frida/http-parser-js",
"ieee754": "@frida/ieee754",
"net": "@frida/net",
"os": "@frida/os",
"path": "@frida/path",
"process": "@frida/process",
"punycode": "@frida/punycode",
"querystring": "@frida/querystring",
"readable-stream": "@frida/readable-stream",
"stream": "@frida/stream",
"string_decoder": "@frida/string_decoder",
"timers": "@frida/timers",
"tty": "@frida/tty",
"url": "@frida/url",
"util": "@frida/util",
"vm": "@frida/vm",
}
type PackageJSON struct {
Main string `json:"main"`
Module string `json:"module"`
}
func resolveShim(shimName string) (string, []esbuild.Message) {
var subDir string
if strings.HasPrefix(shimName, "@frida/") {
subDir = shimName
} else {
actualShimName := strings.TrimPrefix(shimName, "node:")
var ok bool
subDir, ok = shimMap[actualShimName]
if !ok {
return "", []esbuild.Message{{Text: "Unknown shim: " + actualShimName}}
}
}
shimPackageDir := filepath.Join("node_modules", subDir)
packageJSONPath := filepath.Join(shimPackageDir, "package.json")
pkgJSONBytes, _ := embeddedShims.ReadFile(filepath.ToSlash(packageJSONPath))
var pkg PackageJSON
json.Unmarshal(pkgJSONBytes, &pkg)
entryFile := ""
if pkg.Module != "" {
entryFile = pkg.Module
} else if pkg.Main != "" {
entryFile = pkg.Main
} else {
entryFile = "index.js"
}
resolvedEntryPath := filepath.Join(shimPackageDir, entryFile)
return filepath.ToSlash(resolvedEntryPath), nil
}
+448
View File
@@ -0,0 +1,448 @@
package main
import (
"context"
"embed"
"fmt"
"maps"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/frida/typescript-go/pkg/ast"
"github.com/frida/typescript-go/pkg/bundled"
"github.com/frida/typescript-go/pkg/compiler"
"github.com/frida/typescript-go/pkg/core"
"github.com/frida/typescript-go/pkg/tsoptions"
"github.com/frida/typescript-go/pkg/tspath"
"github.com/frida/typescript-go/pkg/vfs"
"github.com/frida/typescript-go/pkg/vfs/iovfs"
"github.com/frida/typescript-go/pkg/vfs/osvfs"
)
//go:embed node_modules/@types/*/package.json
//go:embed node_modules/@types/*/*.d.ts
//go:embed node_modules/@types/*/*/*.d.ts
var embeddedTypes embed.FS
type TSCompiler struct {
projectRoot string
entrypoint string
loadCompilerOptions LoadCompilerOptionsHandler
fs vfs.FS
captureFs *captureFS
mu sync.Mutex
options *core.CompilerOptions
program *compiler.Program
programErr error
forceFreshProgram bool
mtimes map[tspath.Path]time.Time
inputDirs, inputFiles []string
pendingDirs, pendingFiles []string
}
type LoadCompilerOptionsHandler func(host tsoptions.ParseConfigHost) (*core.CompilerOptions, string, error)
func NewTSCompiler(projectRoot, entrypoint string, loadCompilerOptions LoadCompilerOptionsHandler) *TSCompiler {
captureFs := newCaptureFS(osvfs.FS())
fs := newTypesFS(bundled.WrapFS(captureFs), projectRoot)
return &TSCompiler{
projectRoot: projectRoot,
entrypoint: tspath.NormalizePath(entrypoint),
loadCompilerOptions: loadCompilerOptions,
fs: fs,
captureFs: captureFs,
}
}
func (c *TSCompiler) resetProgramState() {
c.options = nil
c.program = nil
c.programErr = nil
c.forceFreshProgram = false
c.mtimes = nil
}
func (c *TSCompiler) EnsureProgramUpToDate() error {
opts, _, err := c.loadCompilerOptions(c)
if err != nil {
c.resetProgramState()
c.recomputeInputs()
return err
}
var prog *compiler.Program
var progErr error
if c.forceFreshProgram || c.program == nil || opts != c.options {
c.forceFreshProgram = false
prog, progErr = c.createProgram(opts)
} else {
prog, progErr = c.updateProgram(c.program, opts)
}
c.program = prog
c.programErr = progErr
c.options = opts
c.recomputeInputs()
return progErr
}
func (c *TSCompiler) createProgram(options *core.CompilerOptions) (*compiler.Program, error) {
host := compiler.NewCompilerHost(options, c.projectRoot, c.fs, bundled.LibPath())
program := compiler.NewProgram(compiler.ProgramOptions{
RootFiles: []string{c.entrypoint},
Host: host,
Options: options,
})
c.updateMtimes(program)
return program, nil
}
func (c *TSCompiler) updateProgram(old *compiler.Program, options *core.CompilerOptions) (*compiler.Program, error) {
newMtimes, err := c.collectMtimes(old)
if err != nil {
return c.createProgram(options)
}
updated := []tspath.Path{}
newProg := old
for path, mtime := range newMtimes {
if !mtime.Equal(c.mtimes[path]) {
var reused bool
newProg, reused = newProg.UpdateProgram(path)
updated = append(updated, path)
if !reused {
c.updateMtimes(newProg)
return newProg, nil
}
}
}
c.mtimes = newMtimes
return newProg, nil
}
func (c *TSCompiler) updateMtimes(p *compiler.Program) {
mt, _ := c.collectMtimes(p)
c.mtimes = mt
}
func (c *TSCompiler) collectMtimes(p *compiler.Program) (map[tspath.Path]time.Time, error) {
mt := make(map[tspath.Path]time.Time, len(p.SourceFiles()))
for _, sf := range p.SourceFiles() {
name := sf.FileName()
if isBundled(name) {
continue
}
info := c.fs.Stat(name)
if info == nil {
return nil, fmt.Errorf("File %q disappeared", name)
}
mt[sf.Path()] = info.ModTime()
}
return mt, nil
}
func isBundled(name string) bool {
return strings.HasPrefix(name, "bundled://")
}
func (c *TSCompiler) WatchDirs() []string {
if c.inputDirs != nil {
return c.inputDirs
}
return c.pendingDirs
}
func (c *TSCompiler) WatchFiles() []string {
if c.inputFiles != nil {
return c.inputFiles
}
return c.pendingFiles
}
func (c *TSCompiler) CommitPendingInputs() {
c.inputDirs, c.pendingDirs = c.pendingDirs, nil
c.inputFiles, c.pendingFiles = c.pendingFiles, nil
}
func (c *TSCompiler) DropPendingInputs() {
c.pendingDirs, c.pendingFiles = nil, nil
}
func (c *TSCompiler) recomputeInputs() {
var capHint int
if c.program != nil {
capHint = 1 + len(c.program.GetSourceFiles())
} else {
capHint = 1
}
files := make([]string, 0, capHint)
files = append(files, filepath.Join(c.projectRoot, "tsconfig.json"))
if c.program != nil {
for _, sf := range c.program.GetSourceFiles() {
name := sf.FileName()
if !isBundled(name) {
files = append(files, name)
}
}
}
sort.Strings(files)
c.pendingDirs = uniqueDirs(files)
c.pendingFiles = files
}
func (c *TSCompiler) Compile(filePathToCompile string) (string, []*ast.Diagnostic, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.programErr != nil {
return "", nil, c.programErr
}
program := c.program
var targetSourceFile *ast.SourceFile
normalizedFilePathToCompile := tspath.NormalizePath(filePathToCompile)
for _, sf := range program.GetSourceFiles() {
if sf.FileName() == normalizedFilePathToCompile {
targetSourceFile = sf
break
}
}
if targetSourceFile == nil {
return "", nil, fmt.Errorf("TypeScript source file not found in program: %s", filePathToCompile)
}
c.captureFs.ClearOutputs()
res := program.Emit(compiler.EmitOptions{
TargetSourceFile: targetSourceFile,
})
ctx := context.Background()
diagnostics := program.GetSyntacticDiagnostics(ctx, targetSourceFile)
if len(diagnostics) == 0 {
diagnostics = append(diagnostics, program.GetBindDiagnostics(ctx, targetSourceFile)...)
}
if len(diagnostics) == 0 {
diagnostics = append(diagnostics, program.GetOptionsDiagnostics(ctx)...)
}
if len(diagnostics) == 0 {
diagnostics = append(diagnostics, program.GetGlobalDiagnostics(ctx)...)
}
if len(diagnostics) == 0 {
semanticDiags := program.GetSemanticDiagnostics(ctx, targetSourceFile)
for _, d := range semanticDiags {
switch d.Code() {
case
2305, // Module '{0}' has no exported member '{1}'.
2306, // File '{0}' is not a module.
2307: // Cannot find module '{0}' or its corresponding type declarations.
c.forceFreshProgram = true
}
}
diagnostics = append(diagnostics, semanticDiags...)
}
if res.EmitSkipped {
errMsg := "TypeScript compilation failed and was skipped"
if len(diagnostics) == 0 {
errMsg = fmt.Sprintf("TypeScript compilation failed and was skipped for %s, but no diagnostics reported", filePathToCompile)
}
return "", diagnostics, fmt.Errorf(errMsg)
}
var compiledJS string
var foundJSOutput bool
for path, content := range c.captureFs.GetOutputs() {
ext := filepath.Ext(path)
if ext == ".js" {
compiledJS = content
foundJSOutput = true
break
}
}
if !foundJSOutput {
if len(diagnostics) == 0 {
return "", nil, fmt.Errorf("TypeScript compilation for %s seemed to succeed (emit not skipped, no diagnostics) but no .js output file was captured. Captured outputs: %v", filePathToCompile, c.captureFs.GetOutputs())
}
return "", diagnostics, fmt.Errorf("No .js output file was captured for %s. Captured outputs: %v", filePathToCompile, c.captureFs.GetOutputs())
}
return compiledJS, diagnostics, nil
}
func uniqueDirs(files []string) []string {
m := make(map[string]struct{}, len(files))
for _, f := range files {
m[filepath.Dir(f)] = struct{}{}
}
out := make([]string, 0, len(m))
for d := range m {
out = append(out, d)
}
sort.Strings(out)
return out
}
// FS implements ParseConfigHost.
func (c *TSCompiler) FS() vfs.FS {
return c.fs
}
// GetCurrentDirectory implements ParseConfigHost.
func (c *TSCompiler) GetCurrentDirectory() string {
return c.projectRoot
}
type captureFS struct {
vfs.FS
outputs map[string]string
mutex sync.Mutex
}
var _ vfs.FS = (*captureFS)(nil)
func newCaptureFS(inner vfs.FS) *captureFS {
return &captureFS{
FS: inner,
outputs: make(map[string]string),
}
}
func (c *captureFS) ClearOutputs() {
c.mutex.Lock()
defer c.mutex.Unlock()
c.outputs = make(map[string]string)
}
func (c *captureFS) GetOutputs() map[string]string {
c.mutex.Lock()
defer c.mutex.Unlock()
snap := make(map[string]string, len(c.outputs))
for k, v := range c.outputs {
snap[k] = v
}
return snap
}
func (c *captureFS) WriteFile(path string, data string, writeByteOrderMark bool) error {
c.mutex.Lock()
defer c.mutex.Unlock()
c.outputs[path] = data
return nil
}
func (c *captureFS) Remove(path string) error {
c.mutex.Lock()
defer c.mutex.Unlock()
delete(c.outputs, path)
return nil
}
type typesFS struct {
vfs.FS
projectRoot string
types vfs.FS
}
var _ vfs.FS = (*typesFS)(nil)
func newTypesFS(inner vfs.FS, projectRoot string) *typesFS {
return &typesFS{
FS: inner,
projectRoot: projectRoot,
types: iovfs.From(embeddedTypes, true),
}
}
func (t *typesFS) DirectoryExists(path string) bool {
embeddedPath := t.resolveEmbeddedPath(path)
if embeddedPath != "" {
if t.types.DirectoryExists(embeddedPath) {
return true
}
}
return t.FS.DirectoryExists(path)
}
func (t *typesFS) GetAccessibleEntries(path string) vfs.Entries {
embeddedPath := t.resolveEmbeddedPath(path)
var embeddedEntries vfs.Entries
if embeddedPath != "" {
embeddedEntries = t.types.GetAccessibleEntries(embeddedPath)
}
otherEntries := t.FS.GetAccessibleEntries(path)
return vfs.Entries{
Files: mergeAndSort(embeddedEntries.Files, otherEntries.Files),
Directories: mergeAndSort(embeddedEntries.Directories, otherEntries.Directories),
}
}
func (t *typesFS) FileExists(path string) bool {
embeddedPath := t.resolveEmbeddedPath(path)
if embeddedPath != "" {
if t.types.FileExists(embeddedPath) {
return true
}
}
return t.FS.FileExists(path)
}
func (t *typesFS) ReadFile(path string) (contents string, ok bool) {
contents, ok = t.FS.ReadFile(path)
if ok {
return contents, ok
}
embeddedPath := t.resolveEmbeddedPath(path)
if embeddedPath != "" {
contents, ok = t.types.ReadFile(embeddedPath)
}
return contents, ok
}
func (c *typesFS) resolveEmbeddedPath(path string) string {
rel, err := filepath.Rel(c.projectRoot, path)
if err != nil {
return ""
}
if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
return ""
}
return "/" + filepath.ToSlash(rel)
}
func mergeAndSort(a, b []string) []string {
m := make(map[string]struct{}, len(a)+len(b))
for _, v := range append(a, b...) {
m[v] = struct{}{}
}
return slices.Sorted(maps.Keys(m))
}
+158
View File
@@ -0,0 +1,158 @@
package main
import (
"encoding/json"
"fmt"
"path/filepath"
"reflect"
"strings"
"sync"
"time"
tscore "github.com/frida/typescript-go/pkg/core"
"github.com/frida/typescript-go/pkg/tsoptions"
"github.com/frida/typescript-go/pkg/tspath"
)
type TSConfigCache struct {
projectRoot string
sourceMap bool
tsconfigPath string
onChange ConfigChangeCallback
mu sync.Mutex
lastModTime time.Time
cachedOpts *tscore.CompilerOptions
lastText string
}
type ConfigChangeCallback func()
func NewTSConfigCache(
projectRoot string,
sourceMap bool,
callback ConfigChangeCallback,
) *TSConfigCache {
return &TSConfigCache{
projectRoot: projectRoot,
sourceMap: sourceMap,
tsconfigPath: filepath.Join(projectRoot, "tsconfig.json"),
lastModTime: time.Time{},
cachedOpts: nil,
lastText: "",
onChange: callback,
}
}
func (c *TSConfigCache) GetCompilerOptions(
host tsoptions.ParseConfigHost,
) (*tscore.CompilerOptions, string, error) {
c.mu.Lock()
defer c.mu.Unlock()
fs := host.FS()
info := fs.Stat(c.tsconfigPath)
var currentModTime time.Time
if info != nil {
currentModTime = info.ModTime()
} else {
currentModTime = time.Time{}
}
if c.cachedOpts != nil && currentModTime.Equal(c.lastModTime) {
return c.cachedOpts, c.lastText, nil
}
var tsconfigText string
if info != nil {
data, ok := fs.ReadFile(c.tsconfigPath)
if !ok {
return nil, "", fmt.Errorf("Unable to read %q", c.tsconfigPath)
}
tsconfigText = string(data)
} else {
tsconfigText = "{}"
}
parsedSource := tsoptions.NewTsconfigSourceFileFromFilePath(
tspath.NormalizePath(c.tsconfigPath),
tspath.ToPath(c.tsconfigPath, "", fs.UseCaseSensitiveFileNames()),
tsconfigText,
)
parsedCommandLine := tsoptions.ParseJsonSourceFileConfigFileContent(
parsedSource,
host,
c.projectRoot,
nil,
c.tsconfigPath,
nil, nil, nil,
)
if len(parsedCommandLine.Errors) > 0 {
var msgs []string
for _, diag := range parsedCommandLine.Errors {
msgs = append(msgs, diag.Message())
}
return nil, "", fmt.Errorf(
"Failed to parse %s: %s",
c.tsconfigPath,
strings.Join(msgs, "; "),
)
}
newOpts := parsedCommandLine.CompilerOptions()
newOpts.Module = tscore.ModuleKindNode16
newOpts.ModuleResolution = tscore.ModuleResolutionKindNode16
newOpts.NoEmit = tscore.TSFalse
sourceMapOptVal := boolToTristate(c.sourceMap)
newOpts.SourceMap = sourceMapOptVal
newOpts.InlineSourceMap = sourceMapOptVal
if newOpts.Target == tscore.ScriptTargetNone {
newOpts.Target = tscore.ScriptTargetES2022
}
if newOpts.Lib == nil {
newOpts.Lib = []string{"lib.es2022.d.ts"}
}
if newOpts.SkipLibCheck == tscore.TSUnknown {
newOpts.SkipLibCheck = tscore.TSTrue
}
if newOpts.Strict == tscore.TSUnknown {
newOpts.Strict = tscore.TSTrue
}
tsconfigData, _ := json.Marshal(parsedCommandLine.ParsedConfig)
tsconfigText = string(tsconfigData)
hadPreviousOpts := c.cachedOpts != nil
optsChanged := true
if c.cachedOpts != nil && reflect.DeepEqual(newOpts, c.cachedOpts) {
optsChanged = false
}
if optsChanged {
c.cachedOpts = newOpts
c.lastText = tsconfigText
}
c.lastModTime = currentModTime
c.mu.Unlock()
defer c.mu.Lock()
if hadPreviousOpts && optsChanged {
if c.onChange != nil {
c.onChange()
}
}
return newOpts, tsconfigText, nil
}
func boolToTristate(val bool) tscore.Tristate {
if val {
return tscore.TSTrue
}
return tscore.TSFalse
}
-11
View File
@@ -1,11 +0,0 @@
{
"compilerOptions": {
"target": "es2020",
"lib": ["es2020"],
"module": "ES2020",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"strict": true,
"noEmit": true
}
}
Loaded 100 of 311 files, more files were not shown because too many files have changed in this diff. Show more