入门x86汇编语言

本文从C语言的角度出发,介绍了如何生成汇编代码,并详细解析了x86架构的硬件基础,包括寄存器(如通用寄存器、段寄存器和标志寄存器EFLAGS)、内存访问和第一个简单程序的编译流程。重点讨论了CPU的寄存器用途,如AX/EAX、BX/EBX等,以及EFLAGS寄存器中的各种标志位,如CF、PF、SF等的含义和作用。此外,还介绍了指令指针IP/EIP和内存寻址方式,如直接寻址、寄存器间接寻址等。
摘要由CSDN通过智能技术生成

从C语言到汇编

一个C语言程序从.c到可执行文件需要经过预处理(preprocessing),编译(compilation),汇编(assembly)和链接(linking)

我们观察一个最简单的例子:hello.c

#include <stdio.h>
int main(){
    printf("hello world!");
    return 0;
}

在linux中经过编译便可以得到汇编源代码hello.s

在terminal中输入gcc -S hello.c -o hello.s

hello.s

 

上面看到的就是汇编代码。汇编代码在经过汇编程序编译生成Obj文件,然后链接最终生成可执行文件

下图是在windows下汇编得到的汇编代码,你会发现有些细微的不同

一条汇编指令对应着一条机器码,汇编语言是直接对CPU编程的语言,所以针对不同的CPU架构有不同的汇编语言,这里主要讲解的是x86汇编语言

硬件基础

图1

上图表示的是CPU和内存

CPU是计算机核心部件,控制整个计算机的运作并进行运算,要想让它工作,就必须向它提供指令和数据。指令和数据就存放在内存中(也就是存储器)。

寄存器

寄存器是存储器和CPU之间数据交换的一个桥梁,存储器到CPU中的数据都要经过寄存器,存储器中不同地址中的内容的交换也要经过寄存器。了解寄存器是学习汇编语言中非常重要的

图2

上图是x86架构中的寄存器组

通用寄存器组

下图是通用寄存器组示意图

• AX/EAX — Accumulator for operands and results data(操作数和结果的累加器)
• BX/EBX — Pointer to data in the DS segment(指向数据段中的数据的指针)
•CX/ECX — Counter for string and loop operations(用于字符串和循环操作的计数器)
• DX/EDX — I/O pointer(输入输出指针)
•SI/ESI — Pointer to data in the segment pointed to by the DS register; source pointer for string operations(指向由 DS 寄存器指向的段中的数据的指针;字符串操作的源指针。也叫做源变址)
• DI/EDI — Pointer to data (or destination) in the segment pointed to by the ES register; destination pointer for
string operations(指向由 ES 寄存器指向的段中的数据(或目标地址)的指针;字符串操作的目标指针。也叫做基变址)
• SP/ESP — Stack pointer (in the SS segment)(栈顶指针)
• BP/EBP — Pointer to data on the stack (in the SS segment)(指向栈上数据的指针,作用于函数调用的返回)

以上是这些通用寄存器常见的用途,但是最主要的作用就是通用寄存器。

段寄存器

The segment registers (CS, DS, SS, ES, FS, and GS) hold 16-bit segment selectors. A segment selector is a special
pointer that identifies a segment in memory. To access a particular segment in memory, the segment selector for
that segment must be present in the appropriate segment register.

这是官方对段寄存器的解释,段寄存器用于保存 16 位的段选择器。段选择器是一种特殊的指针,用于确定内存
中某个段的位置。

段寄存器示意图

Each of the segment registers is associated with one of three types of storage: code, data, or stack.

the CS register contains the segment selector for the code segment, where the instructions being executed are stored.The processor fetches instructions from the code segment, using a logical address that consists of the segment selector in the

  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值