Lots of situations will require working directly with ArrayBuffers but operating with them might not be straightforward because data might not always be simple strings. To get a better understanding of how to operate with them in Frida we will use the `fprintf` function and replace the contents of the second argument (our aim is to replace "target" to "foobar").
This C program calls the `fprintf` function that is defined as:
int fprintf(FILE *stream, const char *format, ...);
Usually, functions will provide us with the length of the string but this is not the case so to get around this limitation `.readCString()` will provide us the length of the `*format` parameter.
To understand how this instrumentation code works we will examine it step by step.
str2ab is an auxiliary function that converts a string back to an Uint8Array.
readCString() returns the contents of the format* string and gives us the length of the content (+ 1 for the null terminator). Having the size allows us to call readByteArray with the correct size.
When the ArrayBuffer is obtained by calling readByteArray we use String.fromCharCode.apply(null, new Uint8Array) to convert it to a human-readable string (you can skip this step and modify the ArrayBuffer directly).
args = str2ab(str).unwrap();
Once the string is modified the str2ab function transforms the string back to an Uint8Array but we cannot just reassign this Uint8Array to args because it is expecting a pointer. To do so, Frida has an auxiliary method called .unwrap() that returns a pointer to the first element of the `ArrayBuffer`.
Then, it is possible to verify the output:
The str2ab (String to ArrayBuffer) function is a slightly modified version of the one found in developers.google.com adapted to Uint8Arrays.