Frida Advanced Techniques
Mobile Reverse Engineering Tools & Techniques · Mobile Application Security track
11 min read
In this module
Frida's Architecture
Mobile Exploitation Techniques introduced Frida as a dynamic instrumentation toolkit. This lesson digs into its guts: the architecture and the advanced APIs. Knowing how Frida actually works under the surface is what separates scripts that fold the moment they touch a hardened app from scripts that hold up against real targets.
Frida is a pile of cooperating components:
The Gum Engine
Gum is Frida's low-level instrumentation library, written in C. It does the unglamorous mechanical work — allocating executable memory, rewriting instructions, juggling trampolines, and coordinating thread-safe hook installation. The Interceptor and Stalker APIs that JavaScript talks to are bindings around Gum.
JavaScript Runtimes
Frida supports two JavaScript engines:
- V8: Google's JavaScript engine, the same one inside Chrome and Node. Faster, hungrier on memory. Default on most platforms.
- QuickJS: tiny, embeddable, a touch slower. Used when memory is tight or V8 isn't available.
Scripts run inside the target's own address space with full read/write access to its memory. That's a long way from external debugging. Frida's hooks execute inside the process, so they're far faster than a debugger stopping the target from outside, and they don't use the debugging interfaces that anti-debug checks probe. That doesn't make Frida invisible: the frida-server port, its named threads and the agent library showing up in /proc/self/maps are all well-known giveaways, as the next lesson shows.
The snippets here use the Frida 17 API (released May 2025). Two changes trip up older scripts. The static Module.findExportByName() and Module.getExportByName() are gone: look the module up first with Process.getModuleByName(), or use Module.getGlobalExportByName() when you don't care which module exports the symbol. And the Java, ObjC and Swift bridges are no longer built into the runtime. The frida REPL and frida-trace still bundle them, so the bridge snippets below work there unchanged, but a standalone agent has to import them (for example import Java from "frida-java-bridge") and be built with frida-compile.
Frida injects a JavaScript runtime (V8 or QuickJS) into the target, backed by the Gum engine for the low-level work. Gum handles trampoline allocation, instruction rewriting, and thread safety. Scripts run inside the target's address space with full memory access, which is why Frida runs circles around external debuggers for instrumentation work.
Interceptor API Deep Dive
The Interceptor is the API you'll reach for first, and most often. It rewrites function prologues with trampolines that bounce execution into your JavaScript callbacks.
// Attach to a native function by address or symbolInterceptor.attach(Process.getModuleByName("libssl.so") .getExportByName("SSL_read"), { onEnter: function(args) { // 'args' is an array of NativePointer values this.buf = args[1]; this.num = args[2].toInt32(); }, onLeave: function(retval) { if (retval.toInt32() > 0) { console.log(hexdump(this.buf, { length: retval.toInt32() })); } }});Here's what one hooked call to SSL_read goes through once attach() has done its work. Gum has overwritten the first few instructions of the function with a branch, and copied those instructions, fixed up for their new address, into a trampoline of its own.
That patched prologue is also what anti-Frida checks look for: compare the first bytes of a sensitive function against the copy on disk and a hook stands out.
Key Interceptor Details
thiscontext: shared betweenonEnterandonLeavefor the same call. Use it to ferry buffer pointers, parsed metadata, anything you'll want on the way out.- Thread safety: each concurrent call gets its own
this. Frida sorts the threading for you. - Modifying
args: assign toargs[n]and the modified value reaches the original function. retval.replace(): call this inonLeaveto swap the return value before the caller sees it.
Replacing Implementations
When you want to ditch a function's behaviour entirely, reach for Interceptor.replace():
Interceptor.replace( Process.getModuleByName("libapp.so").getExportByName("verify_license"), new NativeCallback(function(ctx) { console.log("[+] License check bypassed"); return 1; // Always return "valid" }, "int", ["pointer"]));All calls to the target function now land on your NativeCallback. The original implementation never runs, which makes replace() cheaper than attach() when the original behaviour is just dead weight.
Frida's Interceptor hooks native functions by rewriting their prologues with trampolines. The attach() method provides onEnter and onLeave callbacks with access to arguments and return values. The replace() method substitutes the entire implementation with a NativeCallback. Both are thread-safe and operate at native speed within the target process.
ObjC Bridge
The ObjC bridge is Frida's JavaScript front door to the Objective-C runtime. It resolves classes, hooks methods, sends messages, and walks instances.
// Hook an Objective-C methodvar BBAuth = ObjC.classes.BBAuthenticationManager;
Interceptor.attach( BBAuth["- validateCertificateChain:"].implementation, { onEnter: function(args) { // args[0] = self, args[1] = _cmd, args[2] = first argument var chain = new ObjC.Object(args[2]); console.log("[+] Chain length: " + chain.count()); }, onLeave: function(retval) { retval.replace(ptr(1)); // Force return YES console.log("[+] Certificate validation bypassed"); }});For peering at live state, heap scanning with ObjC.choose() is hard to beat:
// Find all live instances of a class on the heapObjC.choose(ObjC.classes.BBAuthenticationManager, { onMatch: function(instance) { console.log("[+] Token: " + instance.accessToken()); console.log(" Authenticated: " + instance.isAuthenticated()); }, onComplete: function() { console.log("[*] Instance search complete"); }});It scans the heap for live instances and lets you poke at runtime state — read properties, call methods, sketch the app's current condition — without ever tracing how the instance got there in the first place.
Java Bridge
The Java bridge does the same job over on Android's Dalvik/ART runtime.
Java.perform(function() { var CryptoHelper = Java.use("com.example.app.CryptoHelper");
// Hook a method with specific overload CryptoHelper.decrypt.overload("[B", "java.lang.String") .implementation = function(data, key) { console.log("[+] decrypt() called, Key: " + key); var result = this.decrypt(data, key); console.log(" Result: " + result); return result; };});Enumerating Loaded Classes
Walking the loaded class list at runtime surfaces code that static analysis simply cannot see — DEX files loaded after install, classes decrypted on the fly:
Java.perform(function() { Java.enumerateLoadedClasses({ onMatch: function(className) { if (className.includes("Crypto")) { console.log("[+] " + className); } }, onComplete: function() {} });});Java.choose() is the Android counterpart to ObjC.choose(). It finds live instances of any Java class and hands them back so you can call methods and read properties directly.
Frida's ObjC and Java bridges expose the respective language runtimes to JavaScript. Both let you hook methods, enumerate classes, find live instances on the heap, and call methods on whatever you find. The ObjC bridge piggybacks on objc_msgSend. The Java bridge talks to ART/Dalvik through JNI. Together they turn Frida from a native-code tool into a full-spectrum mobile instrumentation platform.
Stalker: Instruction-Level Tracing
Stalker is Frida's tracing engine. Interceptor hooks at the function level. Stalker drops to the instruction level, recording every machine instruction a thread executes.
Under the hood, it does dynamic recompilation. When you ask it to follow a thread, Stalker copies each basic block of code into a new buffer, threads in your instrumentation callbacks, and redirects execution to the recompiled version. The target never notices the swap.
Stalker.follow(Process.getCurrentThreadId(), { events: { call: true, // Trace function calls ret: true, // Trace function returns exec: false, // Do not trace every instruction block: false, // Do not trace basic blocks compile: false // Do not trace compilation events }, onReceive: function(events) { var parsed = Stalker.parse(events, { stringify: false, annotate: true }); for (var i = 0; i < parsed.length; i++) { console.log(JSON.stringify(parsed[i])); } }});Use Cases for Stalker
- Code coverage: see which code paths actually run during a given operation; dead branches reveal themselves.
- Control flow analysis: capture the exact call sequence during a security-critical action — login, encryption, licence check.
- Anti-debug detection: watch the instructions around the app's debugger-detection probes and you learn what they're checking for.
Stalker is heavy. Tracing every instruction in a real app produces a torrent of data. Use it surgically: turn it on only during the operation you care about, and filter output to the address ranges that matter.
r2frida: Live Analysis with Radare2
r2frida smashes Radare2's static analysis together with Frida's runtime instrumentation. The result is a live, interactive analysis environment:
# Connect r2frida to a running app$ r2 frida://usb//com.example.app
# List loaded modules[0x00000000]> :il
# Search memory for a string[0x00000000]> :/ api_key_
# Disassemble a function at runtime[0x00000000]> :is # list all exports[0x00000000]> s 0x7f12340000[0x7f12340000]> pd 20 # disassemble 20 instructions
# Set a hook from within r2[0x00000000]> :di0 0x7f12345678 # hook and trace callsr2frida earns its keep when you want disassembly, string searches, and cross-references next to live memory inspection and hooking, all from the same prompt. It plugs the gap between offline binary analysis and runtime instrumentation, and it's particularly nasty against apps that decrypt or unpack code at runtime — Radare2 will happily disassemble whatever's in memory right now.
r2frida merges Radare2's disassembly and analysis commands with Frida's process injection and hooking capabilities. This combination enables live memory search, runtime disassembly of decrypted code, and interactive hooking from a single command-line interface. It is especially powerful for analysing applications that decrypt or unpack code at runtime, since Radare2 can disassemble the live, decrypted memory.