Linux下汇编学习-2

这个程序是在一组数据中查找出最大值,代码如下:
#PURPOSE:		This program finds the maximum number of a
#				set of data items.
#
#VARIABLIES:	The registers have the following uses:
#
# %edi - Holds the index of the data item being examined
# %ebx - Largest data item found
# %eax - Current data item
#
# The following memory locations are used:
#
# data_items - contains the item data. A 0 is used
#			to terminate the data
#

.section .data

data_items:							#These are the data items
	.long 3,67,34,222,45,75,54,34,44,33,22,11,66,0

.section .text

.globl _start
_start:
	movl $0, %edi					# move 0 into the index register
	movl data_items(,%edi,4), %eax	# load the first byte of data
	movl %eax, %ebx					# since this is the first item, %eax is
									# the biggest

start_loop:							# start loop
	cmpl $0, %eax					# check to see if we've hit the end
	je loop_exit
	incl %edi						# load next value
	movl data_items(,%edi,4), %eax
	cmpl %ebx, %eax					# compare values
	jle start_loop					# jump to loop beginning if the new
									# one isn't bigger
	movl %eax, %ebx					# move the value as the largest
	jmp start_loop					# jump to loop beginning

loop_exit:
	# %ebx is startus code for the exit system call
	# and it already has the maximum number
	movl $1, %eax					# 1 is the exit() syscall
	int $0x80

来分析这个程序
先看数据段中,我们有个符号data_items,然后使用.long命令去定义了一组数据,同c语言一样,我们可以理解这就是数据类型,类似的数据类型还有.byte, .short, .int, .float, .double, .ascii等。然后给edi寄存器赋值0,同时我们通过这样一条语句movl data_items(, %edi, 4), %eax,这个什么意思呢,表示将数据列表中的第一个值3赋给eax寄存器。
接下来我们定义了一个符号start_loop:,然后做了一个判断,判断eax寄存器值是否为0
cmpl $0, %eax
je loop_exit
我们知道cmpl指令是将两个数做减法操作,但不保存最终的结果,只是对标志寄存器eflags有影响,如果eax寄存器值等于0,那么跳转到loop_exit符号处,类似的跳转指令还有jg, jge, jl, jle, jmp等。然后使用incl指令对edi寄存器值加1操作,获取数据列表中数据到寄存器eax中,然后比较eax寄存器和ebx寄存器中值大小,然后不断循环。
总结出这个程序的思路,先假设第一个数为最大值并保存到ebx寄存器中,然后取出一个数同这个数比较,如果大于,则将这个数作为最大数,并保存到ebx寄存器中,这样不断循环,直到最后一个数。

你可能感兴趣的:(汇编)