Segmentation error in assembly language

I am studying AT&T x86 assembler. I am trying to write a build program that takes an integer n and then returns the result (n / 2 + n / 3 + n / 4). Here is what I did:

.text
.global _start
_start:
    pushl $24
    call profit
    movl %eax, %ebx
    movl $1, %eax
    int $0x80

profit:
    popl %ebx
    popl %eax
    mov $0, %esi
    movl $4, %ebp
    div %ebp
    addl %eax, %esi
    movl %ecx, %eax
    movl $3, %ebp
    div %ebp
    addl %eax, %esi
    movl %ecx, %eax
    movl $2, %ebp
    div %ebp
    addl %eax, %esi
    movl %esi, %eax
    cmpl %ecx, %esi
    jg end
    pushl %ebx
    ret

end:
    mov %ecx, %eax
    ret

The problem is that I get a segmentation error. What is the problem?

+5
source share
5 answers

I think the code does not work here:

_start:
    pushl $24
    call profit
    movl %eax, %ebx
    movl $1, %eax
    int $0x80

profit:
    popl %ebx
    popl %eax

So, you push $24(4 bytes), and then call profitthat pushes eipand goes on profit. Then you add the value eipin ebxand the value $24in eax.

, , jg end end:, , ret . , pushl %ebx.

    cmpl %ecx, %esi
    jg end
    pushl %ebx
    ret

end:
    mov %ecx, %eax
    ; `pushl %ebx` is needed here!
    ret
+8
  • ecx ( , Linux ecx ) 0 , )
  • jg end , , ret .
+2

, . x86 ABI (32-, 64- ), " ".

, , : _start, main, C. - , , C , , . , ; C. , , errno ..

+2

, pushl, , , , popl. , , , , ret .

push pop .

.

+1

, , , . , push %ebx.

, , . Linux , , , .

, ,

popl %ebx
popl %eax

,

movl 4(%esp), %eax

, .

subl $4, %esp

after calling the procedure to remove the argument from the stack. It is important to follow this convention correctly if you want you to be able to name your build procedures from other languages.

+1
source

All Articles