2013-05-02 41 views
1

我想在我的x86機器上創建內存地址對齊方式錯誤。我爲什麼要這樣做?因爲我想明確地測試我的SIGBUS處理程序。在x86上創建內存地址對齊方式

這是我的測試示例。

#include <stdio.h> 

int main(int argc, char** argv) { 
    unsigned char array[32]; 
    short *short_ptr; 

    short_ptr = (short *)&array[1]; 
    *short_ptr = 0xffff; // Store 
    printf("value of c = %x", *short_ptr); 

    return 0; 
} 

我知道這會在SPARC體系結構上產生不對齊異常。但是,我不能在我的生活中弄清楚如何在x86上完成它。

我該怎麼辦?

+0

[這篇文章關於mis-align指針](http://stackoverflow.com/questions/548164/mis-aligned-pointers-on-x86)似乎是問一個類似的問題。我不確定它是否是重複的,但它可能會使您朝着正確的方向前進。 – 2013-05-02 23:42:08

+0

@Mark - 感謝您的參考。搜索正在成爲一門藝術。不同的是,在文章中做什麼只會導致SIGSEGV而不是SIGBUS。 SIGBUS是我真正感興趣的。 – 2013-05-03 00:00:39

回答

1

要創建對齊錯誤,您必須在EFLAGS中設置AC標誌。那是位18

一個簡單的方法做,在組裝:

pushf  ; Push the flags onto the stack 
pop eax  ; Pop the pushed flags into EAX 
bts eax, 18 ; Set bit 18 in EAX (note, this might not work. You may need to do "mov ebx, 18; bts eax ebx") 
push eax ; Push that back onto the stack 
popf  ; Pop eflags from the stack 

我不知道,你可以用很短的做到這一點,取決於短是多麼短暫。 8位訪問始終是對齊的,因爲無論如何你都不能訪問少於8位的數據。嘗試使用int來確保。

+0

一個VC++'short'是16位寬,'char'是8位,所以你會認爲OP的樣本應該觸發對齊錯誤。 – 2013-05-03 00:00:04

+0

將short從short更改爲int不會影響exprected .. – 2013-05-03 00:35:40