Saturday, 22 June 2013

Structured Programs

A subroutine to print a vector of bytes is:

# this subroutine prints vectors of bytes
# inputs
#   r0 - start of vector
#   r1 - number of elements to print
#   r2 - pointer to start of string used to print each element
# no outputs
.globl _vprintb
.equ datum_size,1                     @ 1 because we are using bytes
 stmfd sp!, {r4, r5, r6, lr}          @ stash the registers we use
 mov r4, r0                           @ r4 is the pointer to the data
 mov r5, r1                           @ r5 is the counter
 mov r6, r2                           @ r6 is the pointer to the string
 ldrb r1, [r4], #datum_size           @ put the vector element in r1 
                                      @ implicitly increment the pointer r4 by datum_size
 mov r0, r6                
 bl  printf                           @ print the string containing the vector element
 subs r5, r5, #1                      @ decrement the counter
 bne vprintb_loop                     @ loop if the counter is not zero

 ldmfd sp!, {r4, r5, r6, pc}          @ restore the stashed registers

A simple test harness to use the subroutine is given by

.equ datum_size,1
.globl main
.section .rodata
 .asciz "The value is %d\n"
 .byte 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60
 ldr r0, =values               @ the start of the vector
 mov r1, #11                   @ the number of elements
 ldr r2, =output               @ the output string
 bl _vprintb                   @ call the subroutine

 mov     r7, #1                @ set r7 to 1 - the syscall for exit
 swi     0                     @ then invoke the syscall from linux

bob@poland:~/www/examples$ make test_vprintb
/usr/bin/gcc -gstabs -o test_vprintb test_vprintb.s vprintb.s
bob@poland:~/www/examples$ ./test_vprintb
The value is 10
The value is 15
The value is 20
The value is 25
The value is 30
The value is 35
The value is 40
The value is 45
The value is 50
The value is 55
The value is 60

No comments:

Post a Comment