我查看的WebKit代碼是較早的60605版本,沒有觀察新版本是否已經修複。
在O2最佳化下,gcc可能存在過度最佳化的情況。具體來說,WebCore/dom/QualifiedName.h裡
inline unsigned hashComponents(const QualifiedNameComponents& buf){ //... const uint16_t* s = reinterpret_cast<const uint16_t*>(&buf); //...}//... QualifiedNameComponents c = { name->m_prefix.impl(), name->m_localName.impl(), name->m_namespace.impl() }; return hashComponents(c);
hashComponents裡期望通過s能取到buf(即c)裡的內容,但是在O2最佳化下,hashComponents被inline後,c的初始化動作因為亂序最佳化會被延遲(編譯器認為s和c是無關變數),導致從s中取到的是未初始化的值。
類似的情況見:http://wenku.baidu.com/view/18d193d03186bceb19e8bb1f.html簡單做法是將上述hashComponents裡的代碼修改為
volatile QualifiedNameComponents tmpBuf = buf; volatile uint16_t* s = reinterpret_cast<volatile uint16_t*>(&tmpBuf);
引入tmpBuf是為了構造一個值拷貝以促進buf完成初始化。volatile關鍵字必須有,否則tmpBuf可能被最佳化掉。 關於這個問題的簡單測試案例:
#include <stdio.h>typedef struct MyStruct{ short field1; short field2;}MyStruct;int main(int argc, char** argv){ MyStruct obj = {2, 1}; int i = *((int*)(&obj)); printf("%x\n", i); return 0;}使用O1和O2分別編譯同樣的代碼並運行
[root@localhost test]# gcc -O1 -o test_O1.bin test.c[root@localhost test]# gcc -O2 -o test_O2.bin test.c[root@localhost test]# ./test_O1.bin 10002[root@localhost test]# ./test_O2.bin 553dd0
兩種最佳化下輸出結果不一致,編程時要特別注意這一點。