0

I'm new to asm, and I'm writing a very simple asm code like 2^3 + 5^2, but get segment fault error.

I used gdb and found the place which raise segment fault, but can't understand why.

My platform is CentOS 7.

This is my code:

.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
        # segment fault?
        # this line get segment fault
        movl 8(%ebp), %eax
        movl 12(%ebp), %ecx
        movl %ebx, -4(%ebp)

    power_loop_start:
        cmpl $1, %ecx
        je end_power
        movl -4(%ebp), %eax
        imull %ebx, %eax
        movl %eax, -4(%ebp)
        decl %ecx
        jmp power_loop_start

    end_power:
        movl -4(%ebp), %eax
        movl %ebp, %esp
        popl %ebp
        ret
GuoJing
  • 13
  • 1
  • 1
  • 11
  • 1
    Any possibility you are on 64-bit Linux, and you haven't told the assembler you are assembling a 32-bit program? You'd have to show us the commands you use to assemble and link your program. Edit your question with the information. If you are using `as` to assemble add `--32` to the options you are using for your `as` command. if using `ld` to link add `-m elf_i386` . If you are using _GCC_ for compiling/assembling and or linking you'd have to add `-m32` – Michael Petch May 02 '16 at 04:32
  • In `power`, you are doing `movl %ebx, -4(%ebp)`, but ebx hasn't yet been assigned a value. Then you start reading that value in `power_loop_start`. I don't see how that would get you a seg fault, but it doesn't seem like it would do anything useful either. – David Wohlferd May 02 '16 at 06:09
  • So you stepped through with a debugger and found the place that generates the segmentation fault... but you have chosen not to share with us which line that is, forcing us to walk through all of your code? Sorry, no. – David Hoelzer May 02 '16 at 09:37
  • @DavidHoelzer hi, Sorry, I added the segment fault information into the comment. The line 'segment fault?'. I'm not good at English. If anything make you unhappy, I am sorry. – GuoJing May 02 '16 at 09:52
  • @MichaelPetch thanks, let me try, I will let you know if I get the result. Thanks and sorry for poor English. – GuoJing May 02 '16 at 09:55
  • @DavidHoelzer hi, I add one more comment so I think it will be more clear. – GuoJing May 02 '16 at 10:13
  • @MichaelPetch Thanks, it's working. I'm using `ld`, thanks very much for helping me. – GuoJing May 02 '16 at 12:53

0 Answers0