WebKit在gcc編譯器下出現的亂序最佳化bug

來源:互聯網
上載者:User

我查看的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
兩種最佳化下輸出結果不一致,編程時要特別注意這一點。 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.