Linux:組合語言(使用GNU assembler與 ld)

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

底下幾個範例是給了解CPU register 與懂一點組語的人所看的。

範例一:輸出訊息。
//----------------------------------------------------------------
// first.s: Output "Welcome to Assembly World."
//
// compile using: $ as first.s -o first.o
// link using: $ ld first.o -o first
// execute using: $ ./first
//
//----------------------------------------------------------------
.section .data
msg: .string "Welcome to Assembly World.\n" # the output message
len = . - msg # the length of the message
.section .text
_start: movl $4, %eax # system-call number for sys_write
movl $1, %ebx # device-file id-number for stdout
movl $msg, %ecx # address of the message string
movl $len, %edx # length of the message string
int $0x80 # trap-instruction for system-call
movl $1, %eax # system-call number for sys_exit
movl $0, %ebx # value for the exit-code
int $0x80 # trap-instruction for system-call
.globl _start # makes entry-point visible (can omit this)
view raw first.s hosted with ❤ by GitHub
範例二:輸出訊息(ASCII code方式)。
//----------------------------------------------------------------
// Holan.s: print the 'Holan' in ascii code
//
// compile using: $ as Holan.s -o Holan.o
// link using: $ ld Holan.o -o Holan
// execute using: $ ./Holan
//
//----------------------------------------------------------------
.text # this section is program
.global _start # entry point
_start:
# write our string to stdout
movl $len,%edx # third argument: message length
movl $msg,%ecx # second: pointer to message
movl $1,%ebx # Holan: file handle (stdout)
movl $4,%eax # system call number (sys_write)
int $0x80 # call kernel
# and exit
movl $0,%ebx # Holan argument: exit code
movl $1,%eax # system call number (sys_exit)
int $0x80 # call kernel
.data # this section is data
msg:
.byte 72,111,108,97,110,10
len = . - msg # the length of the message
view raw Holan.s hosted with ❤ by GitHub
範例三:加法。
//----------------------------------------------------------------
// sum.s:
//
// compile using: $ as sum.s -o sum.o
// link using: $ ld sum.o -o sum
// execute using: $ ./sum
//
//----------------------------------------------------------------
.text # this section is program
.global _start # entry point
_start:
movl $1, %eax # put 1 into eax
addl $8, %eax # add 8 into eax
addl $48, %eax # convert digit to ASCII
movl $msg, %ecx # put address of msg into ecx
movb %al, (%ecx) # store byte in al in location ecx
# points to
# write our string to stdout
movl $len,%edx # third argument: message length
movl $msg,%ecx # second: pointer to message
movl $1,%ebx # sum: file handle (stdout)
movl $4,%eax # system call number (sys_write)
int $0x80 # call kernel
# and exit
movl $0,%ebx # sum argument: exit code
movl $1,%eax # system call number (sys_exit)
int $0x80 # call kernel
.data # this section is data
msg:
.byte 72,10
len = . - msg
view raw sum.s hosted with ❤ by GitHub

Reference:

沒有留言: