Hooking constructors

📌What is a constructor?

A constructor function is a special method in a class that is called when a new object of that class is instantiated. Its primary purpose is to initialize the object's properties and set up any necessary initial state. In most programming languages, the constructor function shares the same name as the class and does not have a return type.

📍Hooking Example

In this example, we have the Item class

package com.apphacking.fridainstance;

public class Item {
    int itemPower;
    public String name = "skillZap"
    
    //constructor
    public Item(int itemPower) {
        this.itemPower = 1;
        this.itemPower = itemPower;
    }
}

📍Hooking methodology

Hooking a constructor is the same as hooking a normal function, but instead of typing the function name, we use the $init keyword, which refers to the constructor of the current class

Java.perform(function() {

    var itemClassReference = Java.use('com.apphacking.fridainstance.Item');
    itemClassReference.$init.implementation = function(param) {

        send("Item power of the created instance is = " + param);
        this.$init(900000);
    }
});

📍Hooking - overload

  • If a class has more than one constructor, we have to use $init.overload() to handle specific constructors.

  • Sometimes in Java code, we see only one constructor, but there might still be a default constructor that is not explicitly defined—it is automatically provided by the compiler.

  • To check if there is a default constructor, look at the Smali code. Constructors are defined as .method <init>.

  • In the case of multiple constructors, we use the overload method to differentiate them based on the parameter types.

    Java.perform(function() {
    
        var itemClassReference = Java.use('com.apphacking.fridainstance.Item');
        itemClassReference.$init.overload('int').implementation = function(param) {
    
            send("Item power of the created instance is = " + param);
            this.$init(900000);
        }
    });

Last updated