From e7f3a0b3ab5ac459a8b9b72a9529fa5193307c4f Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:33:42 +0600 Subject: [PATCH 1/6] jvm: Fix JDK 8 lookup and code cache sweep Drop unused Method::jmethod_id symbol entries that are absent in Temurin JDK 8 builds. Check the optional UseCompiler flag before invoking code cache sweeps so reverting methods under -Xint does not hang waiting on a sweeper thread that HotSpot never starts. On JDK 8 (which lacks NMethodSweeper::force_sweep()), look up the optional NMethodSweeper::_sweep_started flag and claim it inside a safepoint instead of checking _should_sweep == 0. In OpenJDK 8, _should_sweep stays set to 1 while compiler threads are idle, so checking _should_sweep skipped sweep_code_cache() indefinitely. Also use Int64.add() and Int64.compare() when tracking traversal counts. --- lib/jvm.js | 75 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 17 deletions(-) diff --git a/lib/jvm.js b/lib/jvm.js index 0319cdb..3650ebf 100644 --- a/lib/jvm.js +++ b/lib/jvm.js @@ -61,7 +61,6 @@ function _getApi () { 'Method::size': ['Method::size', 'int', ['int']], 'Method::set_native_function': ['Method::set_native_function', 'void', ['pointer', 'pointer', 'int']], 'Method::clear_native_function': ['Method::clear_native_function', 'void', ['pointer']], - 'Method::jmethod_id': ['Method::jmethod_id', 'pointer', ['pointer']], 'ClassLoaderDataGraph::classes_do': ['ClassLoaderDataGraph::classes_do', 'void', ['pointer']], 'NMethodSweeper::sweep_code_cache': ['NMethodSweeper::sweep_code_cache', 'void', []], 'OopMapCache::flush_obsolete_entries': ['OopMapCache::flush_obsolete_entries', 'void', ['pointer']] @@ -87,9 +86,17 @@ function _getApi () { }, 'NMethodSweeper::_should_sweep': function (address) { this.shouldSweep = address; + }, + 'NMethodSweeper::_sweep_started': function (address) { + this.sweepStarted = address; + }, + UseCompiler: function (address) { + this.useCompiler = address; } }, optionals: [ + 'NMethodSweeper::_sweep_started', + 'UseCompiler' ] }] // If platform is not Windows @@ -106,7 +113,6 @@ function _getApi () { // JDK < 17 _ZN6Method24restore_unshareable_infoEP6Thread: ['Method::restore_unshareable_info', 'void', ['pointer', 'pointer']], _ZN6Method11link_methodERK12methodHandleP10JavaThread: ['Method::link_method', 'void', ['pointer', 'pointer', 'pointer']], - _ZN6Method10jmethod_idEv: ['Method::jmethod_id', 'pointer', ['pointer']], _ZN6Method10clear_codeEv: function (address) { const clearCode = new NativeFunction(address, 'void', ['pointer'], nativeFunctionOptions); this['Method::clear_code'] = function (thisPtr) { @@ -232,6 +238,12 @@ function _getApi () { }, _ZN14NMethodSweeper13_should_sweepE: function (address) { this.shouldSweep = address; + }, + _ZN14NMethodSweeper14_sweep_startedE: function (address) { + this.sweepStarted = address; + }, + UseCompiler: function (address) { + this.useCompiler = address; } }, optionals: [ @@ -270,7 +282,9 @@ function _getApi () { '_ZN13InstanceKlass33create_new_default_vtable_indicesEiP10JavaThread', '_ZN13InstanceKlass33create_new_default_vtable_indicesEiP6Thread', - '_ZN14NMethodSweeper21_sweep_fractions_leftE' + '_ZN14NMethodSweeper21_sweep_fractions_leftE', + '_ZN14NMethodSweeper14_sweep_startedE', + 'UseCompiler' ] }]; @@ -541,13 +555,19 @@ function forceSweep (env) { const { fractions, shouldSweep, + sweepStarted, traversals, + useCompiler, 'NMethodSweeper::sweep_code_cache': sweep, 'NMethodSweeper::sweep_in_progress': inProgress, 'NMethodSweeper::force_sweep': force, JVM_Sleep: sleep } = getApi(); + if (useCompiler !== undefined && useCompiler.readU8() === 0) { + return; + } + if (force !== undefined) { Thread.sleep(0.05); force(); @@ -555,26 +575,47 @@ function forceSweep (env) { force(); } else { let trav = traversals.readS64(); - const endTrav = trav + 2; + const endTrav = trav.add(2); - while (endTrav > trav) { - // Force a full sweep if already in progress. - fractions.writeS32(1); - sleep(env, NULL, 50); + while (trav.compare(endTrav) < 0) { + if (sweepStarted !== undefined) { + let claimed = false; - // Check if current nmethod is set. - if (!inProgress()) { - // Force mark_active_nmethods on exit from safepoint. withJvmThread(() => { - Thread.sleep(0.05); + if (sweepStarted.readS32() === 0) { + sweepStarted.writeS32(1); + claimed = true; + } }); - } - const sweepNotAlreadyInProgress = shouldSweep.readU8() === 0; - if (sweepNotAlreadyInProgress) { - // Sanity check to not divide by 0. + if (claimed) { + try { + if (inProgress()) { + fractions.writeS32(1); + sweep(); + fractions.writeS32(0); + } + } finally { + sweepStarted.writeS32(0); + } + } else { + fractions.writeS32(1); + sleep(env, NULL, 50); + } + } else { fractions.writeS32(1); - sweep(); + sleep(env, NULL, 50); + + if (!inProgress()) { + withJvmThread(() => { + Thread.sleep(0.05); + }); + } + + if (shouldSweep.readU8() === 0) { + fractions.writeS32(1); + sweep(); + } } trav = traversals.readS64(); From eed6f038f3224a93374a95b3cf8da23614310849 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 20:34:47 +0600 Subject: [PATCH 2/6] tests: Parse script messages with json-glib Parse Frida script JSON messages in runner.c using json-glib (already linked via libfrida-gumjs.a) instead of org.json in Script.java, and fail fast with an explicit IllegalStateException on script message timeout. This ensures uniform payload serialization across Android and HotSpot JVM (matching string, boolean, number, array, object, and null values) without depending on Android's built-in org.json implementation. --- test/re/frida/Script.java | 29 ++++---------- test/runner.c | 79 ++++++++++++++++++++++++++++++++++----- 2 files changed, 78 insertions(+), 30 deletions(-) diff --git a/test/re/frida/Script.java b/test/re/frida/Script.java index 9fefdba..14c9332 100644 --- a/test/re/frida/Script.java +++ b/test/re/frida/Script.java @@ -5,9 +5,6 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -import org.json.JSONException; -import org.json.JSONObject; - public class Script implements Closeable { private long handle; private LinkedBlockingQueue pending = new LinkedBlockingQueue<>(); @@ -35,29 +32,19 @@ public void close() throws IOException { public String getNextMessage() { try { - return pending.poll(5, TimeUnit.SECONDS); + String message = pending.poll(5, TimeUnit.SECONDS); + if (message == null) { + throw new IllegalStateException("timed out waiting for a message from the" + + " script; see stderr and logcat for errors raised by it"); + } + return message; } catch (InterruptedException e) { return getNextMessage(); } } - private void onMessage(String rawMessage) { - try { - JSONObject message = new JSONObject(rawMessage); - - String type = message.getString("type"); - if (type.equals("send")) { - pending.add(message.getString("payload")); - } else if (type.equals("log")) { - System.out.println(message.getString("payload")); - } else if (type.equals("error")) { - System.err.println(message.getString("stack")); - } else { - System.err.println(rawMessage); - } - } catch (JSONException e) { - e.printStackTrace(); - } + private void onMessage(String payload) { + pending.add(payload); } private native long create(String sourceCode); diff --git a/test/runner.c b/test/runner.c index 9c41e29..3382555 100644 --- a/test/runner.c +++ b/test/runner.c @@ -465,21 +465,82 @@ on_unload_ready (GObject * source_object, GAsyncResult * result, gpointer user_d static void re_frida_script_on_message (const gchar * message, GBytes * data, gpointer user_data) { - JNIEnv * env; - jweak weak_wrapper = user_data; - jobject wrapper; + JsonNode * root; + JsonObject * object; + const gchar * type; - env = frida_java_get_env (); + root = json_from_string (message, NULL); + if (root == NULL || !JSON_NODE_HOLDS_OBJECT (root)) + { + g_printerr ("%s\n", message); + if (root != NULL) + json_node_unref (root); + return; + } - (*env)->PushLocalFrame (env, 3); + object = json_node_get_object (root); + type = json_object_get_string_member_with_default (object, "type", ""); - wrapper = (*env)->NewLocalRef (env, weak_wrapper); - if (wrapper != NULL) + if (strcmp (type, "send") == 0) + { + JsonNode * payload_node; + const gchar * payload; + gchar * payload_owned = NULL; + JNIEnv * env; + jweak weak_wrapper = user_data; + jobject wrapper; + + payload_node = json_object_get_member (object, "payload"); + if (payload_node == NULL) + { + payload = "null"; + } + else if (JSON_NODE_HOLDS_VALUE (payload_node) && json_node_get_value_type (payload_node) == G_TYPE_STRING) + { + payload = json_node_get_string (payload_node); + } + else + { + payload_owned = json_to_string (payload_node, FALSE); + payload = payload_owned; + } + + env = frida_java_get_env (); + + (*env)->PushLocalFrame (env, 3); + + wrapper = (*env)->NewLocalRef (env, weak_wrapper); + if (wrapper != NULL) + { + gunichar2 * utf16; + glong utf16_len; + jstring payload_value; + + utf16 = g_utf8_to_utf16 (payload, -1, NULL, &utf16_len, NULL); + payload_value = (*env)->NewString (env, utf16, utf16_len); + g_free (utf16); + + (*env)->CallVoidMethod (env, wrapper, re_frida_script_on_message_method, payload_value); + } + + (*env)->PopLocalFrame (env, NULL); + + g_free (payload_owned); + } + else if (strcmp (type, "log") == 0) { - (*env)->CallVoidMethod (env, wrapper, re_frida_script_on_message_method, (*env)->NewStringUTF (env, message)); + g_print ("%s\n", json_object_get_string_member_with_default (object, "payload", "")); + } + else if (strcmp (type, "error") == 0) + { + g_printerr ("%s\n", json_object_get_string_member_with_default (object, "stack", message)); + } + else + { + g_printerr ("%s\n", message); } - (*env)->PopLocalFrame (env, NULL); + json_node_unref (root); } static void From 367569f2e0efe057e8e0519cc0010f43f3403de3 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 22:41:53 +0600 Subject: [PATCH 3/6] tests: Support Android API levels up to 36 Bring the Android test runner, Makefiles, and GitHub Actions workflow up to date for modern Android API levels and improve reliability: - Clamp APP_PLATFORM in test/Application.mk to the NDK's maximum supported API level from meta/platforms.json and handle major.minor API levels across test/Application.mk and test/Makefile for platform paths, sysroot, and d8 --min-api. - Implement multi-handler sigchain support in test/runner.c so ART's implicit null-check and stack-overflow fault handlers are dispatched and chained properly to any previous signal handler. - Expand the CI matrix to API levels 26-36 with fail-fast disabled, auto-detect the latest installed build-tools directory, remove the stale x86 exclusion, and cache downloaded test dependencies. - Rebuild build/frida-java-bridge.js whenever bridge sources change, deploy once in `make check` using `adb push --sync` with an explicit libartpalette.so prerequisite, use atomic `curl -fsSL` downloads (with Maven Central for hamcrest-core), pass `-o` to `unzip`, fix watch quoting and LD_PRELOAD, dump scoped crash/warning logcat since the test start timestamp on failure, and allow filtering test classes via TestRunner args. --- .github/workflows/tests.yml | 25 ++++++--- Makefile | 7 +-- test/Application.mk | 5 +- test/Makefile | 50 ++++++++++++------ test/re/frida/TestRunner.java | 16 +++--- test/runner.c | 95 +++++++++++++++++++++++++++++++++-- 6 files changed, 163 insertions(+), 35 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9dbced4..f89d926 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,19 +4,27 @@ jobs: tests: runs-on: ubuntu-latest strategy: + fail-fast: false matrix: - api: [26, 27, 28, 29, 30, 31] + api: [26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] arch: [x86_64] - exclude: - - api: 30 - arch: x86 - - api: 31 - arch: x86 env: - ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: 200 # Default is 20 + ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: 200 steps: - name: Check out repo uses: actions/checkout@v4 + - name: Cache test dependencies + uses: actions/cache@v4 + with: + path: | + ~/.npm + test/build/junit.jar + test/build/hamcrest.jar + test/build/obj/local/${{ matrix.arch }}/frida-gumjs.h + test/build/obj/local/${{ matrix.arch }}/libfrida-gumjs.a + key: android-deps-${{ matrix.arch }}-${{ hashFiles('test/Makefile', 'package-lock.json', 'test/package-lock.json') }} + restore-keys: | + android-deps-${{ matrix.arch }}- - name: Enable KVM run: | echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules @@ -50,7 +58,8 @@ jobs: disable-animations: true script: >- sdkmanager "platforms;android-${{ matrix.api }}" - && PATH="$ANDROID_SDK_ROOT/build-tools/34.0.0:$PATH" + && BUILD_TOOLS_DIR="$(ls -d "$ANDROID_SDK_ROOT/build-tools/"* | sort -V | tail -n 1)" + && PATH="$BUILD_TOOLS_DIR:$PATH" ANDROID_ARCH=${{ matrix.arch }} ANDROID_ABI=${{ matrix.arch }} ANDROID_API_LEVEL=${{ matrix.api }} diff --git a/Makefile b/Makefile index 3454863..adba877 100644 --- a/Makefile +++ b/Makefile @@ -2,14 +2,15 @@ all: @echo "Nothing to build. To run the test-suite: make check" check: node_modules + $(MAKE) -C test deploy @echo "" @echo "[*] Running the test suite with optimizations disabled (interpreter mode)." @echo "" - @$(MAKE) check-run + @$(MAKE) -C test run @echo "" @echo "[*] Running the test suite with optimizations enabled." @echo "" - @$(MAKE) RUNNER_ARGS="--enable-optimizations" check-run + @$(MAKE) -C test RUNNER_ARGS="--enable-optimizations" run check-run: node_modules $(MAKE) -C test deploy @@ -30,4 +31,4 @@ clean: rm -rf node_modules $(MAKE) -C test clean -.PHONY: all check check-gdb develop clean +.PHONY: all check check-run check-gdb develop clean diff --git a/test/Application.mk b/test/Application.mk index 45ad11f..2b0d386 100644 --- a/test/Application.mk +++ b/test/Application.mk @@ -1,6 +1,9 @@ include config.mk +android_api_major := $(firstword $(subst ., ,$(ANDROID_API_LEVEL))) +ndk_max_api := $(shell sed -n 's/^[[:space:]]*"max":[[:space:]]*\([0-9]*\).*/\1/p' $(ANDROID_NDK_ROOT)/meta/platforms.json 2>/dev/null) + APP_ABI := $(ANDROID_ABI) -APP_PLATFORM := android-$(ANDROID_API_LEVEL) +APP_PLATFORM := android-$(firstword $(sort $(android_api_major) $(ndk_max_api))) APP_STL := c++_static APP_BUILD_SCRIPT := Android.mk diff --git a/test/Makefile b/test/Makefile index aff3fd2..dcc713c 100644 --- a/test/Makefile +++ b/test/Makefile @@ -2,8 +2,10 @@ include config.mk build_os_arch := $(shell uname -s | tr -s "[A-Z]" "[a-z]")-$(shell uname -m) -android_platform := android-$(ANDROID_API_LEVEL) -android_sysroot := $(ANDROID_NDK_ROOT)/platforms/$(android_platform)/arch-$(ANDROID_ARCH) +android_api_major := $(firstword $(subst ., ,$(ANDROID_API_LEVEL))) +android_platform := $(if $(wildcard $(ANDROID_SDK_ROOT)/platforms/android-$(ANDROID_API_LEVEL)/android.jar),android-$(ANDROID_API_LEVEL),$(notdir $(lastword $(sort $(wildcard $(ANDROID_SDK_ROOT)/platforms/android-$(ANDROID_API_LEVEL).*))))) +android_platform := $(if $(android_platform),$(android_platform),android-$(ANDROID_API_LEVEL)) +android_sysroot := $(ANDROID_NDK_ROOT)/platforms/android-$(android_api_major)/arch-$(ANDROID_ARCH) deploy_prefix := /data/local/tmp deploy_data_dir := $(deploy_prefix)/frida-java-bridge-tests @@ -13,28 +15,41 @@ frida_version := 17.26.3 test_sources := $(wildcard re/frida/*.java) test_classes := $(patsubst %.java,%.class,$(test_sources)) +bridge_sources := bundle.js ../index.js $(wildcard ../lib/*.js) android_jar := $(ANDROID_SDK_ROOT)/platforms/$(android_platform)/android.jar +android_deploy_files := \ + build/$(ANDROID_ABI)/runner \ + build/$(ANDROID_ABI)/libartpalette.so \ + build/tests.dex \ + build/frida-java-bridge.js + all: @echo "Available targets: deploy run" clean: rm -rf build -deploy: build/$(ANDROID_ABI)/runner build/tests.dex build/frida-java-bridge.js - adb shell "rm -rf $(deploy_data_dir) && mkdir -p $(deploy_data_dir)" - adb push $^ build/$(ANDROID_ABI)/libartpalette.so $(deploy_data_dir) +deploy: $(android_deploy_files) + adb shell "mkdir -p $(deploy_data_dir) $(deploy_cache_dir)" + adb push --sync $(android_deploy_files) $(deploy_data_dir)/ run: - adb shell "LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)" + @since=$$(adb shell 'date "+%m-%d %H:%M:%S.000"' | tr -d '\r'); \ + adb shell "LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)" || { \ + status=$$?; \ + adb logcat -d -T "$$since" -b crash || true; \ + adb logcat -d -T "$$since" -b main *:W || true; \ + exit $$status; \ + } watch: npm run watch & ./node_modules/.bin/chokidar \ build/frida-java-bridge.js \ - -c "adb push build/frida-java-bridge.js $(deploy_data_dir) \ - && adb shell 'LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)'" + -c "adb push --sync build/frida-java-bridge.js $(deploy_data_dir)/ \ + && adb shell \"LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)\"" debug: build/gdb.setup adb shell "rm -f $(deploy_data_dir)/debug-socket" @@ -60,6 +75,9 @@ build/symbols.stamp: adb pull -a $(shell adb shell "ls $(ANDROID_LIBDIR)/*.so") build/symbols/$(ANDROID_LIBDIR)/; \ touch $@ +build/$(ANDROID_ABI)/libartpalette.so: build/$(ANDROID_ABI)/runner + @test -f $@ + build/$(ANDROID_ABI)/runner: runner.c artpalette.c build/obj/local/$(ANDROID_ABI)/libfrida-gumjs.a $(ANDROID_NDK_ROOT)/ndk-build \ NDK_PROJECT_PATH=$$(pwd) \ @@ -71,15 +89,17 @@ build/$(ANDROID_ABI)/runner: runner.c artpalette.c build/obj/local/$(ANDROID_ABI build/obj/local/$(ANDROID_ABI)/libfrida-gumjs.a: @mkdir -p $(@D) - curl -Ls https://github.com/frida/frida/releases/download/$(frida_version)/frida-gumjs-devkit-$(frida_version)-android-$(ANDROID_ARCH).tar.xz | tar -xJf - -C $(@D) + curl -fsSL https://github.com/frida/frida/releases/download/$(frida_version)/frida-gumjs-devkit-$(frida_version)-android-$(ANDROID_ARCH).tar.xz -o $@.tar.xz.tmp + tar -xJf $@.tar.xz.tmp -C $(@D) + rm -f $@.tar.xz.tmp build/tests.dex: build/tests.jar d8 \ --output build/tests.zip \ --classpath $(android_jar) \ - --min-api $(ANDROID_API_LEVEL) \ + --min-api $(android_api_major) \ $< - cd build && unzip tests.zip classes.dex + cd build && unzip -o tests.zip classes.dex mv build/classes.dex $@ build/tests.jar: $(test_sources) build/junit.jar build/hamcrest.jar @@ -101,13 +121,15 @@ build/tests.jar: $(test_sources) build/junit.jar build/hamcrest.jar build/junit.jar: @mkdir -p $(@D) - curl -Ls https://github.com/junit-team/junit4/releases/download/r4.12/junit-4.12.jar > $@ + curl -fsSL https://github.com/junit-team/junit4/releases/download/r4.12/junit-4.12.jar -o $@.tmp + mv $@.tmp $@ build/hamcrest.jar: @mkdir -p $(@D) - curl -Ls https://search.maven.org/remotecontent?filepath=org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar > $@ + curl -fsSL https://repo1.maven.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar -o $@.tmp + mv $@.tmp $@ -build/frida-java-bridge.js: node_modules +build/frida-java-bridge.js: node_modules $(bridge_sources) npm run build node_modules: package.json diff --git a/test/re/frida/TestRunner.java b/test/re/frida/TestRunner.java index 8be36bf..777495d 100644 --- a/test/re/frida/TestRunner.java +++ b/test/re/frida/TestRunner.java @@ -4,6 +4,7 @@ import java.io.File; import java.io.FileInputStream; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import org.junit.runner.JUnitCore; @@ -24,12 +25,15 @@ public static void main(String[] args, String dataDir, String cacheDir, registerClassLoader(TestRunner.class.getClassLoader()); - JUnitCore.main( - "re.frida.ClassRegistryTest", - "re.frida.MethodTest", - "re.frida.ClassCreationTest", - "re.frida.PerformTest" - ); + String[] classes = (args.length > 1) + ? Arrays.copyOfRange(args, 1, args.length) + : new String[] { + "re.frida.ClassRegistryTest", + "re.frida.MethodTest", + "re.frida.ClassCreationTest", + "re.frida.PerformTest" + }; + JUnitCore.main(classes); } public static String getCacheDir() { diff --git a/test/runner.c b/test/runner.c index 3382555..8f7fcb8 100644 --- a/test/runner.c +++ b/test/runner.c @@ -2,11 +2,14 @@ #include #include #include +#include #include +#include #include typedef struct _CreateScriptOperation CreateScriptOperation; typedef struct _DestroyScriptOperation DestroyScriptOperation; +typedef struct _SigchainAction SigchainAction; struct _CreateScriptOperation { @@ -31,6 +34,13 @@ struct _DestroyScriptOperation GCond cond; }; +struct _SigchainAction +{ + bool (* sc_sigaction) (int, siginfo_t *, void *); + sigset_t sc_mask; + guint64 sc_flags; +}; + static void frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations); static void frida_java_register_test_runner_api (JNIEnv * env); static void frida_java_register_script_api (JNIEnv * env); @@ -54,6 +64,8 @@ static void destroy_weak_ref (jweak ref); static guint get_system_api_level (void); +static void on_special_signal (int signo, siginfo_t * info, void * context); + static const JNINativeMethod re_frida_test_runner_methods[] = { { "registerClassLoader", "(Ljava/lang/ClassLoader;)V", re_frida_test_runner_register_class_loader }, @@ -78,6 +90,12 @@ static jobject re_frida_test_runner_class_loader; static jmethodID re_frida_script_on_message_method; +#define MAX_SPECIAL_HANDLERS 4 + +static SigchainAction special_handlers[NSIG][MAX_SPECIAL_HANDLERS]; +static guint special_handler_count[NSIG]; +static struct sigaction previous_action[NSIG]; + int main (int argc, char * argv[]) { @@ -606,13 +624,84 @@ SetSpecialSignalHandlerFn (int signal, gpointer fn) } void -AddSpecialSignalHandlerFn (int signal, gpointer sa) +AddSpecialSignalHandlerFn (int signal, SigchainAction * sa) { - /* g_print ("AddSpecialSignalHandlerFn(signal=%d)\n", signal); */ + guint count; + struct sigaction action; + + if (signal <= 0 || signal >= NSIG) + return; + + count = special_handler_count[signal]; + if (count >= MAX_SPECIAL_HANDLERS) + return; + + special_handlers[signal][count] = *sa; + special_handler_count[signal] = count + 1; + + if (count == 0) + { + memset (&action, 0, sizeof (action)); + action.sa_sigaction = on_special_signal; + action.sa_flags = SA_SIGINFO | SA_ONSTACK; + action.sa_mask = sa->sc_mask; + + sigaction (signal, &action, &previous_action[signal]); + } } void RemoveSpecialSignalHandlerFn (int signal, bool (* fn) (int, siginfo_t *, void *)) { - /* g_print ("RemoveSpecialSignalHandlerFn(signal=%d)\n", signal); */ + guint count, i; + + if (signal <= 0 || signal >= NSIG) + return; + + count = special_handler_count[signal]; + for (i = 0; i != count; i++) + { + if (special_handlers[signal][i].sc_sigaction == fn) + { + guint j; + + for (j = i + 1; j != count; j++) + special_handlers[signal][j - 1] = special_handlers[signal][j]; + + special_handler_count[signal] = count - 1; + if (count == 1) + sigaction (signal, &previous_action[signal], NULL); + return; + } + } +} + +static void +on_special_signal (int signo, siginfo_t * info, void * context) +{ + guint count, i; + struct sigaction prev; + + count = special_handler_count[signo]; + for (i = 0; i != count; i++) + { + bool (* handler) (int, siginfo_t *, void *) = special_handlers[signo][i].sc_sigaction; + if (handler != NULL && handler (signo, info, context)) + return; + } + + prev = previous_action[signo]; + if ((prev.sa_flags & SA_SIGINFO) != 0 && prev.sa_sigaction != NULL) + { + prev.sa_sigaction (signo, info, context); + return; + } + + if ((prev.sa_flags & SA_SIGINFO) == 0 && prev.sa_handler != SIG_DFL && prev.sa_handler != SIG_IGN) + { + prev.sa_handler (signo); + return; + } + + sigaction (signo, &prev, NULL); } From ce0cc146931561b624599ccf6eeaaa1873639b42 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 22:42:13 +0600 Subject: [PATCH 4/6] tests: Work around Stalker slab allocation failure Install a 64-bit Linux GumMemoryHooks allocator in test/runner.c that probes a 64 MiB window before mapping Stalker slabs, working around gum_data_slab_new() NULL dereferences on Android API 35-36 (frida/frida-gum#793). Also call Stalker.unfollow() before send() in MethodTest.callCanBeTraced() so teardown is not traced into extra slabs. --- test/re/frida/MethodTest.java | 4 +- test/runner.c | 84 +++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/test/re/frida/MethodTest.java b/test/re/frida/MethodTest.java index f736ee6..52bf65d 100644 --- a/test/re/frida/MethodTest.java +++ b/test/re/frida/MethodTest.java @@ -208,8 +208,10 @@ public void callCanBeTraced() { "}" + "});" + - "send(returnZero.call(badger));" + + "var result = returnZero.call(badger);" + + "Stalker.unfollow();" + + "send(result);" + "Stalker.flush();"); assertEquals("0", script.getNextMessage()); assertEquals("onCallSummary", script.getNextMessage()); diff --git a/test/runner.c b/test/runner.c index 8f7fcb8..e7f14ce 100644 --- a/test/runner.c +++ b/test/runner.c @@ -5,6 +5,9 @@ #include #include #include +#if defined (__linux__) && defined (__LP64__) +# include +#endif #include typedef struct _CreateScriptOperation CreateScriptOperation; @@ -62,6 +65,11 @@ static void re_frida_badger_native_method (JNIEnv * env, jobject self, jstring s static void destroy_weak_ref (jweak ref); +#if defined (__linux__) && defined (__LP64__) +static gpointer frida_java_allocate_memory (const GumAddressSpec * spec, gsize size, gsize alignment, + GumPageProtection prot, gpointer user_data); +#endif + static guint get_system_api_level (void); static void on_special_signal (int signo, siginfo_t * info, void * context); @@ -113,6 +121,14 @@ main (int argc, char * argv[]) gum_init_embedded (); +#if defined (__linux__) && defined (__LP64__) + { + GumMemoryHooks hooks = { 0, }; + hooks.allocate = frida_java_allocate_memory; + gum_memory_set_hooks (&hooks); + } +#endif + js_scheduler = gum_script_backend_get_scheduler (); js_context = gum_script_scheduler_get_js_context (js_scheduler); gum_script_scheduler_enable_background_thread (js_scheduler); @@ -576,6 +592,74 @@ destroy_weak_ref (jweak ref) (*env)->DeleteWeakGlobalRef (env, ref); } +#if defined (__linux__) && defined (__LP64__) + +static gpointer +frida_java_allocate_memory (const GumAddressSpec * spec, + gsize size, + gsize alignment, + GumPageProtection prot, + gpointer user_data) +{ + GumPageProtection non_exec_prot = prot & ~GUM_PAGE_EXECUTE; + gpointer mem = NULL; + + if (spec != NULL) + { + mem = gum_memory_allocate_near (spec, size, alignment, non_exec_prot); + } + else + { + const gsize window_size = 64 * 1024 * 1024; + gsize page_size = gum_query_page_size (); + gsize effective_alignment = MAX (alignment, page_size); + gsize aligned_size = GUM_ALIGN_SIZE (size, page_size); + + if (aligned_size > 0 && + aligned_size <= (window_size / 4) && + effective_alignment <= (window_size / 4) && + (effective_alignment & (effective_alignment - 1)) == 0) + { + gpointer probe = mmap (NULL, window_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (probe != MAP_FAILED) + { + guint8 * probe_start = probe; + guint8 * probe_end = probe_start + window_size; + guint8 * target = GUM_ALIGN_POINTER (guint8 *, probe_start + (window_size / 2), effective_alignment); + gpointer mapped = mmap (target, aligned_size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + if (mapped == target) + { + munmap (probe_start, target - probe_start); + if (target + aligned_size < probe_end) + munmap (target + aligned_size, probe_end - (target + aligned_size)); + mem = mapped; + } + else + { + munmap (probe, window_size); + } + } + } + + if (mem == NULL) + mem = gum_memory_allocate (NULL, size, alignment, non_exec_prot); + } + + if (mem != NULL && prot != non_exec_prot) + { + if (!gum_try_mprotect (mem, size, prot)) + { + gum_memory_free (mem, size); + return NULL; + } + } + + return mem; +} + +#endif + static guint get_system_api_level (void) { From 6b9c49cdc0e2d4048bed49f163e4059b53e1a06b Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 22:42:54 +0600 Subject: [PATCH 5/6] tests: Add HotSpot JVM test runner and CI Run the test suite on HotSpot JVM in addition to Android ART across supported LTS releases (JDK 8, 11, and 17): - Extend test/runner.c to launch HotSpot via JNI_CreateJavaVM on non-Android platforms, guarding Android-only sigchain and AttachCurrentThread differences with #ifdef __ANDROID__, fixing destroy_weak_ref's GDestroyNotify signature for OpenJDK jni.h, converting script sources via GetStringChars + g_utf16_to_utf8 (since HotSpot GetStringUTFChars emits Modified UTF-8 for surrogate pairs like the ESM package header), and deferring script-load completion to a G_PRIORITY_LOW idle callback so pending Script.nextTick() hook installations finish before new Script() returns. - Add TestRunner.isAndroid() and TestRunner.getAndroidApiLevel() so ClassRegistryTest and MethodTest compile and run on HotSpot without android.jar, selecting Android-only suites (ClassCreationTest and PerformTest) only on Android. - Rename Android Makefile/CI targets, variables, and build outputs symmetrically (build-android, deploy-android, run-android, watch-android, debug-android, check-android, check-android-gdb, develop-android, android, tests-android.dex) alongside HotSpot targets (build-jvm, run-jvm, watch-jvm, debug-jvm, check-jvm, check-jvm-gdb, develop-jvm, jvm) and update README.md accordingly. - Add a `jvm` matrix job on ubuntu-latest with Temurin JDK 8, 11, and 17 running `make check-jvm` (both interpreter and JIT modes). --- .github/workflows/tests.yml | 36 ++++++- Makefile | 49 +++++---- README.md | 46 ++++++--- test/Makefile | 142 +++++++++++++++++++-------- test/re/frida/ClassRegistryTest.java | 2 +- test/re/frida/MethodTest.java | 4 + test/re/frida/TestRunner.java | 35 +++++-- test/runner.c | 107 ++++++++++++++++++-- 8 files changed, 333 insertions(+), 88 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f89d926..68fa860 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,7 +1,7 @@ name: tests on: [push, pull_request] jobs: - tests: + android: runs-on: ubuntu-latest strategy: fail-fast: false @@ -64,4 +64,36 @@ jobs: ANDROID_ABI=${{ matrix.arch }} ANDROID_API_LEVEL=${{ matrix.api }} ANDROID_LIBDIR=/system/${{ contains(matrix.arch, '64') && 'lib64' || 'lib' }} - make check + make check-android + + jvm: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + java: ['8', '11', '17'] + steps: + - name: Check out repo + uses: actions/checkout@v4 + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ matrix.java }} + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - name: Cache test dependencies + uses: actions/cache@v4 + with: + path: | + test/build/junit.jar + test/build/hamcrest.jar + test/build/jvm/frida-gumjs + key: jvm-deps-${{ hashFiles('test/Makefile') }} + restore-keys: | + jvm-deps- + - name: Run JVM tests + run: make check-jvm diff --git a/Makefile b/Makefile index adba877..9a51ef4 100644 --- a/Makefile +++ b/Makefile @@ -1,28 +1,43 @@ all: - @echo "Nothing to build. To run the test-suite: make check" + @echo "Nothing to build. To run the test-suite: make check-android or make check-jvm" -check: node_modules - $(MAKE) -C test deploy +check-android: node_modules + $(MAKE) -C test deploy-android @echo "" - @echo "[*] Running the test suite with optimizations disabled (interpreter mode)." + @echo "[*] Running the Android test suite with optimizations disabled (interpreter mode)." @echo "" - @$(MAKE) -C test run + @$(MAKE) -C test run-android @echo "" - @echo "[*] Running the test suite with optimizations enabled." + @echo "[*] Running the Android test suite with optimizations enabled." @echo "" - @$(MAKE) -C test RUNNER_ARGS="--enable-optimizations" run + @$(MAKE) -C test RUNNER_ARGS="--enable-optimizations" run-android -check-run: node_modules - $(MAKE) -C test deploy - $(MAKE) -C test run +check-android-gdb: node_modules + $(MAKE) -C test deploy-android + $(MAKE) -C test debug-android -check-gdb: node_modules - $(MAKE) -C test deploy - $(MAKE) -C test debug +develop-android: node_modules + $(MAKE) -C test deploy-android + $(MAKE) -C test watch-android -develop: node_modules - $(MAKE) -C test deploy - $(MAKE) -C test watch +check-jvm: node_modules + $(MAKE) -C test build-jvm + @echo "" + @echo "[*] Running the JVM test suite with optimizations disabled (interpreter mode)." + @echo "" + @$(MAKE) -C test run-jvm + @echo "" + @echo "[*] Running the JVM test suite with optimizations enabled." + @echo "" + @$(MAKE) -C test RUNNER_ARGS="--enable-optimizations" run-jvm + +check-jvm-gdb: node_modules + $(MAKE) -C test build-jvm + $(MAKE) -C test debug-jvm + +develop-jvm: node_modules + $(MAKE) -C test build-jvm + $(MAKE) -C test watch-jvm node_modules: package.json npm install @@ -31,4 +46,4 @@ clean: rm -rf node_modules $(MAKE) -C test clean -.PHONY: all check check-run check-gdb develop clean +.PHONY: all check-android check-android-gdb develop-android check-jvm check-jvm-gdb develop-jvm clean diff --git a/README.md b/README.md index 7c391a1..3fa0f12 100644 --- a/README.md +++ b/README.md @@ -5,36 +5,60 @@ through the global named `Java`. ## Running the test-suite -### Dependencies +### Android -- Android SDK Platform-Tools >= 27.0.1 -- Android NDK r21 +#### Dependencies + +- Android SDK Platform-Tools >= 29.0.6 +- Android NDK r21+ With environment configured accordingly: ```sh $ export ANDROID_SDK_ROOT=~/Library/Android/Sdk -$ export ANDROID_NDK_ROOT=/usr/local/opt/android-ndk-r21 +$ export ANDROID_NDK_ROOT=/usr/local/opt/android-ndk-r25b ``` -### Configuration +#### Configuration - Go to `/test/config.mk` for editing the device configuration settings. -### Run +#### Run + +```sh +$ make check-android +``` + +#### Debug + +```sh +$ make check-android-gdb +``` + +#### Auto-run tests on JavaScript change + +```sh +$ make develop-android +``` + +### HotSpot JVM + +With `JAVA_HOME` pointing to a HotSpot JDK (JDK 8–17 on Linux x86_64): + +#### Run ```sh -$ make check +$ make check-jvm ``` -### Debug +#### Debug ```sh -$ make check-gdb +$ make check-jvm-gdb ``` -### Auto-run tests on JavaScript change +#### Auto-run tests on JavaScript change ```sh -$ make develop +$ make develop-jvm ``` diff --git a/test/Makefile b/test/Makefile index dcc713c..784b3d4 100644 --- a/test/Makefile +++ b/test/Makefile @@ -1,20 +1,23 @@ include config.mk build_os_arch := $(shell uname -s | tr -s "[A-Z]" "[a-z]")-$(shell uname -m) +jvm_arch := $(shell uname -m) +JAVA_HOME ?= $(shell dirname $$(dirname $$(readlink -f $$(which javac)))) +jvm_lib := $(firstword $(wildcard $(JAVA_HOME)/lib/server/libjvm.so $(JAVA_HOME)/jre/lib/amd64/server/libjvm.so)) android_api_major := $(firstword $(subst ., ,$(ANDROID_API_LEVEL))) android_platform := $(if $(wildcard $(ANDROID_SDK_ROOT)/platforms/android-$(ANDROID_API_LEVEL)/android.jar),android-$(ANDROID_API_LEVEL),$(notdir $(lastword $(sort $(wildcard $(ANDROID_SDK_ROOT)/platforms/android-$(ANDROID_API_LEVEL).*))))) android_platform := $(if $(android_platform),$(android_platform),android-$(ANDROID_API_LEVEL)) android_sysroot := $(ANDROID_NDK_ROOT)/platforms/android-$(android_api_major)/arch-$(ANDROID_ARCH) -deploy_prefix := /data/local/tmp -deploy_data_dir := $(deploy_prefix)/frida-java-bridge-tests -deploy_cache_dir := $(deploy_data_dir)/dalvik-cache +android_deploy_prefix := /data/local/tmp +android_deploy_data_dir := $(android_deploy_prefix)/frida-java-bridge-tests +android_deploy_cache_dir := $(android_deploy_data_dir)/dalvik-cache frida_version := 17.26.3 -test_sources := $(wildcard re/frida/*.java) -test_classes := $(patsubst %.java,%.class,$(test_sources)) +android_test_sources := $(wildcard re/frida/*.java) +jvm_test_sources := $(filter-out re/frida/ClassCreationTest.java re/frida/PerformTest.java,$(android_test_sources)) bridge_sources := bundle.js ../index.js $(wildcard ../lib/*.js) android_jar := $(ANDROID_SDK_ROOT)/platforms/$(android_platform)/android.jar @@ -22,57 +25,76 @@ android_jar := $(ANDROID_SDK_ROOT)/platforms/$(android_platform)/android.jar android_deploy_files := \ build/$(ANDROID_ABI)/runner \ build/$(ANDROID_ABI)/libartpalette.so \ - build/tests.dex \ + build/tests-android.dex \ build/frida-java-bridge.js all: - @echo "Available targets: deploy run" + @echo "Available targets: build-android deploy-android run-android watch-android debug-android build-jvm run-jvm watch-jvm debug-jvm" clean: rm -rf build -deploy: $(android_deploy_files) - adb shell "mkdir -p $(deploy_data_dir) $(deploy_cache_dir)" - adb push --sync $(android_deploy_files) $(deploy_data_dir)/ +build-android: $(android_deploy_files) -run: +deploy-android: build-android + adb shell "mkdir -p $(android_deploy_data_dir) $(android_deploy_cache_dir)" + adb push --sync $(android_deploy_files) $(android_deploy_data_dir)/ + +run-android: @since=$$(adb shell 'date "+%m-%d %H:%M:%S.000"' | tr -d '\r'); \ - adb shell "LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)" || { \ + adb shell "LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(android_deploy_data_dir)' $(android_deploy_data_dir)/runner $(RUNNER_ARGS)" || { \ status=$$?; \ adb logcat -d -T "$$since" -b crash || true; \ adb logcat -d -T "$$since" -b main *:W || true; \ exit $$status; \ } -watch: +watch-android: npm run watch & ./node_modules/.bin/chokidar \ build/frida-java-bridge.js \ - -c "adb push --sync build/frida-java-bridge.js $(deploy_data_dir)/ \ - && adb shell \"LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(deploy_data_dir)' $(deploy_data_dir)/runner $(RUNNER_ARGS)\"" + -c "adb push --sync build/frida-java-bridge.js $(android_deploy_data_dir)/ \ + && adb shell \"LD_PRELOAD=$(ANDROID_VM) LD_LIBRARY_PATH='$(APEX_LIBDIRS):$(android_deploy_data_dir)' $(android_deploy_data_dir)/runner $(RUNNER_ARGS)\"" -debug: build/gdb.setup - adb shell "rm -f $(deploy_data_dir)/debug-socket" - adb push $(ANDROID_NDK_ROOT)/prebuilt/android-$(ANDROID_ARCH)/gdbserver/gdbserver $(deploy_data_dir) - adb shell "$(deploy_data_dir)/gdbserver +$(deploy_data_dir)/debug-socket $(deploy_data_dir)/runner $(RUNNER_ARGS)" & +debug-android: build/gdb-android.setup + adb shell "rm -f $(android_deploy_data_dir)/debug-socket" + adb push $(ANDROID_NDK_ROOT)/prebuilt/android-$(ANDROID_ARCH)/gdbserver/gdbserver $(android_deploy_data_dir) + adb shell "$(android_deploy_data_dir)/gdbserver +$(android_deploy_data_dir)/debug-socket $(android_deploy_data_dir)/runner $(RUNNER_ARGS)" & sleep 1 - adb forward tcp:$(DEBUG_PORT) localfilesystem:$(deploy_data_dir)/debug-socket - $(ANDROID_NDK_ROOT)/prebuilt/$(build_os_arch)/bin/gdb -x build/gdb.setup + adb forward tcp:$(DEBUG_PORT) localfilesystem:$(android_deploy_data_dir)/debug-socket + $(ANDROID_NDK_ROOT)/prebuilt/$(build_os_arch)/bin/gdb -x build/gdb-android.setup + +build-jvm: build/jvm/runner build/tests-jvm.jar build/frida-java-bridge.js + +run-jvm: + @test -n "$(jvm_lib)" || { echo "Unable to locate libjvm.so under JAVA_HOME=$(JAVA_HOME)" >&2; exit 1; } + FRIDA_JAVA_TESTS_JVM_PATH="$(jvm_lib)" build/jvm/runner $(RUNNER_ARGS) + +watch-jvm: + @test -n "$(jvm_lib)" || { echo "Unable to locate libjvm.so under JAVA_HOME=$(JAVA_HOME)" >&2; exit 1; } + npm run watch & + ./node_modules/.bin/chokidar \ + build/frida-java-bridge.js \ + -c "FRIDA_JAVA_TESTS_JVM_PATH='$(jvm_lib)' build/jvm/runner $(RUNNER_ARGS)" + +debug-jvm: + @test -n "$(jvm_lib)" || { echo "Unable to locate libjvm.so under JAVA_HOME=$(JAVA_HOME)" >&2; exit 1; } + FRIDA_JAVA_TESTS_JVM_PATH="$(jvm_lib)" gdb --args build/jvm/runner $(RUNNER_ARGS) -build/gdb.setup: build/symbols.stamp +build/gdb-android.setup: build/android-symbols.stamp ( \ - echo "set sysroot $(abspath build/symbols/)"; \ + echo "set sysroot $(abspath build/android-symbols/)"; \ echo "directory $(android_sysroot)/usr/include"; \ echo "directory $(abspath .)"; \ echo "file $(abspath build/obj/local/$(ANDROID_ABI)/runner)"; \ echo "target remote :$(DEBUG_PORT)"; \ ) > $@ -build/symbols.stamp: - rm -rf build/symbols - mkdir -p build/symbols/$(ANDROID_BINDIR)/ build/symbols/$(ANDROID_LIBDIR)/ - adb pull -a $(ANDROID_BINDIR)/linker build/symbols/$(ANDROID_BINDIR)/ - adb pull -a $(shell adb shell "ls $(ANDROID_LIBDIR)/*.so") build/symbols/$(ANDROID_LIBDIR)/; \ +build/android-symbols.stamp: + rm -rf build/android-symbols + mkdir -p build/android-symbols/$(ANDROID_BINDIR)/ build/android-symbols/$(ANDROID_LIBDIR)/ + adb pull -a $(ANDROID_BINDIR)/linker build/android-symbols/$(ANDROID_BINDIR)/ + adb pull -a $(shell adb shell "ls $(ANDROID_LIBDIR)/*.so") build/android-symbols/$(ANDROID_LIBDIR)/; \ touch $@ build/$(ANDROID_ABI)/libartpalette.so: build/$(ANDROID_ABI)/runner @@ -84,8 +106,8 @@ build/$(ANDROID_ABI)/runner: runner.c artpalette.c build/obj/local/$(ANDROID_ABI NDK_APPLICATION_MK=$$(pwd)/Application.mk \ NDK_OUT=$$(pwd)/build/obj \ NDK_LIBS_OUT=$$(pwd)/build \ - FRIDA_JAVA_TESTS_DATA_DIR=$(deploy_data_dir) \ - FRIDA_JAVA_TESTS_CACHE_DIR=$(deploy_cache_dir) + FRIDA_JAVA_TESTS_DATA_DIR=$(android_deploy_data_dir) \ + FRIDA_JAVA_TESTS_CACHE_DIR=$(android_deploy_cache_dir) build/obj/local/$(ANDROID_ABI)/libfrida-gumjs.a: @mkdir -p $(@D) @@ -93,31 +115,67 @@ build/obj/local/$(ANDROID_ABI)/libfrida-gumjs.a: tar -xJf $@.tar.xz.tmp -C $(@D) rm -f $@.tar.xz.tmp -build/tests.dex: build/tests.jar +build/jvm/runner: runner.c build/jvm/frida-gumjs/libfrida-gumjs.a + @mkdir -p $(@D) + gcc -g -Wall -Werror -pthread \ + -I$(JAVA_HOME)/include \ + -I$(JAVA_HOME)/include/linux \ + -Ibuild/jvm/frida-gumjs \ + -DFRIDA_JAVA_TESTS_DATA_DIR=\"$(abspath build)\" \ + -DFRIDA_JAVA_TESTS_CACHE_DIR=\"$(abspath build)/jvm/cache\" \ + runner.c \ + build/jvm/frida-gumjs/libfrida-gumjs.a \ + -Wl,--no-as-needed -lstdc++ -Wl,--as-needed \ + -ldl -lm -lrt -lresolv -pthread \ + -o $@ + +build/jvm/frida-gumjs/libfrida-gumjs.a: + @mkdir -p $(@D) + curl -fsSL https://github.com/frida/frida/releases/download/$(frida_version)/frida-gumjs-devkit-$(frida_version)-linux-$(jvm_arch).tar.xz -o $@.tar.xz.tmp + tar -xJf $@.tar.xz.tmp -C $(@D) + rm -f $@.tar.xz.tmp + +build/tests-android.dex: build/tests-android.jar d8 \ - --output build/tests.zip \ + --output build/tests-android.zip \ --classpath $(android_jar) \ --min-api $(android_api_major) \ $< - cd build && unzip -o tests.zip classes.dex + cd build && unzip -o tests-android.zip classes.dex mv build/classes.dex $@ -build/tests.jar: $(test_sources) build/junit.jar build/hamcrest.jar - @rm -rf build/java/ - @mkdir -p build/java/ - cd build/java/ \ +build/tests-android.jar: $(android_test_sources) build/junit.jar build/hamcrest.jar + @rm -rf build/java-android/ + @mkdir -p build/java-android/ + cd build/java-android/ \ && jar xf ../junit.jar \ && jar xf ../hamcrest.jar javac \ - -cp .:build/java/:$(android_jar) \ + -cp .:build/java-android/:$(android_jar) \ -bootclasspath $(android_jar) \ -source 1.8 \ -target 1.8 \ -Xlint:deprecation \ -Xlint:unchecked \ - $(test_sources) \ - -d build/java/ - jar cfe $@ re.frida.tests.Runner -C build/java . + $(android_test_sources) \ + -d build/java-android/ + jar cf $@ -C build/java-android . + +build/tests-jvm.jar: $(jvm_test_sources) build/junit.jar build/hamcrest.jar + @rm -rf build/java-jvm/ + @mkdir -p build/java-jvm/ + cd build/java-jvm/ \ + && jar xf ../junit.jar \ + && jar xf ../hamcrest.jar + javac \ + -cp .:build/java-jvm/ \ + -source 1.8 \ + -target 1.8 \ + -Xlint:deprecation \ + -Xlint:unchecked \ + $(jvm_test_sources) \ + -d build/java-jvm/ + jar cf $@ -C build/java-jvm . build/junit.jar: @mkdir -p $(@D) @@ -135,4 +193,4 @@ build/frida-java-bridge.js: node_modules $(bridge_sources) node_modules: package.json npm install -.PHONY: all clean deploy run watch debug +.PHONY: all clean build-android deploy-android run-android watch-android debug-android build-jvm run-jvm watch-jvm debug-jvm diff --git a/test/re/frida/ClassRegistryTest.java b/test/re/frida/ClassRegistryTest.java index 86ef175..a1c891b 100644 --- a/test/re/frida/ClassRegistryTest.java +++ b/test/re/frida/ClassRegistryTest.java @@ -26,7 +26,7 @@ public void loadedClassesCanBeEnumerated() { @Test public void classLoadersCanBeEnumerated() { - if (android.os.Build.VERSION.SDK_INT < 24) { + if (TestRunner.isAndroid() && TestRunner.getAndroidApiLevel() < 24) { return; } diff --git a/test/re/frida/MethodTest.java b/test/re/frida/MethodTest.java index 52bf65d..410b0b8 100644 --- a/test/re/frida/MethodTest.java +++ b/test/re/frida/MethodTest.java @@ -540,6 +540,10 @@ public void performNowWorks() { // Issue #271 @Test public void toStringOnOverloadedToString() { + if (!TestRunner.isAndroid()) { + return; + } + loadScript("const utf16 = Java.use('android.icu.text.UTF16');" + "send(utf16.toString());"); assertEquals("", script.getNextMessage()); diff --git a/test/re/frida/TestRunner.java b/test/re/frida/TestRunner.java index 777495d..c8450fc 100644 --- a/test/re/frida/TestRunner.java +++ b/test/re/frida/TestRunner.java @@ -27,15 +27,38 @@ public static void main(String[] args, String dataDir, String cacheDir, String[] classes = (args.length > 1) ? Arrays.copyOfRange(args, 1, args.length) - : new String[] { - "re.frida.ClassRegistryTest", - "re.frida.MethodTest", - "re.frida.ClassCreationTest", - "re.frida.PerformTest" - }; + : isAndroid() + ? new String[] { + "re.frida.ClassRegistryTest", + "re.frida.MethodTest", + "re.frida.ClassCreationTest", + "re.frida.PerformTest" + } + : new String[] { + "re.frida.ClassRegistryTest", + "re.frida.MethodTest" + }; JUnitCore.main(classes); } + public static boolean isAndroid() { + try { + Class.forName("android.os.Build"); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } + + public static int getAndroidApiLevel() { + try { + Class version = Class.forName("android.os.Build$VERSION"); + return version.getField("SDK_INT").getInt(null); + } catch (Exception e) { + return 0; + } + } + public static String getCacheDir() { return dataDir; } diff --git a/test/runner.c b/test/runner.c index e7f14ce..5185bce 100644 --- a/test/runner.c +++ b/test/runner.c @@ -2,22 +2,26 @@ #include #include #include -#include #include #include #if defined (__linux__) && defined (__LP64__) # include #endif -#include +#ifdef __ANDROID__ +# include +# include +#endif typedef struct _CreateScriptOperation CreateScriptOperation; typedef struct _DestroyScriptOperation DestroyScriptOperation; +#ifdef __ANDROID__ typedef struct _SigchainAction SigchainAction; +#endif struct _CreateScriptOperation { jweak wrapper; - const gchar * source_code; + gchar * source_code; gboolean done; GumScript * script; @@ -37,12 +41,14 @@ struct _DestroyScriptOperation GCond cond; }; +#ifdef __ANDROID__ struct _SigchainAction { bool (* sc_sigaction) (int, siginfo_t *, void *); sigset_t sc_mask; guint64 sc_flags; }; +#endif static void frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations); static void frida_java_register_test_runner_api (JNIEnv * env); @@ -56,6 +62,7 @@ static jlong re_frida_script_create (JNIEnv * env, jobject self, jstring source_ static gboolean create_script_on_js_thread (gpointer user_data); static void on_create_ready (GObject * source_object, GAsyncResult * result, gpointer user_data); static void on_load_ready (GObject * source_object, GAsyncResult * result, gpointer user_data); +static gboolean finish_create_script_on_js_thread (gpointer user_data); static void re_frida_script_destroy (JNIEnv * env, jobject self, jlong handle); static gboolean destroy_script_on_js_thread (gpointer user_data); static void on_unload_ready (GObject * source_object, GAsyncResult * result, gpointer user_data); @@ -63,16 +70,18 @@ static void re_frida_script_on_message (const gchar * message, GBytes * data, gp static void re_frida_badger_native_method (JNIEnv * env, jobject self, jstring str); -static void destroy_weak_ref (jweak ref); +static void destroy_weak_ref (gpointer data); #if defined (__linux__) && defined (__LP64__) static gpointer frida_java_allocate_memory (const GumAddressSpec * spec, gsize size, gsize alignment, GumPageProtection prot, gpointer user_data); #endif +#ifdef __ANDROID__ static guint get_system_api_level (void); static void on_special_signal (int signo, siginfo_t * info, void * context); +#endif static const JNINativeMethod re_frida_test_runner_methods[] = { @@ -98,11 +107,13 @@ static jobject re_frida_test_runner_class_loader; static jmethodID re_frida_script_on_message_method; -#define MAX_SPECIAL_HANDLERS 4 +#ifdef __ANDROID__ +# define MAX_SPECIAL_HANDLERS 4 static SigchainAction special_handlers[NSIG][MAX_SPECIAL_HANDLERS]; static guint special_handler_count[NSIG]; static struct sigaction previous_action[NSIG]; +#endif int main (int argc, char * argv[]) @@ -198,6 +209,8 @@ main (int argc, char * argv[]) return result; } +#ifdef __ANDROID__ + static void frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations) { @@ -235,7 +248,7 @@ frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations) options[1].optionString = "-verbose:gc"; options[2].optionString = "-Xcheck:jni"; options[3].optionString = "-Xdebug"; - options[4].optionString = "-Djava.class.path=" FRIDA_JAVA_TESTS_DATA_DIR "/tests.dex"; + options[4].optionString = "-Djava.class.path=" FRIDA_JAVA_TESTS_DATA_DIR "/tests-android.dex"; if (enable_optimizations) { @@ -275,6 +288,53 @@ frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations) } } +#else + +static void +frida_java_init_vm (JavaVM ** vm, JNIEnv ** env, gboolean enable_optimizations) +{ + const gchar * jvm_path; + void * vm_module; + jint (* create_java_vm) (JavaVM ** vm, void ** env, void * vm_args); + int n_options; + JavaVMOption * options; + JavaVMInitArgs args; + jint result; + + jvm_path = getenv ("FRIDA_JAVA_TESTS_JVM_PATH"); + if (jvm_path == NULL) + jvm_path = "libjvm.so"; + + vm_module = dlopen (jvm_path, RTLD_LAZY | RTLD_GLOBAL); + if (vm_module == NULL) + { + g_printerr ("Unable to load VM: %s\n", dlerror ()); + exit (1); + } + + create_java_vm = dlsym (vm_module, "JNI_CreateJavaVM"); + g_assert (create_java_vm != NULL); + + n_options = enable_optimizations ? 1 : 2; + options = g_new0 (JavaVMOption, n_options); + + options[0].optionString = "-Djava.class.path=" FRIDA_JAVA_TESTS_DATA_DIR "/tests-jvm.jar"; + if (!enable_optimizations) + options[1].optionString = "-Xint"; + + args.version = JNI_VERSION_1_8; + args.nOptions = n_options; + args.options = options; + args.ignoreUnrecognized = JNI_TRUE; + + result = create_java_vm (vm, (void **) env, &args); + g_assert_cmpint (result, ==, JNI_OK); + + g_free (options); +} + +#endif + static void frida_java_register_test_runner_api (JNIEnv * env) { @@ -334,7 +394,11 @@ frida_java_get_env (void) { g_assert_cmpint (result, ==, JNI_EDETACHED); +#ifdef __ANDROID__ result = (*java_vm)->AttachCurrentThread (java_vm, &env, NULL); +#else + result = (*java_vm)->AttachCurrentThread (java_vm, (void **) &env, NULL); +#endif g_assert_cmpint (result, ==, JNI_OK); } @@ -351,10 +415,15 @@ static jlong re_frida_script_create (JNIEnv * env, jobject self, jstring source_code) { CreateScriptOperation op; + const jchar * chars; + jsize length; GSource * idle_source; op.wrapper = (*env)->NewWeakGlobalRef (env, self); - op.source_code = (*env)->GetStringUTFChars (env, source_code, NULL); + chars = (*env)->GetStringChars (env, source_code, NULL); + length = (*env)->GetStringLength (env, source_code); + op.source_code = g_utf16_to_utf8 (chars, length, NULL, NULL, NULL); + (*env)->ReleaseStringChars (env, source_code, chars); op.done = FALSE; op.script = NULL; @@ -376,7 +445,7 @@ re_frida_script_create (JNIEnv * env, jobject self, jstring source_code) g_cond_clear (&op.cond); g_mutex_clear (&op.lock); - (*env)->ReleaseStringUTFChars (env, source_code, op.source_code); + g_free (op.source_code); if (op.error != NULL) { @@ -431,10 +500,25 @@ static void on_load_ready (GObject * source_object, GAsyncResult * result, gpointer user_data) { CreateScriptOperation * op = user_data; + GSource * idle_source; gum_script_load_finish (op->script, result); + idle_source = g_idle_source_new (); + g_source_set_priority (idle_source, G_PRIORITY_LOW); + g_source_set_callback (idle_source, finish_create_script_on_js_thread, op, NULL); + g_source_attach (idle_source, js_context); + g_source_unref (idle_source); +} + +static gboolean +finish_create_script_on_js_thread (gpointer user_data) +{ + CreateScriptOperation * op = user_data; + create_script_operation_notify_complete (op); + + return FALSE; } static void @@ -583,8 +667,9 @@ re_frida_badger_native_method (JNIEnv * env, jobject self, jstring str) } static void -destroy_weak_ref (jweak ref) +destroy_weak_ref (gpointer data) { + jweak ref = data; JNIEnv * env; env = frida_java_get_env (); @@ -660,6 +745,8 @@ frida_java_allocate_memory (const GumAddressSpec * spec, #endif +#ifdef __ANDROID__ + static guint get_system_api_level (void) { @@ -789,3 +876,5 @@ on_special_signal (int signo, siginfo_t * info, void * context) sigaction (signo, &prev, NULL); } + +#endif From 09e271e5e483d38f482f4ca59c90b47b6fb17d56 Mon Sep 17 00:00:00 2001 From: Muhtasham Nawr al-Mahmud Date: Fri, 20 Nov 2026 22:43:49 +0600 Subject: [PATCH 6/6] ci: Modernize workflows and add job timeouts Upgrade GitHub Actions to their Node 24 releases (actions/checkout@v7, actions/setup-node@v7, actions/setup-java@v6, and actions/cache@v6) across both workflows, and modernize the linting workflow to Node 22 with JavaScript syntax (`node --check`) and TypeScript declaration (`tsc --noEmit`) verification. Set explicit timeout-minutes on all CI jobs (30m for android, 15m for jvm, 10m for lint) so hung runs fail promptly instead of blocking for GitHub Actions' 6-hour default, and clean up orphaned emulator crashpad_handler processes on script exit so emulator termination does not hang after tests finish. --- .github/workflows/linting.yml | 12 ++++++++---- .github/workflows/tests.yml | 21 +++++++++++++-------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml index adc979e..26b5b15 100644 --- a/.github/workflows/linting.yml +++ b/.github/workflows/linting.yml @@ -1,12 +1,16 @@ name: linting on: [push, pull_request] jobs: - eslint: + lint: runs-on: ubuntu-latest + timeout-minutes: 10 steps: - - uses: actions/checkout@v3 - - uses: actions/setup-node@v3 + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 with: - node-version: 18 + node-version: 22 + cache: npm - run: npm install - run: npm run lint + - run: node --check index.js lib/*.js + - run: npx --no-install tsc --noEmit --lib es2022 index.d.ts diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 68fa860..63e9955 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -3,6 +3,7 @@ on: [push, pull_request] jobs: android: runs-on: ubuntu-latest + timeout-minutes: 30 strategy: fail-fast: false matrix: @@ -12,9 +13,9 @@ jobs: ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: 200 steps: - name: Check out repo - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Cache test dependencies - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: | ~/.npm @@ -31,7 +32,7 @@ jobs: sudo udevadm control --reload-rules sudo udevadm trigger --name-match=kvm - name: AVD cache - uses: actions/cache@v4 + uses: actions/cache@v6 id: avd-cache with: path: | @@ -47,7 +48,9 @@ jobs: force-avd-creation: false emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none disable-animations: false - script: echo "Generated AVD snapshot for caching." + script: >- + trap 'pkill -INT -f "[c]rashpad_handler" || true' EXIT; + echo "Generated AVD snapshot for caching." - name: Run tests in emulator uses: reactivecircus/android-emulator-runner@v2 with: @@ -57,6 +60,7 @@ jobs: emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none disable-animations: true script: >- + trap 'pkill -INT -f "[c]rashpad_handler" || true' EXIT; sdkmanager "platforms;android-${{ matrix.api }}" && BUILD_TOOLS_DIR="$(ls -d "$ANDROID_SDK_ROOT/build-tools/"* | sort -V | tail -n 1)" && PATH="$BUILD_TOOLS_DIR:$PATH" @@ -68,25 +72,26 @@ jobs: jvm: runs-on: ubuntu-latest + timeout-minutes: 15 strategy: fail-fast: false matrix: java: ['8', '11', '17'] steps: - name: Check out repo - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v4 + uses: actions/setup-java@v6 with: distribution: temurin java-version: ${{ matrix.java }} - name: Set up Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@v7 with: node-version: 22 cache: npm - name: Cache test dependencies - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: | test/build/junit.jar