您的位置:首页 > 其它

Hello World---MIPS汇编例程

2012-08-08 09:24 417 查看
# hello.S by Spencer T. Parkin

# This is my first MIPS-RISC assembly program!

# To compile this program type:

# > gcc -o hello hello.S -non_shared

# This program compiles without errors or warnings

# on a PlayStation2 MIPS R5900 (EE Core).

# EE stands for Emotion Engine...lame!

# The -non_shared option tells gcc that we`re

# not interrested in compiling relocatable code.

# If we were, we would need to follow the PIC-

# ABI calling conventions and other protocols.

#include <asm/regdef.h> // ...for human readable register names

#include <asm/unistd.h> // ...for system serivices

.rdata

# begin read-only data segment

.align 2

# because of the way memory is built

hello: .asciz "Hello, world!\n"

# a null terminated string

.align 4

# because of the way memory is built

length: .word . - hello

# length = IC - (hello-addr)

.text

# begin code segment

.globl main

# for gcc/ld linking

.ent main

# for gdb debugging info.

main:

# We must specify -non_shared to gcc or we`ll need these 3 lines that fallow.

# .set noreorder # disable instruction reordering

# .cpload t9 # PIC ABI crap (function prologue)

# .set reorder # re-enable instruction reordering

move a0,$0

# load stdout fd

la a1,hello

# load string address

lw a2,length

# load string length

li v0,__NR_write

# specify system write service

syscall

# call the kernel (write string)

li v0,0

# load return code

j ra

# return to caller

.end main

# for dgb debugging info.

# That`s all folks!

我把上面的程序翻译了一下,供大家参考。

# hello.S 作者:Spencer T. Parkin(注意!这里是.S)

# 这是我的第一个MIPS-RISC汇编语言程序!

# 编译时,键入:

# > gcc -o hello hello.S -non_shared

# 本程序在一台PS2游戏机(CPU为MIPS R5900 EE Core)上正常编译,

# 没有警告和出错信息。

# EE 即Emotion Engine(激情引擎)...这也缩写为EE? 晕!

# -non_shared选项表示生成静态连接代码

# 如果需要动态连接的可重定位代码,

# 则需要使用有关的系统(PIC-ABI)约定

#include <asm/regdef.h> // ...在指令中使用寄存器软件名,

# 便于阅读和识别这些寄存器

#include <asm/unistd.h> // ...调用系统功能时,使用符号名,

# 而不是数字编号。

# 上面的两行include,是让cpp对源程序做处理,

# cpp主要是完成一些替换工作,此时是把符号替换为数字。

.rdata # 使用rdata定义一个只读的数据段

.align 2 # 访存按16位半字的边界对齐

hello: .asciz "Hello, world!\n" # hello为0字符结尾的字符串。

.align 4 # 访存按32位字边界对齐

length: .word . - hello # length = IC - (hello-addr)

# 在length中保存字符串的长度

.text # 代码段开始

.globl main # 允许外部调用main,main为全局可见的符号名,

# 同时main也是gcc连接时的主程序入口

.ent main # 与排错(debugging)有关(表示main之开始)

main: # 用-non_shared编译时(静态连接),以下的三行代码注释掉,动态连接则需要去掉注释符“#”,让其在程序里有效。

# .set noreorder # 关闭as指令重排功能

# .cpload t9 # 位置无关代码的函数开头的重定位约定

# .set reorder # 打开as指令重排功能

move a0,$0 # 指定输出的文件为stdout

la a1,hello # 设定字符串地址

lw a2,length # 设置字符串长度

li v0,__NR_write # 指定__NR_write系统调用

syscall # 发出系统调用 (输出一个字符串)

li v0,0 # 设置返回码

j ra # 返回到调用者

.end main # 与排错(debugging)有关(表示main之结束)

# 诸位,程序到此为止!

附加:

Q:汇编语言的源代码文件,有的用“.s”做后缀,有的用“.S”做后缀,这两者有何区别?

A:以.S作后缀的,是原始的汇编语言源文件,经过预编译,就生成了以.s作后缀的文件。

file.s

Assembler code.

file.S

Assembler code which must be preprocessed.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: