0

更新:我被允许在我的代码中使用 strcpy。

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

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 部分:我编写的代码会将指针传回给调用者吗?就像释放我稍后分配的任何空间的能力一样。

4

1 回答 1

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     
于 2012-10-13T15:44:41.910 回答