Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a string with ARM/C

so I'm trying to learn ARM, and am practicing by taking a character array pointer from C, copying that string, and returning a pointer to a different character array. I've written up this code (commented with what I assume I happening):

    .global copy                    @Let the linker know what's going on

copy:                           @Start
    stmfd sp!, {v1-v6, lr}      @Push stuff onto stack
    mov r6, a1                  @Put the pointer to the original string in r6
    bl length                   @Get the length of the string
    mov a1, r4                  @Put length into the input parameter
    bl malloc                   @Allocate enough memory for our new string
    mov r9, a1                  @Move the first memory location to r9

loop:                           @Loop to copy string
    ldrb r8, [r6], #1           @Load first character from string and move pointer
    strb r8, [a1], #1           @Store character in new string and move character
    subs r4, r4, #1             @Subtract 1 from length
    bne loop                    @Stop looping if string is done
    mov a1, r9                  @Move the start of the new string to the return value
    b ending                    @Go to the ending


length:                         @Length function
    mov r4, #0                  @counter set to 0
countLoop: 
    ldrb r5, [r6], #1           @Load first character
    cmp r5, #0                  @Check for null character
    add r4, r4, #1              @Add 1 to the length
    bne countLoop               @Loop if we're not at the end
    mov pc, lr                  @Return the program

ending:
    ldmfd sp!, {v1-v6, pc}      @Pop stuff off the stack
.end

With this C driver:

#include <stdlib.h>
extern char * copy( char str[] ) ; /* declare the assembly routine */
int main( int argc, char * argv[] )
{
   char str[] = "abcd" ;
   char * result;
   result = copy( str ) ; /* call the assembly language routine */
   printf("Will this work? %s", result);
   exit(0);
}

However I keeping getting the result (null). Obviously something is not correct in my thinking, but I don't know what it is. Any help would be appreciated!

like image 542
user2255853 Avatar asked Nov 08 '22 15:11

user2255853


1 Answers

You moved the pointer to the original string to r6 at the start, however afterwards you overwrote r6 in the length function immediately after. I'd suggest to either store it somewhere else too, or use a1 directly in that function call

like image 157
wjmccann Avatar answered Nov 15 '22 05:11

wjmccann