【问题标题】:Create a memory address alignment on x86在 x86 上创建内存地址对齐
【发布时间】:2013-04-27 07:05:22
【问题描述】:

我想在我的 x86 机器上创建内存地址对齐错误。我为什么要这样做?因为我想明确测试我的 SIGBUS 处理程序。

这是我的测试示例。

#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 上做到这一点。

我该怎么做?

【问题讨论】:

  • This post about mis-aligned pointers 似乎在问类似的问题。我不确定它是否重复,但它可能会引导您朝着正确的方向前进。
  • @Mark - 感谢您的参考。搜索正在成为一门艺术。不同之处在于,做文章中所做的只会导致 SIGSEGV 而不是 SIGBUS。 SIGBUS 是我真正感兴趣的。

标签: x86 x86-64


【解决方案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 来确定。

【讨论】:

  • VC++ short 是 16 位宽,char 是 8 位,所以你会认为 OP 的样本应该触发对齐错误。
猜你喜欢
  • 2012-04-18
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 2019-05-31
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
相关资源
最近更新 更多