zoukankan      html  css  js  c++  java
  • X86平台下用汇编写"HelloWorld"

    首先需要安装一个汇编器,我用的是Nasm,这个汇编器在Linux下安装还是很简单的。

    Nasm下载地址http://www.nasm.us/pub/nasm/releasebuilds/

    在下载之后对其进行解压,然后进入到其目录下,会发现有configure文件,接下来相信对于熟悉Linux的同学就知道该怎么办了。

    输入./configure然会待其执行完成后,会发现在目录下生成了一个Makefile文件,这是输入make命令,就可以完成对Nasm的编译了

    然后进入root,输入make install对Nasm进行安装即可了。然后如果你的机器上没有gcc的话可以安装下gcc这里自己去搜索引擎找就行了,因为我这里已经安装了gcc所以这里不再多说。

    接下来就可以编写helloworld的汇编代码了,我这里参考的是维基百科上的代码示例

      section .data
         msg     db      'Hello, world!',0xA
         len     equ     $-msg
     
         section .text
     global  _start
     _start:
             mov     edx,len
             mov     ecx,msg
             mov     ebx,1
             mov     eax,4
             int     0x80
     
             mov     ebx,0
             mov     eax,1
             int     0x80

    然后将编辑的文件保存,起始后缀名没什么关系,后缀名在Linux下只是给人看的罢了,保存之后,输入nasm -f elf32 文件名,然后会发现在该命令执行完成后

    生成了一个 文件名.o的文件,然后输入ld 文件名.o -o 文件名  执行完成后,就生成了我们平时使用的可以执行文件。

    此时输入./文件名 就会出现Hello World了。

    自己在看了下汇编的东西后,自己用AT&T的汇编格式写出了一个Hello World,虽然很简单,但是对于一直想自学下汇编,但是一直也没学的我来说,还是觉得自己能独立写出一个小小的

    汇编程序感到很兴奋。

    .equ          SYS_WRITE,      4
    .equ          SYS_EXIT,         1
    .equ          SYSCALL,           0x80
    .equ          STDOUT,            1
    .equ          STR_LEN           12
    
    .section       .data
    str:
         .ascii     "hello world
    "
    
    .section       .text
    
    .globl      _start
    
    _start:
        movl   %esp, %ebp
        subl     $4,  %esp
        movl   $str,  -4(%ebp)
        movl   $SYS_WRITE, %eax
       movl   $STDOUT,  %ebx
       movl   -4(%ebp),  %ecx
        movl  $STR_LEN, %edx
        int       $SYSCALL
    
        movl   $SYS_EXIT,  %eax
       movl    $0,  %ebx
        int      $SYSCALL 

     调用动态链接库实现HelloWorld

    .section   .data
    str:
        ,ascii   "hello world
    "
    
    .section   .text
    .globl   _start
    
    _start:
        pushl  $str
        call  printf
    
         pushl $0
        call  exit

    这样,该程序在汇编时仍然和之前一样使用 as helloworld.s -o helloworld.o,但是在进行链接时却需要做一些改变

    应该使用如下的方式进行: ld  -dynamic-linker /lib/ld-linux.so.2 -o  helloworld  helloworld.o  -lc这样编译就可以完成了。

  • 相关阅读:
    【小白建站笔记】从购买域名及服务器到备案成功:以阿里云为例
    jarvisoj-Evil Exe
    jarvisoj-软件密码破解-2(CFF_100_1)
    Jarvis OJ-superexpress
    JarvisOJ-[xman2019]xfz
    csictf-Esrever
    分解质因数
    矩阵乘法
    python获取一组数个位数之和
    python计算字母出现次数
  • 原文地址:https://www.cnblogs.com/coder-zhang/p/3838277.html
Copyright © 2011-2022 走看看