time_after是不是有bug

o倚楼听风雨o 2016-11-05 06:19:23
之前内核time_after定义为:
#define time_after(a,b) \
(typecheck(unsigned long, a) && \
typecheck(unsigned long, b) && \
((long)(b) - (long)(a) < 0)

若a,b为unsigned char型,该宏简化成
#define time_after(a, b) ((char)(b)-(char)(a)<0)

当a = 130, b = 125时,理论上该宏应该返回真,但是a转化成char型后为-126,b转化成char型后仍为125, 此时b - a = 125-(-126)=251>0, 该宏返回假!!!!所以说这个宏是不是有bug。

我查看了最新的内核,发现该宏的定义变成
之前内核time_after定义为:
#define time_after(a,b) \
(typecheck(unsigned long, a) && \
typecheck(unsigned long, b) && \
((long)((b) - (a) )< 0)
就是先相减,再进行类型转换了,这样就没有问题了!!!

所以我想问,之前内核的time_after是不是有bug?????????

...全文
502 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
nswcfd 2016-11-07
  • 打赏
  • 举报
回复
commit 5a581b367b5df0531265311fc681c2abd377e5e6 Author: Paul E. McKenney <paulmck@linux.vnet.ibm.com> Date: Sat Jul 27 03:53:54 2013 -0700 jiffies: Avoid undefined behavior from signed overflow According to the C standard 3.4.3p3, overflow of a signed integer results in undefined behavior. This commit therefore changes the definitions of time_after(), time_after_eq(), time_after64(), and time_after_eq64() to avoid this undefined behavior. The trick is that the subtraction is done using unsigned arithmetic, which according to 6.2.5p9 cannot overflow because it is defined as modulo arithmetic. This has the added (though admittedly quite small) benefit of shortening four lines of code by four characters each. Note that the C standard considers the cast from unsigned to signed to be implementation-defined, see 6.3.1.3p3. However, on a two's-complement system, an implementation that defines anything other than a reinterpretation of the bits is free to come to me, and I will be happy to act as a witness for its being committed to an insane asylum. (Although I have nothing against saturating arithmetic or signals in some cases, these things really should not be the default when compiling an operating-system kernel.) diff --git a/include/linux/jiffies.h b/include/linux/jiffies.h index 97ba4e7..d235e88 100644 --- a/include/linux/jiffies.h +++ b/include/linux/jiffies.h @@ -101,13 +101,13 @@ static inline u64 get_jiffies_64(void) #define time_after(a,b) \ (typecheck(unsigned long, a) && \ typecheck(unsigned long, b) && \ - ((long)(b) - (long)(a) < 0)) + ((long)((b) - (a)) < 0)) #define time_before(a,b) time_after(b,a) #define time_after_eq(a,b) \ (typecheck(unsigned long, a) && \ typecheck(unsigned long, b) && \ - ((long)(a) - (long)(b) >= 0)) + ((long)((a) - (b)) >= 0)) #define time_before_eq(a,b) time_after_eq(b,a)
nswcfd 2016-11-07
  • 打赏
  • 举报
回复
还真没注意到这个区别,可以去查查kernel的git log,看看为什么做这样的修改。 PS,顺便问一下,什么时候会用char去调用time_after呀?

4,436

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 内核源代码研究区
社区管理员
  • 内核源代码研究区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧