pythonfrida

How to use rpc exports in Frida?


I tried to use rpc.exports.dispose but it's not working. Here is code I tried:

import frida
import sys

device = frida.get_local_device()
session = device.attach('simple')
script = session.create_script("""
    rpc.exports.dispose = function() {
        console.log('dispose');
    };
""")
script.load()
sys.stdin.read()

According to the documentation dispose should be executed before the hooked process terminates or the script is unloaded.

I terminated "simple" process by several ways (click Ctrl+C, run "kill -9 ", run "kill "). But i couldn't see dispose log. I am using Ubuntu. Can you please let me know what is wrong in my code? Thank you!


Solution

  • In my opinion relying on code that is executed in a process while it is terminating is a bad idea. Too many things can go wrong and the code is not executed.

    A far better way is to register the detached handler on Python side:

    def on_detached():
        print("on_detached")
    
    def on_detached_with_reason(reason):
        print("on_detached_with_reason:", reason)
    
    def on_detached_with_varargs(*args):
        print("on_detached_with_varargs:", args)
    
    session = frida.attach("simple")
    print("attached")
    session.on('detached', on_detached)
    session.on('detached', on_detached_with_reason)
    session.on('detached', on_detached_with_varargs)