]> git.ipfire.org Git - thirdparty/man-pages.git/commit
printf.3: Prevent signed integer overflow in example
authorTobias Stoeckmann <tobias@stoeckmann.org>
Thu, 21 May 2020 12:15:06 +0000 (14:15 +0200)
committerMichael Kerrisk <mtk.manpages@gmail.com>
Mon, 25 May 2020 13:59:42 +0000 (15:59 +0200)
commit7577e4074b375acb55fb95d799adb800807933e3
tree161f63d185349d53cda41fcb6e099c2cd2351af1
parent9a766452249b3a9e2e1252bd563e3a04186df68c
printf.3: Prevent signed integer overflow in example

The function make_message illustrates how to use vsnprintf to
determine the required amount of memory for a specific format and
its arguments.

If make_message is called with a format which will use exactly
INT_MAX characters (excluding '\0'), then the size++ calculation
will overflow the signed integer "size", which is an undefined
behaviour in C.

Since malloc and vsnprintf rightfully take a size_t argument, I
decided to use a size_t variable for size calculation. Therefore,
this patched code uses variables of the same data types as
expected by function arguments.

Proof of concept (tested on Linux/glibc amd64):

int main() { make_message("%647s%2147483000s", "", ""); }

If the code is compiled with address sanitizer (gcc
-fsanitize=address) you can see the following line, assuming that
a signed integer overflow simply leads to INT_MIN:

==3094==WARNING: AddressSanitizer failed to allocate 0xffffffff80000000 bytes

Signed-off-by: Michael Kerrisk <mtk.manpages@gmail.com>
man3/printf.3