【问题标题】:Assembly on Linux: unexpected behaviour from Assembly [duplicate]Linux 上的程序集:程序集的意外行为 [重复]
【发布时间】:2018-08-07 01:09:48
【问题描述】:

运行下面的代码会生成一个以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

【问题讨论】:

  • 不知道为什么这会让您感到惊讶。您要求它将len 字节的数据写入文件,并且您已将len 定义为msg 定义和msgafter 定义结束之间的所有字节。所以两者都在写。
  • 赞成,因为它包含了一个好的问题应该包含的所有点点滴滴(源代码、观察到的行为、预期的行为、对行为意外原因的解释)并且代码被很好地注释了。如果能把更多的问题写得那么好,那么回答问题将是一种更愉快的体验。
  • 汇编中没有变量,只有字节......当您写入 24 字节而不是 14 字节时,文件中有 24 字节。此外,您可能不想将零字节存储到文本文件中?这非常罕见,我宁愿添加换行符,即我会将源数据定义更改为:...to jj', 10 以在最终文本文件中添加换行符。 (顺便说一句,关于$ 在那些equ 中所做的事情有一些相当好的重复,所以如果fuz 答案不完全清楚,请搜索一些关于nasm、equ 和$ 的问题。(尽管我认为答案很清楚:) ))
  • @fuz:已经有一个完全相同的副本。但是,是的,写得很好的问题很好,并且可以很容易地看出问题所在。 @Shashwat:作为副本关闭并不意味着这是一个坏问题;如果您不知道问题发生的原因,则无法搜索正确的术语以找到重复项。
  • fd_out: resb 1 是个问题。您正在加载/存储 4 个字节,但您只保留了 1 个。mov [fd_out], eaxfd_in 之后覆盖resb,在info 之后覆盖resb 的前两个字节为好吧。 (正如 Ped7g 所说,程序集没有变量:标签只是让您参考地点的标记,由您决定数据布局 + 您的加载/存储指令是否有意义。)

标签: linux assembly linux-kernel x86


【解决方案1】:

那是因为你在定义msgmsgafter 之后说len equ $-msg,所以len 设置为msgmsgafter 的长度,使你的write 调用写入两个字符串。这是因为len equ $-msg 的意思是“将len 设置为当前位置($) 和msg 的位置之间的差异。”

要解决此问题,请将 len equ $-msg 行移到 msg 的定义之后。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多