]> git.ipfire.org Git - thirdparty/git.git/commit - git-compat-util.h
add helpers for detecting size_t overflow
authorJeff King <peff@peff.net>
Fri, 19 Feb 2016 11:21:19 +0000 (06:21 -0500)
committerJunio C Hamano <gitster@pobox.com>
Fri, 19 Feb 2016 17:40:37 +0000 (09:40 -0800)
commit320d0b493a259db3b481f985545b244438e6c086
tree6b3a53c1c23c520bc1c54595765224827044f2ea
parentc3a700fba1693f68643f24c4f2e6d4cdd240babf
add helpers for detecting size_t overflow

Performing computations on size_t variables that we feed to
xmalloc and friends can be dangerous, as an integer overflow
can cause us to allocate a much smaller chunk than we
realized.

We already have unsigned_add_overflows(), but let's add
unsigned_mult_overflows() to that. Furthermore, rather than
have each site manually check and die on overflow, we can
provide some helpers that will:

  - promote the arguments to size_t, so that we know we are
    doing our computation in the same size of integer that
    will ultimately be fed to xmalloc

  - check and die on overflow

  - return the result so that computations can be done in
    the parameter list of xmalloc.

These functions are a lot uglier to use than normal
arithmetic operators (you have to do "st_add(foo, bar)"
instead of "foo + bar"). To at least limit the damage, we
also provide multi-valued versions. So rather than:

  st_add(st_add(a, b), st_add(c, d));

you can write:

  st_add4(a, b, c, d);

This isn't nearly as elegant as a varargs function, but it's
a lot harder to get it wrong. You don't have to remember to
add a sentinel value at the end, and the compiler will
complain if you get the number of arguments wrong. This
patch adds only the numbered variants required to convert
the current code base; we can easily add more later if
needed.

Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
git-compat-util.h