mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* precedence bug in MAKE_PROCESS_CPUCLOCK macro?
@ 2017-12-24  3:26 Nick Desaulniers
  2017-12-28 15:49 ` Thomas Gleixner
  0 siblings, 1 reply; 6+ messages in thread
From: Nick Desaulniers @ 2017-12-24  3:26 UTC (permalink / raw)
  To: Thomas Gleixner; +Cc: Al Viro, Deepa Dinamani, Linux Kernel Mailing List

I'm seeing the following warning compiling with Clang:

kernel/time/posix-cpu-timers.c:1397:29: warning: shifting a negative
signed value is undefined
      [-Wshift-negative-value]
        return posix_cpu_clock_get(THREAD_CLOCK, tp);
                                   ^~~~~~~~~~~~
kernel/time/posix-cpu-timers.c:1367:22: note: expanded from macro 'THREAD_CLOCK'
#define THREAD_CLOCK    MAKE_THREAD_CPUCLOCK(0, CPUCLOCK_SCHED)
                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
./include/linux/posix-timers.h:48:2: note: expanded from macro
'MAKE_THREAD_CPUCLOCK'
        MAKE_PROCESS_CPUCLOCK((tid), (clock) | CPUCLOCK_PERTHREAD_MASK)
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
./include/linux/posix-timers.h:46:23: note: expanded from macro
'MAKE_PROCESS_CPUCLOCK'
        ((~(clockid_t) (pid) << 3) | (clockid_t) (clock))
          ~~~~~~~~~~~~~~~~~~ ^

If I understand C's operator precedence rules
(http://en.cppreference.com/w/c/language/operator_precedence)
correctly, then I suspect the problem is in the sub-expression:

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

where pid (an argument to the macro) is first cast to a clockid_t (aka
[signed] int), then negated, then shifted by 3 (oops, undefined
behavior).

Should the result after negation be cast to an unsigned int, or should
the left shift happen before negation?

CPUCLOCK_PID and CLOCKID_TO_FD seem to shift then negate, but
FD_TO_CLOCKID seems to have the same issue as MAKE_PROCESS_CPUCLOCK.

Changing the sub-expression to:

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

changes what it evaluates to.  Changing it to:

(~(unsigned) (pid) << 3)

or

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

or

(((unsigned) ~(clockid_t) (pid)) << 3) /* ugly */

does not.

I'm happy to send a patch with your suggestion.

^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2018-01-04 14:04 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2017-12-24  3:26 precedence bug in MAKE_PROCESS_CPUCLOCK macro? Nick Desaulniers
2017-12-28 15:49 ` Thomas Gleixner
2017-12-29  3:01   ` [PATCH] posix-timers: prevent UB from shifting negative signed value Nick Desaulniers
2017-12-29  3:08     ` Nick Desaulniers
2017-12-29  3:11     ` [PATCH v2] " Nick Desaulniers
2018-01-04 14:01       ` [tip:timers/core] posix-timers: Prevent " tip-bot for Nick Desaulniers

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®