Linux上的程序集:程序集的意外行为

时间:2018-02-27 11:39:05

标签: linux assembly linux-kernel x86

运行下面的代码会生成一个以Welcome to jj Shashwat为内容的文件。我没有得到的是为什么它在文件的末尾写ShashwatShashwat是一个完全不同的变量。知道为什么会这样吗?

section .text
   global _start         ;must be declared for using gcc

_start:  

   ;create the file
   mov  eax, 8
   mov  ebx, file_name
   mov  ecx, 0777        ;read, write and execute by all
   int  0x80             ;call kernel

   mov [fd_out], eax

   ; close the file
   mov eax, 6
   mov ebx, [fd_out]

   ;open the file for reading
   mov eax, 5
   mov ebx, file_name
   mov ecx, 2             ;for read/write access
   mov edx, 0777          ;read, write and execute by all
   int  0x80

   mov  [fd_out], eax

   ; write into the file
   mov  edx,len          ;number of bytes
   mov  ecx, msg         ;message to write
   mov  ebx, [fd_out]    ;file descriptor 
   mov  eax,4            ;system call number (sys_write)
   int  0x80             ;call kernel

   ; close the file
   mov eax, 6
   mov ebx, [fd_out]

   mov  eax,1             ;system call number (sys_exit)
   int  0x80              ;call kernel

section .data
        file_name db 'myfile.txt', 0
        msg db 'Welcome to jj', 0
        mgafter db ' Shashwat', 0
        lntwo equ $-mgafter
        len equ  $-msg

section .bss
        fd_out resb 1
        fd_in  resb 1
        info resb  26

1 个答案:

答案 0 :(得分:4)

这是因为您在定义len equ $-msgmsg之后说msgafter,因此len设置为msg和{{1}的长度},使msgafter调用写入两个字符串。这是因为write表示“将len equ $-msg设置为当前位置(len)与$的位置之间的差异。”

要解决此问题,请在msg定义后立即移动len equ $-msg行。