Question

Update: I'm allowed to use strcpy in my code.

I'm trying to write an implementation of strdup in x86 assembly (att syntax), converting the code in C to code in Assembly.

Code in C:

char* func( int x, char* name){

    namestr = (char *) malloc( strlen(name) + 1 );
    strdup( namestr, name );
    free( name ); //Just showing what I plan to do later.

    return namestr;

}

Code in Assembly:

;basic start, char* I'm trying to copy is at 12(%ebp)
new_string: 
    pushl   %ebp
    movl    %esp, %ebp
    pushl   %edi
    subl    $20, %esp
    movl    12(%ebp), %ecx
    movl    %ecx, %edi
    movl    (%ecx), %ecx
    movl    %ecx, -8(%ebp)

;get the length of the string + 1, allocate space for it
.STR_ALLOCATE: 
    movl    $0, %eax
    movl    $-1, %ecx
    repnz   scasb
    movl    %ecx, %eax
    notl    %eax
    subl    $1, %eax
    addl    $1, %eax
    movl    %eax, (%esp)
    call    malloc
    movl    %eax, -12(%ebp)

;copy value of of the char* back to %eax, save it to the stack, pass the address back
.STR_DUP: 
    movl    -8(%ebp), %eax
    movl    %eax, -12(%ebp)
    leal    -12(%ebp), %eax

.END:
    popl    %edi
    leave
    ret

When I run the code, I only get a part of the char* back. Example: Passing in "Stack Overflow" gets me "Stac@@#$$". I guess I'm doing something wrong with the movl, not really sure what.

p/s: I'm pretty sure that my strlen works.

Part 2: Would the code I wrote pass back a pointer to the caller? As in the ability to free whatever space I allocated later.

Was it helpful?

Solution

With a bit rusty assembler skills it would look like this:

    pushl   %ebp
    movl    %esp, %ebp
    pushl   %edi
    pushl   %esi
    subl    $20, %esp
    movl    12(%ebp), %edi
;get the length of the string + 1, allocate space for it
.STR_ALLOCATE: 
; next is dangerous. -1 is like scan "forever". You might want to set a proper upper bound here, like in "n" string variants.
    movl    $-1, %ecx
    repnz   scasb
    notl    %ecx
;    subl    $1, %ecx
;    addl    $1, %ecx
    movl    %ecx, -8(%ebp)
    pushl   %ecx
    call    malloc
    add     $4,%esp
    movl    %eax, -12(%ebp)   
    movl    -8(%ebp),%ecx
    movl    %eax, %edi
    movl    12(%ebp).%esi
    rep     movsb
    movl    -12(%ebp),%eax
    popl    %esi
    popl    %edi
    leave
    ret     
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top