Subject: mktime test in configure: UB resulting in infinite loop

From: Rich Felker <[email-masked]>
Date: Thu, 27 Jan 2011 00:21:59 -0500

The configure test for mktime (m4/mktime.m4) contains the following
code:

  for (;;)
    {
      t = (time_t_max << 1) + 1;
      if (t <= time_t_max)
        break;
      time_t_max = t;
    }

This code has undefined behavior on signed integer overflow; at least
some versions of gcc, and any sane compiler, will optimize out the
exit condition since algebraically 2x+1>x for any nonnegative x. The
result is an infinite loop and failure of the test after the 60-second
timeout.

Finding the max possible value for a signed integer type is actually a
very hard problem in C. As far as I know it's impossible at
compile-time and might even be impossible at runtime unless you make
some assumptions (either the absence of padding bits, or the
well-definedness of converting larger/unsigned types to signed types).
The approach I would take is just:

  time_t_max = (time_t)1 << 8*sizeof(time_t)-2;

If this test comes from higher-up (gnulib?) please forward my bug
report to the relevant upstream.