1

I want to create a memory address alignment fault on my x86 machine. Why do I want to do this? Because I would like to expressly test out my SIGBUS handler.

Here is my test example.

#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;
}

I know this will create a misalignment exception on the SPARC architecture. But, I can't for the life of me figure out how to do it on x86.

How can I do it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • [This post about mis-aligned pointers](http://stackoverflow.com/questions/548164/mis-aligned-pointers-on-x86) seems to be asking a similar question. I'm not sure it is a duplicate but it might lead you in the right direction. – Mark Wilkins May 02 '13 at 23:42
  • @Mark - Thanks for this reference. Searching is becoming a fine art. The difference is that doing what is done in the article only causes a SIGSEGV and not a SIGBUS. The SIGBUS is what I'm really interested in. – Brad Walker May 03 '13 at 00:00

1 Answers1

1

To create an alignment fault, you have to set the AC flag in EFLAGS. That is bit 18.

A simple way to do that in assembly is:

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

I'm not sure you can do this with a short, depending on how short a short is. An 8-bit access is always aligned, since you can't access less than 8 bits anyway. Try using an int just to be sure.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319