2

我编写了一个简单的程序集外部程序,它接受输入ESI->buffer addressEDI->number to printifEDI=0 print till null character并将其打印到控制台。如果将其源代码复制到主程序中,它就可以完美运行。但是,如果它在一个单独的文件中并使用链接在一起,它会导致双重打印

ld main.o write.o -o main

并组装为

nasm -f elf64 -o write.o write.asm

写程序:

section .text
global write
write:       ; Save registers state 
    push rdx    
    push rbx
    push rcx
    
    cmp edi, 0                ; test if edi = 0
    je loop_setup             ; if true calculate string length
    mov edx, edi              ; If edi != 0 store number of bytes in edx
    
sys_write: 
       mov eax, 4             ; specify sys_write
       mov ebx, 1             ; specify file descriptor 1
       mov ecx, esi           ; Pass Buffer address
                              ; edx already contain number of bytes to write
       int 80h                ; make sys_call   
        ; Restore back all registers modifed except eax(contain return code)
       pop rcx
       pop rbx
       pop rdx   
       ret              ; Return back to the caller
          
loop_setup: mov edx, 0              ; set write counter to zero 
loop_part:   
        mov al, byte[esi+edx]       ; store byte into al adjusted by counter
        inc edx                     ; increment counter by one byte 
        cmp byte al, 0              ; check if character is "/0"
        jne loop_part               ; loop back until find null character
        jmp sys_write               ; go to sys_write if found

主程序为

section .data
    name: db "test",0
section .text
global _start
_start:
    mov esi, name
    mov edi, 0
    call write
4

0 回答 0