achicn3
achicn3

Reputation: 123

reverse string in arm

I tried translate the following C code into arm language

int main(int argc,char **argv){

    for(int i=strlen(argv[1])-1;i!=-1;i--)printf("%c",argv[1][i]);

}

The C code is reverse the string from argv[1]

$ g++ -o reverse reverse.c

$ ./reverse abcd

$ dcba

I know the string argv[1] is store in r1+4 and argc store in r0

but I don't know what's the end address of the string argv[1],I found a post which writes that r0 store the length of r1,so I write my code base on this post, here is my arm code

 @@@@ input : hi 
 @@@@ expected output : ih
 @@@@ if "hi" is a string named a-> string aaa="hi"
 @@@@ so r3=aaa[0],and the length of aaa is r2

    .text   
    .align 2
    .global main
    .extern printf
main:
    stmfd sp!, {r0,r1,r2,r3,fp,lr}
    ldr r3,[r1,#4] ; r3 = a pointer point to argv[1]
    mov r2,r0
    sub r2,r2,#4  ;minus the last character (terminated character) 
    b LOOP
    ldmfd sp!, {r0,r1,r2,r3,fp,lr}
    bx lr

LOOP:
    ldr r0,=string
    cmp r2,r3 
    subne r2,r2,#4 ; if r2 != r3 , r2=r2-4 (address step forward) 
    bl printf ; print one character 
    bne LOOP

string:
    .asciz "%c"

this arm code is run in CodeSourcery

$ arm-none-eabi-gcc j.s -T generic-hosted.ld

$ arm-none-eabi-run a.out "hi"

$ (nothing print,what I expected output : ih)

how can I fixed my code? this question disturb me for 3 days

Upvotes: 0

Views: 3016

Answers (1)

Vidya
Vidya

Reputation: 402

This code work perfectly.

area reverseString,code
CR EQU 0x0D
 entry
 ldr r0,=data
 ldr r2,=0x40000000
 ldr r3,=0x40000020
 mov r4,#00

up ldrb r5,[r0],#1
 cmp r5,#CR
 strb r5,[r2],#1
 add r4,r4,#1
 BNE up
 sub r4,r4,#1
 sub r2,r2,#2
 BNE down

down ldrb r6,[r2]
 strb r6,[r3],#1
 sub r2,r2,#1
 subs r4,r4,#1
 BNE down


stop b stop
data dcb "Vidya",CR
 end

Upvotes: 1

Related Questions