【问题标题】:Writing to a file in Assembly file descriptor trouble在程序集文件描述符问题中写入文件
【发布时间】:2014-11-17 02:33:46
【问题描述】:

我正在编写一个程序,将内容从一个文件写入另一个文件。 我现在正在做的(用于测试)是打开这两个文件并在其中一个中写入一个字符串。该程序没有显示任何错误,但是文件中没有写入任何内容。

这是我的代码

BITS 32

section .data
    msg db "Hola"

section .bss
    src_file    resb 1      ; Source file descriptor 
    dest_file   resb 1      ; Destination file descriptor

section .text
    global _start

_start:
    pop ebx             ; argc
    pop ebx             ; argv[0] nombre del ejecutable

    pop ebx             ; src file name
    ;; Open src file
    mov ecx,1           ; Write mode
    mov eax,5           ; sys_open()
    int 0x80            ; Interruption 80. kernel call
    mov [src_file],eax

    pop ebx             ; dest file name
    ;; Open dest file
    mov ecx,1           ; Write mode
    mov eax,5           ; sys_open()
    int 0x80            ; Interruption 80. kernel call
    mov [dest_file],eax

    ;; Writes in src file
    mov edx,4           ; Long
    mov ecx,msg         ; text
    mov ebx,[src_file]  ; File descriptor of dest file
    mov eax,4
    int 0x80

    ;; Closes src file
    mov ebx,[src_file]  ; File descriptor of src file
    mov eax,6           ; sys_close()
    int 0x80            ; Kernel call

    ;; Closes dest file
    mov ebx,[dest_file] ; File descriptor of src file
    mov eax,6           ; sys_close()
    int 0x80            ; Kernel call

    ;; Exits the program
    mov ebx,0           ; OS exit code
    mov eax,1           ; sys_exit
    int 0x80            ; Kernel call

我认为在打开文件后存储文件描述符可能有问题,因为如果我在打开源文件后立即移动写入文件的代码块,它就可以正常工作。

感谢您的帮助!

【问题讨论】:

    标签: linux assembly x86


    【解决方案1】:
    src_file    resb 1      ; Source file descriptor 
    dest_file   resb 1      ; Destination file descriptor
    

    文件描述符的 1 个字节不会删除它。当您执行像mov ebx,[src_file] 这样的4 字节加载时,EBX 的第二低字节将来自dest_file 字节而不是零,因此读或写系统调用将返回-EBADF。 它们需要是 DWORD 大小的变量!

    src_file    resd 1      ; Source file descriptor 
    dest_file   resd 1      ; Destination file descriptor
    

    程序没有显示任何错误

    为什么程序会显示错误?你从来没有告诉过它!这是组装,没有什么是自动的。 CPU 很乐意将文件描述符放在您告诉它的位置,然后覆盖它们之后的任何内容,因为它们还不够大。

    【讨论】:

    • 谢谢!我开始在汇编中编程,但我仍然不太了解变量的大小。谢谢
    • 对于 32 位,几乎所有内容都是 DWORD 大小的变量,除非在函数/库的文档中注明。指针是 DWORD,返回值是 DWORD,等等...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    相关资源
    最近更新 更多