gpt4 book ai didi

linux - 迷失在组装 NASM ELF64 世界

转载 作者:太空狗 更新时间:2023-10-29 11:27:37 28 4
gpt4 key购买 nike

因此,作为我的计算机体系结构类(class)的一部分,我需要熟悉 Assembly,或者至少足够舒适,我正在尝试读取用户的输入然后重新打印(暂时),这是我的我是如何尝试用伪代码来展示它的:

  1. 声明 msg 变量(这将打印在屏幕上)
  2. 声明具有足够长值的长度变量(由 sys_write 函数使用)
  3. 出栈一次得到程序名
  4. 再次出栈得到第一个参数
  5. 将栈的当前值移入msg变量
  6. 将 msg 移至 ECX(sys_write 参数)
  7. 将长度移动到 EDX(sys_write 参数)
  8. 使用标准输出调用 sys_write
  9. 内核调用
  10. 调用sys_exit并离开

到目前为止,这是我的代码

section .data
msg: db 'placeholder text',0xa;
length: dw 0x123;

section .text
global _start

_start:
pop rbx;
pop rbx;
; this is not working when I leave it in I get this error:
; invalid combination of opcode and operands
;mov msg, rbx;
mov ecx, msg;
mov edx, length;

mov eax, 4;
mov ebx, 1;
int 0x80;
mov ebx, 0;
mov eax, 1;
int 0x80;

当我省略它时(没有将参数移动到 msg 中),我得到了这个输出

placeholder text
#.shstrtab.text.data
�@�$�`��

我们真的刚刚开始使用 NASM,所以非常感谢任何帮助,我一直在看这个 http://www.cin.ufpe.br/~if817/arquivos/asmtut/index.html#stackhttp://syscalls.kernelgrok.com/根据我的理解调整注册表名称以匹配 http://www.nasm.us/doc/nasmdo11.html 的示例

我正在运行 Ubuntu 12.04,64 位编译(甚至不确定这是不是正确的词)ELF64 下的 NASM,我很抱歉问了这样一个愚蠢的问题,但我一直无法找到足够简单的 NASM 教程使用 64 位。

最佳答案

当程序被调用时,堆栈应该是这样的:

+----------------+
| ... | <--- rsp + 24
+----------------+
| argument 2 | <--- rsp + 16
+----------------+
| argument 1 | <--- rsp + 8
+----------------+
| argument count | <--- rsp
+----------------+

第一个参数是程序的名称,第二个是用户输入(如果用户键入任何内容作为参数)。所以参数的个数至少为 1。

64 位模式下系统调用的参数存储在以下寄存器中:

  • rax(系统调用号)
  • rdi(第一个参数)
  • rsi(第二个参数)
  • rdx(第三个参数)
  • rcx(第四个参数)
  • r8(第 5 个参数)
  • r9(第 6 个参数)

系统调用是用syscall调用的。可以找到所有系统调用的编号 here here (是的,它们与 32 位模式下的数字不同)。

这是应该做你的事情的程序:

section .data
msg: db 'Requesting 1 argument!', 10 ; message + newline

section .text
global _start

_start:
cmp qword [rsp], 2 ; check if argument count is 2
jne fail ; if not jump to the fail lable

mov rax, 1 ; sys_write
mov rdi, 1 ; stdout
mov rsi, [rsp+16] ; get the address of the argument
mov rdx, 1 ; one character (length 1)

loop:
cmp byte [rsi], 0 ; check if current character is 0
je exit ; if 0 then jump to the exit lable
syscall
inc rsi ; jump to the next character
jmp loop ; repeat

fail:
mov rax, 1 ; sys_write
mov rdi, 1 ; stdout
lea rsi, [rel msg] ; move the address of the lable msg in rsi
mov rdx, 23 ; length = 23
syscall

exit:
mov rax, 60 ; sys_exit
mov rdi, 0 ; with code 0
syscall

由于代码在很多方面都不够完美,您可能需要对其进行修改。

关于linux - 迷失在组装 NASM ELF64 世界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13639369/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com