Search code examples
assemblyx86segmentation-faultldgnu-assembler

Segmentation fault in x86 example program


I'm reading this book Programming From the Ground Up, Jonathan Bartlett. On this program that shows the function calling conventions for the first time I'm getting a segmentation fault when running it after typing it just like in the book. The function just takes 2 numbers from the stack, and returns the first number to the second number power in %eax.

Here is the program in question:

.code32

.section .data

.section .text

.globl _start
_start:

  pushl $3
  pushl $2
  call power
  addl $8, %esp

  pushl %eax

  pushl $2
  pushl $5
  call power
  addl $8, %esp

  popl %ebx

  addl %eax, %ebx

  movl $1, %eax
  int $0x80

.type power, @function
power:
  pushl %ebp
  movl %esp, %ebp
  subl $4, %esp

  movl 8(%ebp),  %ebx
  movl 12(%ebp), %ecx

  movl %ebx, -4(%ebp)

power_loop:
  cmpl $1, %ecx
  je end_power

  movl -4(%ebp), %eax
  imull %ebx, %eax
  movl %eax, -4(%ebp)
  decl %ecx

  jmp power_loop

end_power:
  movl -4(%ebp), %eax
  movl %ebp, %esp
  popl %ebp
  ret

I loaded the program in edb and stepped through it, and the segmentation fault appears when I get to the instruction that loads the first function argument. Giving the error message saying

The address 0x000000003EC56208 could not be accessed.

Shouldn't I be able to access the values pointed by (8 + %ebp) and (12 + %ebp) inside the function?


Solution

  • I guess that you want to build a 32-bit program on a 64-bit operating system. You have to tell assembler and linker about that circumstance:

    as --32 -o power.o power.s
    ld -m elf_i386 -o power power.o
    

    Run it with ./power.