0

Hello before I explain my problem I would like to say that I am a complete beginner to assembly programming. I'm trying to compare two variables (of int type because they are nothing but 0x10 and 0x20). I can successfully execute it with almost no error. My condition is satisfied and program executes as it was supposed to, however, it also gives me a 'Segmentation fault' and instead of returning zero it returns 139. I don't know what that means but I want to fix my issue.

Here are some details about my system and the code:

I am running a 64-bit Linux machine. I have coded the file in x64 (or AMD64) Intel syntax and compiled it with nasm.

I have posted the assembly code below:

section .text

    global _start

_start:

    ;SET VALUE TO VARIABLES
    mov rax, 0x20
    mov rbx, 0x10

    ;COMPARE THEM
    cmp rax, rbx

    jge isGreater

    ;EXIT FUNCTION
    xor rax, rax
    mov al, 60
    xor rdi, rdi
    syscall

isGreater:
    xor rax, rax
    mov al, 1
    xor rdi, rdi
    mov dil, 1
    lea rsi, [rel msg+0x11111111]
    sub rsi, 0x11111111
    mov rdx, msg_len+0x11111111
    sub rdx, 0x11111111
    syscall
    ret

msg:
    db "RAX is greater than RBX", 10
msg_len: equ $-msg

it is saved in a file called 'compare.asm'

I am compiling and linking it using the following commands:

root@kali:~# nasm -f elf64 compare.asm 
root@kali:~# ld compare.o -o compare
root@kali:~# 

now see what is the output for this:

root@kali:~# ./compare 
RAX is greater than RBX
Segmentation fault
root@kali:~# echo $?
139
root@kali:~# 

It seems like I have made a really stupid mistake but as I mentioned I am a complete beginner to all this.

Thank you for your precious time!

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • 1
    `ret` only works if you used `call` (simplified). Since you have `jge isGreater` the `ret` at the end will have no return address on the stack and hence crash. Replace the `ret` with a `jmp exit` and put an `exit:` label on the `;EXIT FUNCTION` block. – Jester Nov 01 '19 at 17:24
  • Thank you so much this was the answer I was looking for! – sopsahesta Nov 01 '19 at 17:37
  • Related but not exactly a duplicate : [What if there is no return statement in a CALLed block of code in assembly programs](//stackoverflow.com/q/41205054) is kind of the opposite problem of using `call` without `ret`, instead of `ret` without `call`. My answer explains that `ret` is just `pop rip`. – Peter Cordes Nov 02 '19 at 03:45
  • Also, use a debugger to see which instruction faulted. Your question is nothing to do with comparing integers, everything to do with how you used `ret`. – Peter Cordes Nov 02 '19 at 03:52

0 Answers0