section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
mov edx, len ;message length
mov ecx, msg ;message to write
mov ebx, 1 ;file descriptor (stdout)
mov eax, 4 ;system call number (sys_write)
int 0x80 ;call kernel
mov eax, 1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg db 'Hello, world!',0xa ;our dear string
len equ $ - msg ;length of our dear string
Run Code Online (Sandbox Code Playgroud)
这是打印"Hello,World!"的基本汇编代码.屏幕上.现在我想问一下这段代码是如何在幕后工作的.就像所有这些指令的需要一样
nasm -felf -g -Fdwarf hello.asm
gcc …Run Code Online (Sandbox Code Playgroud) 幸运的是,学习计算机编程艺术的所有用途都可以访问Stack Overflow等社区!我决定承担学习如何编程计算机的任务,我正在通过一本名为"从头开始编程"的电子书的知识这样做,该电子书教会读者如何用汇编语言创建程序在GNU/Linux环境中.
我在本书中的进展已经到了创建一个程序,该程序用函数计算整数4的阶乘,我已经完成并完成了没有由GCC的汇编程序引起的或由运行程序引起的任何错误.但是,我的程序中的功能没有返回正确的答案!阶乘4是24,但程序返回值0!说对了,我不知道为什么会这样!
以下是供您考虑的代码:
.section .data
.section .text
.globl _start
.globl factorial
_start:
push $4 #this is the function argument
call factorial #the function is called
add $4, %rsp #the stack is restored to its original
#state before the function was called
mov %rax, %rbx #this instruction will move the result
#computed by the function into the rbx
#register and will serve as the return
#value
mov $1, %rax #1 must be placed inside this register for
#the exit system …Run Code Online (Sandbox Code Playgroud) 我知道这int 0x80会在 linux 中造成中断。但是,我不明白这段代码是如何工作的。它会返回一些东西吗?
代表什么$ - msg?
global _start
section .data
msg db "Hello, world!", 0x0a
len equ $ - msg
section .text
_start:
mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, len
int 0x80 ;What is this?
mov eax, 1
mov ebx, 0
int 0x80 ;and what is this?
Run Code Online (Sandbox Code Playgroud) 请注意,这个问题在这里已经有类似的答案,我想指出:
然而,这个问题更多地询问它们的返回格式以及它们如何相互关联(我认为上面的问题没有完全涵盖)。
_start和之间有什么区别main?在我看来,像ld用途_start,但gcc用途main为切入点。我注意到的另一个区别是main似乎返回值 in %rax,而_start返回值 in%rbx
以下是我看到的两种方式的示例:
.globl _start
_start:
mov $1, %rax
mov $2, %rbx
int $0x80
Run Code Online (Sandbox Code Playgroud)
并运行它:
$ as script.s -o script.o; ld script.o -o script; ./script; echo $?
# 2
Run Code Online (Sandbox Code Playgroud)
另一种方式:
.globl main
main:
mov $3, %rax
ret
Run Code Online (Sandbox Code Playgroud)
并运行它:
$ gcc script.s -o script; ./script; echo $?
3
Run Code Online (Sandbox Code Playgroud)
这两种方法有什么区别?是否main自动调用_start某处,或者它们如何相互关联?为什么一个返回它们的值,rbx而另一个返回它的值rax …