Cristian G
Cristian G

Reputation: 47

Why is my assembly code exiting prematurely despite it working in a separate file?

This assembly file is for my raspberry pi (ARM assembly). I'm converting this: if(9<x && x<=10){ r0 += 7; //otherwise exit }
Into assembly code, which is the bottom half of _start: . Simply, I have this:

     .global _start
_start:
     mov r0, #0
     mov r1, #10


     cmp r1, #5
     bgt _true

     cmp r1, #10 @ x < 10
     bge _else
     add r0, #3

    cmp r1, #9 @ *here is where the program messes up and exits*
    ble _exit
    cmp r1, #10
    bgt _exit
    mov r0, #7
_true:
       add r0, #1
_else:
       add r0, #5
_exit:
       mov r7, #1
       swi 0

I believe my logic is fine because I isolated the problem into a different .s file and it works perfectly.

     .global _start
    _start:
        cmp r1, #9 @ *this works as expected*
        ble _exit
        cmp r1, #10
        bgt _exit
        mov r0, #7
    _exit:
        mov r7, #1
        swi 0

I'm thinking I could solve this problem if I put this at the top half instead of the bottom, but I would like to know why this is happening. Some guidance would be much appreciated.

In terminal I run these command lines to build:

Upvotes: 1

Views: 254

Answers (1)

sinkmanu
sinkmanu

Reputation: 1102

It is normal because after the first comparison will branch to _true (because !Z && N==O) and continue until the end (_else and _exit).

     .global _start
_start:
     mov r0, #0
     mov r1, #10


     cmp r1, #5
     bgt _true          @ It will branch to true because !Z && N==O

But, answering to your question, you have to jump to _exit after _true and _else (or branch with link (bl)), because if not, you will continue running instructions secuentially. In addition, if you don't want use branch with link (bl), you can put _exit at the top and b _exit in _true and _else.

e.g.

     .global _start

_exit:
       mov r7, #1
       swi 0

_start:
     mov r0, #0
     mov r1, #10


     cmp r1, #5
     bgt _true

     cmp r1, #10 @ x < 10
     bge _else
     add r0, #3

    cmp r1, #9 @ *here is where the program messes up and exits*
    ble _exit
    cmp r1, #10
    bgt _exit
    mov r0, #7
_true:
       add r0, #1
       b _exit

_else:
       add r0, #5
       b _exit

Upvotes: 1

Related Questions