Read value from frida hooked native method basic_string parameter

Recently I started using Frida and playing with some native methods. But i have a problem with reading value of basic_string

Here is method which I’m hooking:

Here is JavaScript code which I’m using to hook method:

Interceptor.attach(Module.getExportByName('libsigning.so', '_ZN8Security4signEP7_JNIEnvP6rsa_stRKNSt6__ndk112basic_stringIcNS4_11char_traitsIcEENS4_9allocatorIcEEEE'), {
    onEnter: function (args) {
        console.log("RSA.sign()")
        console.log(Memory.readCString(args[2]))
    },
    onLeave: function (retval) {
        // simply replace the value to be returned with 0
        return retval
    }
});

In output I’m getting ! character instead of real value

What is a proper way of doing this?

Answer

Problem was resolved using this frida code:

function readStdString (str) {
  const isTiny = (str.readU8() & 1) === 0;
  if (isTiny) {
    return str.add(1).readUtf8String();
  }

  return str.add(2 * Process.pointerSize).readPointer().readUtf8String();
}

source: https://codeshare.frida.re/@oleavr/read-std-string/

final working code:

Interceptor.attach(Module.getExportByName('libsigning.so', '_ZN8Security4signEP7_JNIEnvP6rsa_stRKNSt6__ndk112basic_stringIcNS4_11char_traitsIcEENS4_9allocatorIcEEEE'), {
    onEnter: function (args) {
        console.log("RSA.sign()")
        console.log(readStdString(args[2]))
    },
    onLeave: function (retval) {
        // simply replace the value to be returned with 0
        return retval
    }
});