4

I'm learning frida and trying to hook a function that looks like:

`.method public final fn()[B`

It returns a byte array. Here's my code:

Java.perform(function () {
    var test = Java.use("com...");
    test.fn.overload().implementation = function () {
        var ret = this.fn();
        console.log("how to write here?");
        return ret;
    };
});

How to print the ret variable returned by the function? It's a byte[]. I tried console.log but it only prints a [object], and hexdump complains 'expected a pointer'. How can I print the array?

1

5 Answers 5

10

 

var ret = this.fn();
var buffer = Java.array('byte', ret);
console.log(buffer.length);
var result = "";
for(var i = 0; i < buffer.length; ++i){
    result+= (String.fromCharCode(buffer[i]));
}
console.log(result);
1
  • 2
    But this only works for arrays with byte values that represent printable characters. Wouldn't it be better to just print the array in hex representation using something like result+= (buffer[i] & 0xff).toString(16);?
    – Robert
    May 8, 2020 at 9:33
4

Frida's java byte array element representation is signed number currently. Therefore, your byte array may contain negative number. We should edit accepted answer to reflect this:

var buffer = Java.array('byte', ret);
var result = "";
for(var i = 0; i < buffer.length; ++i){
    result += (String.fromCharCode(buffer[i] & 0xff)); // here!!
}
console.log(result);

Related https://stackoverflow.com/a/9609447/9304999 and https://github.com/frida/frida/issues/289

2

One liner console.log(Java.use("java.util.Arrays").toString(ret));

1

Dump byte-array as hex (Android only)

If you are using Frida on Android there is an alternative, using the Android built-in Apache commons codec Hex encoder. As far as I know all Android versions should include the class org.apache.commons.codec.binary.Hex. Unfortunately the version available in Android does not directly output a String, hence you also have to use java.lang.String class:

function encodeHex(byteArray) {
    const HexClass = Java.use('org.apache.commons.codec.binary.Hex');
    const StringClass = Java.use('java.lang.String');
    const hexChars = HexClass.encodeHex(byteArray);
    return StringClass.$new(hexChars).toString();
}
0

Easy:

var stringClass = Java.use("java.lang.String");
var stringInstance = stringClass.$new(ret);
console.log('look = ' + stringInstance.toString())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.