util/cbfstool: Prevent overflow of 16 bit multiplications
commit2d58bf6a037c8ad474db4a902e799bee637e7ec0
authorJacob Garber <jgarber1@ualberta.ca>
Tue, 2 Jul 2019 20:38:38 +0000 (2 14:38 -0600)
committerMartin Roth <martinroth@google.com>
Sun, 7 Jul 2019 20:59:04 +0000 (7 20:59 +0000)
tree049fba76fd9d23f5281dc95e70e5e87acde7a901
parent96e0ce30dbcdf709c92ef40ca9cfee0895b712ac
util/cbfstool: Prevent overflow of 16 bit multiplications

Considering the following integer multiplication:

    u64 = u16 * u16

What on earth, one might wonder, is the problem with this? Well, due to
C's unfortunately abstruse integer semantics, both u16's are implicitly
converted to int before the multiplication, which cannot hold
all possible values of a u16 * u16. Even worse, after overflow the
intermediate result will be a negative number, which during the
conversion to a u64 will be sign-extended to a huge integer. Not good.

The solution is to manually cast one of the u16 to a u32 or u64, which
are large enough to not have any overflow and will prevent the implicit
conversion. The type of the u64 is preferred, though a u32 is used
instead of size_t, since that can change depending on the platform.

Change-Id: I5391221d46d620d0e5bd629e2f9680be7a53342e
Signed-off-by: Jacob Garber <jgarber1@ualberta.ca>
Found-by: Coverity CID 12297{03,04,05,06,07,08,09,10}
Reviewed-on: https://review.coreboot.org/c/coreboot/+/33986
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Reviewed-by: Julius Werner <jwerner@chromium.org>
Reviewed-by: Paul Menzel <paulepanter@users.sourceforge.net>
util/cbfstool/elfheaders.c