Search code examples
linuxassemblynewlinearmv7

Print Newline for Armv7 assembly program


I'm working on this armv7 assembly program that finds the greatest common divisor(gcd) of two integers. Everything is working fine except for the newline function. When i assemble and run the program, it doesn't print any newlines, just the integers in one line. Any suggestions on how i can fix that?

  .global _start
_start:
    mov r2, #24     @first set of integers
    mov r4, #18
    bl mysub1
    bl mysub2
    bl mysub3

    mov r2, #78     @second set of integers
    mov r4, #34
    bl mysub1
    bl mysub2
    bl mysub3

    mov r2, #99     @third set of integers
    mov r4, #36
    bl mysub1
    bl mysub2
    bl mysub3

_exit:
    mov r7, #1
    swi 0


mysub1:             @subroutine to find gcd
    cmp r2, r4
    beq done
    bgt greater
    blt less
greater:
    sub r2, r2, r4
    bal mysub1

less:
    sub r4, r4, r2
    bal mysub1
done:
    bx lr

mysub2:             @subroutine to convert gcd result to ascii value
    add r4, #48
    ldr r9, =store
    str r4, [r9]

    mov r7, #4      @print out a newline
    mov r0, #1
    mov r2, #1
    ldr r1, =newline
    swi 0

    bx lr

mysub3:             @subroutine to print out the ascii value
    mov r7, #4
    mov r0, #1
    mov r2, #2
    ldr r1, =store
    swi 0

    bx lr


    .data
store:
    .space 2

newline:
    .ascii "\n"

Solution

  • This is the culprint:

    add r4, #48
    ldr r9, =store
    str r4, [r9]
    

    This code has two bugs:

    • it only works for numbers between 0 and 9
    • str r4, [r9] stores four bytes to store, overwriting the newline right after the two-byte buffer.

    To fix the first issue, you need to do a division with rest to separate the number in r4 into two digits. To fix the second issue, use strb or strh to store a byte or halfword instead as to not overrun the buffer.