Goal: Print variable number of bytes using a single format specifier.
Environment: x86-64 Ubuntu 20.04.3 LTS running in VM on an x86-64 host machine.
Example:
Let %kmagic
be the format specifier I am looking for which prints k
bytes by popping them from the stack and additing them to the output. Then, for %rsp
pointing to a region in memory holding bytes 0xde 0xad 0xbe 0xef
, I want printf("Next 4 bytes on the stack: %4magic")
to print Next 4 bytes on the stack: deadbeef
.
What I tried so far:
%khhx
, which unfortunately just results ink-1
blank spaces followed by two hex-characters (one byte of data).%kx
, which I expected to print k/2 bytes interpreted as one number. This only prints 8 hex-characters (4 bytes) prepended by k - 8 blank spaces.
The number of non-blank characters printed matches the length of the format specifiers, i.e. the expected length of %hhx
is 2, which is also the number of non-blank characters printed. The same holds for %x
, which one expects to print 8 characters.
Question: Is it possible to get the desired behavior? If so, how?