From a4129823006e750b98060919e09bce1f69d88f4e Mon Sep 17 00:00:00 2001 From: Richard Cochran Date: Tue, 27 Mar 2018 18:26:54 -0700 Subject: [PATCH] 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 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 --- missing.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/missing.h b/missing.h index 16ae97a..6d5d550 100644 --- a/missing.h +++ b/missing.h @@ -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