汇编语言简介

本文更新于 2018.10.24

汇编代码的两种记法

  • intel:

    mov ecx, AABBCCDDh
    
  • AT&T:

    movl $0xAABBCCDD, %ecx
    

CentOS运行nasm

安装软件包:

$ yum install nasm

要在64位系统上编译运行32位汇编程序(gcc -m32), 需要安装:

$ yum install libgcc.i686
$ yum install glibc-devel.i686

查看支持的所有输出格式:

$ nasm -hf
valid output formats for -f are (`*' denotes default):
  * bin       flat-form binary files (e.g. DOS .COM, .SYS)
    ith       Intel hex
    srec      Motorola S-records
    aout      Linux a.out object files
    aoutb     NetBSD/FreeBSD a.out object files
    coff      COFF (i386) object files (e.g. DJGPP for DOS)
    elf32     ELF32 (i386) object files (e.g. Linux)
    elf64     ELF64 (x86_64) object files (e.g. Linux)
    elfx32    ELFX32 (x86_64) object files (e.g. Linux)
    as86      Linux as86 (bin86 version 0.3) object files
    obj       MS-DOS 16-bit/32-bit OMF object files
    win32     Microsoft Win32 (i386) object files
    win64     Microsoft Win64 (x86-64) object files
    rdf       Relocatable Dynamic Object File Format v2.0
    ieee      IEEE-695 (LADsoft variant) object file format
    macho32   NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (i386) object files
    macho64   NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (x86_64) object files
    dbg       Trace of all info passed to output stage
    elf       ELF (short name for ELF32)
    macho     MACHO (short name for MACHO32)
    win       WIN (short name for WIN32)

汇编为ELF 32位object文件:

$ nasm -f elf hello.asm

链接为32位可执行文件:

$ gcc -m32 -o first first.o asm_io.o driver.c

查看可执行文件的属性:

$ file first
first: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs),
for GNU/Linux 2.6.32, BuildID[sha1]=593c03319f41b2377c5de4f2e650a50bfeced720, not strip

gcc生成C代码对应的汇编代码(intel记法):

$ gcc -S -masm=intel test.c

icc生成C代码对应的汇编代码(intel记法):

$ icc -S -masm=intel test.c

以32位形式反汇编程序:

$ objdump -M i386,intel,intel-mnemonic,data32,addr32 -d hello

操作数

// 立即数, 寄存器, 内存地址

基本指令

// mov, add ...

指示符

// resv, db ...

输入输出

代码模板

// skel.asm

第一个程序

  • 源文件: asm_io.inc, asm_io.asm, first.asm, driver.c, 见 https://github.com/zzqcn/storage/tree/master/code/asm

  • 编译链接(Linux):

    nasm -f elf asm_io.asm
    nasm -f elf first.asm
    gcc -m32 -o first asm_io.o first.o driver.c
    
  • 运行:

    $ ./first
    Enter a number: 2
    Enter another number: 3
    Register Dump # 1
    EAX = 00000005 EBX = 00000005 ECX = EAE0B455 EDX = FFAEC1A4
    ESI = 00000000 EDI = 00000000 EBP = FFAEC158 ESP = FFAEC138
    EIP = 080484E7 FLAGS = 0206                PF
    Memory Dump # 2 Address = 0804A054
    0804A050 72 3A 20 00 59 6F 75 20 65 6E 74 65 72 65 64 20 "r: ?You entered "
    0804A060 00 20 61 6E 64 20 00 2C 20 74 68 65 20 73 75 6D "? and ?, the sum"
    You entered 2 and 3, the sum of these is 5