0

I have a problem working on stacks.

Say for example I am in a stack and I already used movl %esp, %ebp

If I make 2 local word-sized variables (subl $4, esp), whenever I go to movw $1, -2(%ebp) it triggers a segmentation fault. Why is that so? Also, are immediate values allowed to be passed directly to stack variables?

My code is:

    movw $12, %ax 
    pushw %ax 
    call _function 
exit: 
    movl $1, %eax
    movl $0, %ebx
    int $0x80

_function: 
    movl %esp, %ebp 
    subl $4, %esp 
    movw $2, -2(%ebp) 
    addl $4, %esp 
    ret $2

I assemble, link and run with:

as myfile.s -o myfile.o
ld myfile.o 
./a.out

I'm on a 64-bit system.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Jsandesu
  • 105
  • 12
  • 1
    You assembling as 32-bit or 64-bit code? Yes, you can move an immediate to any memory operand. I also assume you mean `subl $4, %esp`. Are you actually sure it crashes right on `movw $1, -2(%ebp)`? Did you see this in the debugger? – Michael Petch Nov 25 '17 at 06:48
  • 1
    If you showed us a minimal complete verifiable example we could probably tell you what has gone wrong. – Michael Petch Nov 25 '17 at 06:54
  • This is 32-bit assembly code. – Jsandesu Nov 25 '17 at 07:10
  • Can you show us all your code and how you assemble and link it? And I'd like to see the output of this command `file ./myexec` where `myexec` is the name of your executable. – Michael Petch Nov 25 '17 at 07:10
  • You're probably building it as 64-bit, like Michael suggested: https://stackoverflow.com/questions/36861903/assembling-32-bit-binaries-on-a-64-bit-system-gnu-toolchain. That would explain what you're seeing. – Peter Cordes Nov 25 '17 at 07:13
  • movw $12, %ax pushw %ax call _function exit: movl $1, %eax movl$0, %ebx int $0x80 _function: movl %esp, %ebp subl $4, %esp movw $2, -2(%ebp) addl $4, %esp ret $2 – Jsandesu Nov 25 '17 at 07:18
  • as myfile.s -o myfile.o ld myfile.o ./a.out – Jsandesu Nov 25 '17 at 07:20
  • 1
    file ./a.out returned a message like: ELF 64-bit executable, x86-64, version 1 (SYSV), statically linked, not strippped – Jsandesu Nov 25 '17 at 07:22
  • If you are on a 64-bit system `as myfile.s -o myfile.o` followed by `ld myfile.o` will create a 64- bit executable. If you are on 64-bit Linux and want to create a 32-bit executable you'll want to use `as --32 myfile.s -o myfile.o` and `ld -melf_i386 myfile.o` – Michael Petch Nov 25 '17 at 07:22
  • The file output tells me you built a 64-bit executable (also gathered that by the commands you used to assemble and link). – Michael Petch Nov 25 '17 at 07:23
  • It worked. Thanks! – Jsandesu Nov 25 '17 at 07:26

0 Answers0