0

I stumbled upon an assembly programming challenge where I need to find why the following code gives a Bus Error when trying to run it. After much googling, I still can't figure out why.. My understanding of assembly x86 not great, any tips on finding the solution would be very appreciated.

Here is the code:

#include <stdlib.h>
int main(void) {
  asm("pushf\n"
      "orl $ 0x40000, (%esp)\n"
      "popf\n");

  *((int*) (((char*) malloc(5)) + 1)) = 23; // This line causes the Bus Error


  return 0;
}
juliensaad
  • 2,019
  • 2
  • 20
  • 27

1 Answers1

1

Essentially you are setting a flag in the flags register. Flag 0x40000, aka bit 18 which according to http://en.wikipedia.org/wiki/FLAGS_register_%28computing%29 is

18 AC Alignment check (486SX+ only) X

If you search for "flag alignment check" you find amongst others:

http://forum.soft32.com/linux2/Turn-x86-Alignment-Check-ftopict12003.html

I hope this sets you on the right track. But do you really have a 486SX?

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89
  • Thank you, I have no idea if I have a 486SX is, but at least that put me on the right track. I will check for info about the flag. – juliensaad Apr 25 '12 at 19:48
  • Note that the alignment check bit of the flags register seems like a really cool idea, and could help you catch and fix non-portable misaligned accesses in your programs without building and testing them on more RISCy architectures. However, since the x86 abi only has `double`s aligned to 4 bytes and not 8, it leads to spurious `SIGBUS` on most floating point code... :-( This makes it just about impossible to use in practice unless you write a `SIGBUS` handler that checks if the exception was due to floating point load/store and works around it... – R.. GitHub STOP HELPING ICE Apr 27 '12 at 04:20