I've been reading the book 'Programming from the Ground Up' to learn assembly programming in Linux. I'm having trouble solving one of the exercises at the end of chapter 3. The exercise says to modify the following program to use the address at the end of the set of data to terminate the loop. This is just a simple program to find the maximum number in a set of data, it currently just uses the number zero to mark the end of the data.
#PURPOSE: This program finds the maximum number of a
# set of data items.
#
#VARIABLES: 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:
.long 3, 67, 34, 14, 45, 75, 54, 187, 44, 87, 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 # The biggest
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 the beginning if new value
# Isn't larger
movl %eax, %ebx # Move the value as the largest
jmp start_loop # Jump to the beginning of loop
loop_exit:
# %ebx is the status code for the exit system call
# and it contains the maximum number
movl $1, %eax # 1 is the exit() system call
int $0x80
I know that I could just hard code the length of the list of data, or I could store it in the first byte of data, but the exercise is asking to terminate the loop by using the address of the last element. The book mentions using a symbol to mark the end. I think my problem is that I just don't understand how to get the address. If I knew how to get it I could just store it in a register. Any help is appreciated.
With some minor mods for Mac OSX...
.data
data_items:
.long 3, 67, 34, 14, 45, 75, 54, 187, 44, 87, 22, 11, 66, 0
data_end:
.text
.globl start
start:
movl $0, %edi # Move 0 into the index register
movl data_items (, %edi, 4), %eax # Load the first data value
movl %eax, %ebx # The biggest
leal data_end, %ecx # Load and save ending address
start_loop:
leal data_items(, %edi, 4), %eax # Get address of next value
cmpl %eax, %ecx # Check to see if we've hit the end
je loop_exit
incl %edi # Increment index
movl (%eax), %eax # Load value
cmpl %ebx, %eax # Compare values
jle start_loop # Jump to the beginning if new value
# Isn't larger
movl %eax, %ebx # Move the value as the largest
jmp start_loop # Jump to the beginning of loop
loop_exit:
movl $1, %eax # 1 is the exit() system call
pushl %ebx
pushl $0
int $0x80
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With