首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Linux x86中用nasm保存汇编语言文件?

如何在Linux x86中用nasm保存汇编语言文件?
EN

Stack Overflow用户
提问于 2013-11-11 04:28:27
回答 2查看 2K关注 0票数 0

我只是想知道怎样才能将缓冲区抛给一个文件。我知道我可以像这样设置寄存器:

代码语言:javascript
复制
mov eax, 4
mov ebx, (file descriptor here)
mov ecx, myBuffer
mov edx, myBufferLen
int 80h

然后使用以下命令关闭该文件:

代码语言:javascript
复制
mov eax, 6
int 80h

但我不确定如何获得文件描述符。有人告诉我,无论何时打开文件,在调用服务分派器之后,eax都会有文件描述符。无论我如何尝试,它都不会创建新文件或保存当前文件。

EN

回答 2

Stack Overflow用户

发布于 2013-11-11 05:28:40

代码语言:javascript
复制
mov eax, 5 ; __NR_open
mov ebx, filename ; zero terminated!
mov ecx, 2 ; O_WRITE? Check me on this!
mov edx, 777q ; permissions - Check me on this, too!
int 80h
; did we succeed?
cmp eax, -4096
ja exit
mov [descriptor], eax
; and so on...
;...
xor eax, eax ; claim no error
exit:
mov ebx, eax
neg ebx
mov eax, 1 ; __NR_exit
int 80h

我不确定open标志和权限的“魔术数字”,而且现在懒得去查找它们(fs.h?)。您可能需要在O_CREATE中使用“或”打开标志来创建新文件(?)。"exit:“的诀窍是否定(负) ERRNO (如果有的话),这样您就可以用"echo $?”轻松地读取它。诸如此类的事情。

票数 0
EN

Stack Overflow用户

发布于 2013-11-11 05:39:03

感谢@gnometorule提供的解决方案。因此,这就是如何将缓冲区存储到文件中:在这种情况下,当您运行程序时,您将收到作为第一个参数的文件名。

代码语言:javascript
复制
section .text
    global _start

_start:

    pop ebx ; this is the amount of parameter received (in this case 2)
    pop ebx ; this is the direction of our program
    pop ebx ; this is the first parameter (our file name eg. "text.txt") 

因此,我们打开它,并将其移动到缓冲区进行编辑或任何我们想要的东西。

代码语言:javascript
复制
textEdit:

    ;we open the file

    mov eax, 5
    push ebx   ; we save the file name in the stack for later use
    mov ecx,0 
    int 80h

    ; and then we move the information read to buffer

    mov eax, 3
    mov ebx, eax             ; really dont know how this works, but it does.
    mov ecx, fileBuffer
    mov edx, fileBufferSize
    int 80h 

现在,fileBuffer (它是在.bss一节中定义的缓冲区)包含了我们打开的文件中的内容。您可以在此处编辑信息。当我们想要将它保存回文件时,它是这样的:

代码语言:javascript
复制
saveFile:

        ;open the file

    mov eax, 5
    pop ebx                ; the file name was stored in the stack, 
    push ebx               ; so we retrieve it and save it back for later use
    mov ecx, 2             ; ecx has the access mode ("2"aloud us to read/write) 
    mov edx, $0666 
    int 80h

        ;now we are going to write to the file

    mov ebx, eax               ; eax has the file descriptor we opened. so we move it to ebx.
    mov eax, 4                 ; we are going to use the write service (#4)
    mov ecx, fileBuffer        ; ecx has the adress of what we want to write
    mov edx, fileBufferSize    ; edx has the amount of bytes we want to write
    int 80h

        ; close the file

    mov eax, 6
    int 80h

    jmp exit  ; jump wherever you want, or end your program... etc.

这对我很有效。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19894769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档