[tz] [PROPOSED 1/7] Avoid undefined behavior if no Link lines
Paul Eggert
eggert at cs.ucla.edu
Wed Oct 26 10:03:47 UTC 2022
On 10/26/22 01:58, Ian Abbott via tz wrote:
>
> Also in 7.22.5 Searching and sorting utilities, paragraph 1:
>
> [...] Pointer arguments on such a call shall still have valid values, as
> described in 7.1.4.
Yes, that's why portable C code can't call qsort(NULL, 0, ...).
It's not just an academic point. Without the patch, 'zic /dev/null'
dumps core on Fedora 36 x86-64, when tzcode is built via "make
CFLAGS='$(GCC_DEBUG_FLAGS)'". That's how I discovered the need for the
patch.
The core dump occurred because GCC translates this:
qsort(links, nlinks, sizeof *links, qsort_linkcmp);
as if it were this:
if (nlinks == 0)
__builtin_trap();
qsort(links, nlinks, sizeof *links, qsort_linkcmp);
That is, if qsort's second argument is zero, the code generated by GCC
doesn't call the qsort library function. Instead, it directly executes
the ud2 instruction <https://www.felixcloutier.com/x86/ud>, which raises
the invalid opcode exception. Presumably this is because the GCC
maintainers are in the faction that says a null pointer cannot be used
to pass a size-zero object to a library function. This is likely the
same faction that says "char *p = NULL; return p + 0;" has undefined
behavior.
More information about the tz
mailing list