Search code examples
cprintfstring-formattingformat-string

Printing variable number of bytes using format strings with printf


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:

  1. %khhx, which unfortunately just results in k-1 blank spaces followed by two hex-characters (one byte of data).
  2. %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?


Solution

  • Is it possible to get the desired behavior? If so, how?

    There does not exist printf format specifier to do what you want.

    Is it possible

    Write your own printf implementation that supports what you want. Use implementation-specific tools to create your own printf format specifier. You can take inspiration from linux kernel printk %*phN format speciifer.