util:tsort.h: add a macro for safely comparing numbers
authorDouglas Bagnall <douglas.bagnall@catalyst.net.nz>
Tue, 2 Apr 2024 23:43:27 +0000 (12:43 +1300)
committerAndrew Bartlett <abartlet@samba.org>
Wed, 10 Apr 2024 22:56:33 +0000 (22:56 +0000)
commit5ab93f48c575db1a3c5a707258cc44f707a5eeb0
treebdcbbc1b3d503ea250b5adb8fa3762875442b705
parent8b6a584170eeb5082a188879be88e5f414b0be81
util:tsort.h: add a macro for safely comparing numbers

In many places we use `return a - b;` in a comparison function. This can
be problematic if the comparison is used in a sort, as `a - b` is not
guaranteed to do what we expect. For example:

* if a and b are 2s-complement ints, a is INT_MIN and b is INT_MAX, then
  a - b = 1, which is wrong.

* if a and b are 64 bit pointers, a - b could wrap around many times in
  a cmp function returning 32 bit ints. (We do this often).

The issue is not just that a sort could go haywire.
Due to a bug in glibc, this could result in out-of-bounds access:

https://www.openwall.com/lists/oss-security/2024/01/30/7

(We have replicated this bug in ldb_qsort).

BUG: https://bugzilla.samba.org/show_bug.cgi?id=15625

Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>
lib/util/tsort.h