printf("%2$*11$s", ...) what is this formation means

Viewed 161

it use like in c11/c++?:

printf("%2$*11$s",...)

It is come from a elf file, this file using printf() to operate like mem[4]=mem[2]+mem[1]. You can refer from this https://ctftime.org/task/5042 (it is a reverse CTF question).

To my point, I know the $ is use to specify the position of which var but no reference notice that one block can have two $.

also, I cannot find any func about $ in format except location.

so, I will be grateful if anyone can tell me it is meaning.

image

2 Answers

n$ is an extension defined in POSIX to select which argument to print. This is called Parameter field.

printf format string - Wikipedia

Actually this question is about using two n$ in one format specifier. Let me examine with small examples...

#include <stdio.h>

int main(void) {
    printf("%1$*3$s\n", "a", "b", 10, 20);
    printf("%1$*4$s\n", "a", "b", 10, 20);
    printf("%2$*3$s\n", "a", "b", 10, 20);
    printf("%2$*4$s\n", "a", "b", 10, 20);
    return 0;
}

Output:

         a
                   a
         b
                   b

It looks like %n$*m$s means "print the n-th argument using the width specified by the m-th argument". The final s has the meaning of s in %s.

See the POSIX specification for printf() and family.

It is used to allow internationalization (I18N) and localization (L10N) of messages, so that the arguments to the printf() call can be printed in arbitrary orders. When you use an n$ notation for any element of the format string, you are supposed to use it for all elements. You are also supposed to identify all arguments from 1 to the maximum number referenced — and the types must match what the format expects too.

An example:

printf("%2$ is %1$allowed to fly to %3$\n", "not ", "Superman", "School");
printf("%3$ is %1$allowed to fly to %2$\n", "", "Superman", "School");

Those produce:

Superman is not allowed to fly to School
School is allowed to fly to Superman

Often, the format string will come from a variable so that the order may be varied according to the local requirements. The formatted data will also usually be in variables too. Using hard-coded strings as in these examples is abnormal.

Related