Loyal Tingley
Loyal Tingley

Reputation: 900

EXC_BAD_ACCESS in assembly function

I am trying to write a function in assembly that is callable from Objective-C code. I've gotten simple results by setting %rax and returning directly, but when I try to use the stack to store local variables, I get EXC_BAD_ACCESS. Could someone take a look at this and tell me what's going wrong? My assembly looks like this:

.global _fn
_fn:
pushq %rbp
movq %rsp, %rbp
subq 0x8, %rsp
addq 0x8, %rsp
popq %rbp
ret

Xcode dumps this and indicates the crash is at sub 0x8,%rsp when I call fn from main:

0x0000000100020000  <+0000>  push   %rbp
0x0000000100020001  <+0001>  mov    %rsp,%rbp
0x0000000100020004  <+0004>  sub    0x8,%rsp
0x000000010002000c  <+0012>  add    0x8,%rsp
0x0000000100020014  <+0020>  pop    %rbp
0x0000000100020015  <+0021>  retq

Upvotes: 0

Views: 502

Answers (1)

Alexey Frunze
Alexey Frunze

Reputation: 62106

The mere subtraction of 8 from rsp should not cause an exception.

Most likely you need to prefix the constants with the dollar sign. If you don't, (g)as will treat those numbers as memory operands at the corresponding addresses.

And accessing memory at address 8 is usually as good on the x86 platform as a NULL pointer dereference.

Upvotes: 3

Related Questions