将指针的值复制到Assembly中的另一个新指针

时间:2012-10-13 15:10:30

标签: pointers assembly att

更新:我可以在代码中使用strcpy。

我正在尝试在x86程序集中编写strdup的实现(att语法),将C中的代码转换为Assembly中的代码。

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;

}

汇编代码:

;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

当我运行代码时,我只获得了一部分char *。 示例:传入“Stack Overflow”获取“Stac @@#$$”。 我想我对movl做错了,不确定是什么。

p / s:我很确定我的strlen有效。

第2部分: 我写的代码会传回指向调用者的指针吗?因为能够释放我后来分配的任何空间。

1 个答案:

答案 0 :(得分:0)

有点生锈的汇编技能,它看起来像这样:

    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