C

共58篇文章。

一个奇怪的移位计算结果

Development

今天强迫症朱小瘦同学提到一个非常有意思的问题,一个32bit的无符号整数算术右移32个bit应该得多少?

我们知道算术右移一个bit相当于除2,所以一个32bit无符号整数除以2322^{32},理论上,应该得0。

然而事实不是这样。测试显示在x86系统上,一个32bit无符号整数算术右移32个bit之后得到的是原数。例如下面这个测试程序:

不启用任何优化的话,编译出来的程序得到的结果是:

5a5a5a5a

更进一步,我们将上面的测试改写为:

阅读全文…:一个奇怪的移位计算结果(本文约964字,阅读大致需要2分钟)

对齐操作和非对齐操作

Kernel

操作是否对齐是一个简单而容易忽略的性能(有时是可靠性)问题。对齐主要是指读写操作不产生不必要地跨越存储设备上原生存储单元的访问,这里的存储单元说的是在访问路径上的任何设备,它可以是外存,也可以是内存,甚至是CPU附近或内建的快取缓存,等等。

阅读全文…:对齐操作和非对齐操作(本文约1184字,阅读大致需要3分钟)

NULL指针引用和内核bug的利用

Security

总算是发公告了,可以说具体的事情了。

FreeBSD昨天发布了2项安全公告和1项Errata Notice:SA-09:13.pipe、SA-09:14.devfs和EN-09:05.null。两个安全公告修正的是同一类问题,也就是我们常说的多线程程序中的竞态条件(Race Condition);EN-09:05.null则是增加了一个使这类问题不再那么容易被利用达到特权提升目的的功能,但默认并不启用。

阅读全文…:NULL指针引用和内核bug的利用(本文约1342字,阅读大致需要3分钟)

memchr(3) rewrite

Development

I have taken some time to rewrite memchr(3) to utilize a similar algorithm to my strlen(3). Two different formulas, however, would have roughly a 1/3 difference.

Currently I have taken an approach where, when memchr(3) tries to match an 8-bit pattern, it treats the string as 8-bit using the first formula, which is expected to have uniform O(n)O(n) time complexity by reducing unnecessary branches.

This approach, however, might be bogus: if you look for a 7-bit character within an 8-bit string, memchr(3) will perform poorly when there are many characters with their MSB set to 1.

阅读全文…:memchr(3) rewrite(本文约109字,阅读大致需要1分钟)

New strlen(3) committed

Development

Finally, I got my strlen(3) [1] committed against -HEAD. This is a long story, to put it short, I had proposed assembly version of some string operations at the point of 2005, but these was never committed due to a hard disk failure, and as Bruce pointed out, having the hand optimized assembly code use a different algorithm is not good in general.

Therefore, I have take some time on it and reimplemented the idea in C,resulting in a portable (say, you can use it on any 32-bit or 64-bit processors, and it can be easily extended to 128-bit) version.

So, is it important for *YOU*?

Generally speaking, it should not. Performance sensitive programs should, by all means, avoid C style string operations. Think a 5x better strlen(3) would boost performance of your application since it uses strlen(3) in critical path? Think again!

However, I found it valuable. There is difference in worldstone, where I saw some minor improvements. Micro-benchmark indicates that this version is at most 2x slower when the string is very short, but 5x faster for strings that is at least word-length long.

[1] Note: the version has been further revised to provide better comment and match style(9).

阅读全文…:New strlen(3) committed(本文约292字,阅读大致需要2分钟)
搜索文章…(按ESC退出)