Correct macro to avoid undefined C language behavior.

I stumbled across a kernel commit that fixes the macro that convert
between file descriptors and clock ID types (see below).  This patch
corrects the FD-to-clockid macro by casting to unsigned before
shifting.

commit 29f1b2b0fecfae69e31833836f1da3136696eee5
Author: Nick Desaulniers <nick.desaulniers@gmail.com>
Date:   Thu Dec 28 22:11:36 2017 -0500

    posix-timers: Prevent UB from shifting negative signed value

    Shifting a negative signed number is undefined behavior. Looking at the
    macros MAKE_PROCESS_CPUCLOCK and FD_TO_CLOCKID, it seems that the
    subexpression:

    (~(clockid_t) (pid) << 3)

    where clockid_t resolves to a signed int, which once negated, is
    undefined behavior to shift the value of if the results thus far are
    negative.

Signed-off-by: Richard Cochran <richardcochran@gmail.com>
master
Richard Cochran 2018-03-27 18:26:54 -07:00
parent 862724fda5
commit a412982300
1 changed files with 1 additions and 1 deletions

View File

@ -45,7 +45,7 @@
#endif
#define CLOCKFD 3
#define FD_TO_CLOCKID(fd) ((~(clockid_t) (fd) << 3) | CLOCKFD)
#define FD_TO_CLOCKID(fd) ((clockid_t) ((((unsigned int) ~fd) << 3) | CLOCKFD))
#define CLOCKID_TO_FD(clk) ((unsigned int) ~((clk) >> 3))
#ifndef HAVE_ONESTEP_SYNC