0

I am very new to assembly and was trying to create a simple program which uses jg. Here is the code-

BITS 64

section .text
    global _start
_start:
    mov rdi, 1
    cmp rdi, 0
    jg greater

    mov rax, 1
    mov rdi, 1
    mov rsi, msg
    mov rdx, msg_len
    syscall

    mov rax, 60
    mov rdi, 0
    syscall

greater:
    mov rax, "More!!!"
    mov rdx, 10
    mov [msg], rax
    mov [msg_len], rdx

section .bss
msg: resb 12
msg_len: resb 1

I don't see any kind of error in it. The program even works well if jg greater not used. For example this program works well-

BITS 64

section .text
    global _start
_start:
    mov rdi, 1
    cmp rdi, 0
    ; jg greater

    mov rax, "More!!!"
    mov rdx, 10
    mov [msg], rax
    mov [msg_len], rdx

    mov rax, 1
    mov rdi, 1
    mov rsi, msg
    mov rdx, msg_len
    syscall

    mov rax, 60
    mov rdi, 0
    syscall

greater:
    mov rax, "More!!!"
    mov rdx, 10
    mov [msg], rax
    mov [msg_len], rdx

section .bss
msg: resb 12
msg_len: resb 1

Where is the error then? I think I must have misunderstood some concept.

Thanks in advance.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
L_R
  • 170
  • 11
  • 2
    [What happens if there is no exit system call in an assembly program?](https://stackoverflow.com/q/49674026) - Single-stepping should make it clear what happens: execution falls off the bottom of your `.text` section, because you jumped over your `_exit` syscall. Use GDB's `layout asm` to see disassembly of the instructions as you `stepi`. (See the bottom of https://stackoverflow.com/tags/x86/info for tips on using a debugger on asm.) – Peter Cordes Jun 16 '22 at 08:14
  • Thanks! Now I understand what `je` does. I previously was thinking assembly `jmp` statements to be equal to C-language's functions. – L_R Jun 16 '22 at 08:20
  • 1
    That's `call`, and the called code has to end with a `ret` while RSP is pointing at the return address. That's how you use asm instructions to implement the high-level concept of a function-call. JMP and CALL are just *instructions* for the CPU to run when reached. See [What if there is no return statement in a CALLed block of code in assembly programs](https://stackoverflow.com/q/41205054) / [Code executes condition wrong?](https://stackoverflow.com/q/32872539) / [call subroutines conditionally in assembly](https://stackoverflow.com/q/7301683) – Peter Cordes Jun 16 '22 at 10:43
  • @user1234 ```JMP```, ```je```, etc., are equal to ```goto``` in C, except they don't really care about scope. You can fix this pretty easily by putting a label before that ```mov rax,60``` and then putting a ```jmp``` to that label after ```mov [msg_len], rdx```. – puppydrum64 Jun 30 '22 at 18:22

0 Answers0