在64位linux上编写32位汇编程序

例子来自IBM开发者网站http://www.ibm.com/developerworks/cn/linux/l-gas-nasm.html

程序功能:接受用户名作为输入,并在终端返回一句问候语

一、nasm

myhello.asm

section .data

   prompt_str  db   'Enter your name: '

; $ is the location counter
   STR_SIZE  equ  $ - prompt_str

   greet_str  db  'Hello '


   GSTR_SIZE  equ  $ - greet_str


section .bss

; Reserve 32 bytes of memory
   buff  resb  32

; A macro with two parameters
; Implements the write system call
   %macro write 2 
      mov   eax, 4
      mov   ebx, 1
      mov   ecx, %1
      mov   edx, %2
      int   80h
   %endmacro


; Implements the read system call
   %macro read 2
      mov   eax, 3
      mov   ebx, 0
      mov   ecx, %1
      mov   edx, %2
      int   80h
   %endmacro


section .text

   global _start

   _start:
      write prompt_str, STR_SIZE
      read  buff, 32

; Read returns the length in eax
      push  eax

; Print the hello text
      write greet_str, GSTR_SIZE

      pop   edx

; edx  = length returned by read
      write buff, edx

   _exit:
      mov   eax, 1
      mov   ebx, 0
      int   80h

汇编、链接、运行

$ nasm -f elf myhello.asm 

$ ld -m elf_i386 -o myhello myhello.o

$ ./myhello 

Enter Your Name: wxw

Hello wxw

二、gas(as)

myhello.s

.section .data

   prompt_str:
      .ascii "Enter Your Name: "
   pstr_end:
      .set STR_SIZE, pstr_end - prompt_str

   greet_str:
      .ascii "Hello "

   gstr_end:
      .set GSTR_SIZE, gstr_end - greet_str

.section .bss

// Reserve 32 bytes of memory
   .lcomm  buff, 32

// A macro with two parameters
//  implements the write system call
   .macro write str, str_size 
      movl  $4, %eax
      movl  $1, %ebx
      movl  \str, %ecx
      movl  \str_size, %edx
      int   $0x80
   .endm


// Implements the read system call
   .macro read buff, buff_size
      movl  $3, %eax
      movl  $0, %ebx
      movl  \buff, %ecx
      movl  \buff_size, %edx
      int   $0x80
   .endm


.section .text

   .globl _start

   _start:
      write $prompt_str, $STR_SIZE
      read  $buff, $32

// Read returns the length in eax
      pushl %eax

// Print the hello text
      write $greet_str, $GSTR_SIZE

      popl  %edx

// edx = length returned by read
   write $buff, %edx

   _exit:
      movl  $1, %eax
      movl  $0, %ebx
      int   $0x80

$ as --32 -o myhello.o myhello.s

$ ld -m elf_i386 -o myhello myhello.o

$ ./myhello 

Enter Your Name: wxw

Hello wxw

转载于:https://my.oschina.net/u/2245781/blog/710010

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值