Поток функции сборки
Вопрос
Я читаю «программирование с нуля», если вы не знаете, что это за книга, вы все равно можете мне помочь.
В этой книге (Глава 4) Есть две вещи, которые я не понимаю:
- какие
movl %ebx, -4(%ebp) #store current result
за. - А что означает «текущий результат»
В помеченном разделе в коде ниже есть:
movl 8(%ebp), %ebx
что означает сохранение 8(%ebp)
к %ebx
, но причина, по которой я не понимаю, в том, что программист хочет 8(%ebp)
чтобы спасти до -4(%ebp)
, почему следует 8(%ebp)
пройти через %ebx
? Является "movl 8(%ebp), -4(%ebp)
"Аквард? Или есть опечатка в movl 8(%ebp), %ebx #put first argument in %eax
? (Я думаю %ebx
должно быть %eax
или наоборот)
#PURPOSE: Program to illustrate how functions work
# This program will compute the value of
# 2^3 + 5^2
#Everything in the main program is stored in registers,
#so the data section doesn’t have anything.
.section .data
.section .text
.globl _start
_start:
pushl $3 #push second argument
pushl $2 #push first argument
call power #call the function
addl $8, %esp #move the stack pointer back
pushl %eax #save the first answer before
#calling the next function
pushl $2 #push second argument
pushl $5 #push first argument
call power #call the function
addl $8, %esp #move the stack pointer back
popl %ebx #The second answer is already
#in %eax. We saved the
#first answer onto the stack,
#so now we can just pop it
#out into %ebx
addl %eax, %ebx #add them together
#the result is in %ebx
movl $1, %eax #exit (%ebx is returned)
int $0x80
#PURPOSE: This function is used to compute
# the value of a number raised to
# a power.
#INPUT: First argument - the base number
# Second argument - the power to
# raise it to
#
#OUTPUT: Will give the result as a return value
#
#NOTES: The power must be 1 or greater
#
#VARIABLES:
# %ebx - holds the base number
# %ecx - holds the power
#
# -4(%ebp) - holds the current result
#
# %eax is used for temporary storage
#
.type power, @function
power:
pushl %ebp #save old base pointer
movl %esp, %ebp #make stack pointer the base pointer
subl $4, %esp #get room for our local storage
##########################################
movl 8(%ebp), %ebx #put first argument in %eax
movl 12(%ebp), %ecx #put second argument in %ecx
movl %ebx, -4(%ebp) #store current result
##########################################
power_loop_start:
cmpl $1, %ecx #if the power is 1, we are done
je end_power
movl -4(%ebp), %eax #move the current result into %eax
imull %ebx, %eax #multiply the current result by
#the base number
movl %eax, -4(%ebp) #store the current result
decl %ecx #decrease the power
jmp power_loop_start #run for the next power
end_power:
movl -4(%ebp), %eax #return value goes in %eax
movl %ebp, %esp #restore the stack pointer
popl %ebp #restore the base pointer
ret
Решение
Я верю, что это:
movl 8(%ebp), %ebx #put first argument in %eax
была опечатка, и это действительно должно быть:
movl 8(%ebp), %ebx #put first argument in %ebx
И если вы заметили, позже код верен:
movl %ebx, -4(%ebp) #store current result
В конце концов, автор мог бы использовать %eax
Для этой операции (вместо %ebx
), нет никаких причин, по которым он не должен, поскольку это вообще не изменит программу.
Но комментарий может быть намного яснее, и я считаю, что это также опечатка. На данный момент было бы лучше, если бы он сказал: #storing 1st argument on the local stack frame
.
метка power_loop_start использует эту переменную и временно хранит ее в %eax
Для быстрой работы, а затем поместите его в то же место в стеке для следующего цикла:
movl %eax, -4(%ebp) #store the current result
decl %ecx #decrease the power
jmp power_loop_start #run for the next power
Другие советы
Многие сборочные выборы принимают только один операнд памяти (либо источник, или пункт назначения). Это, вероятно, объясняет, почему переход от памяти к памяти осуществляется через %EBX.
В качестве Грег Намеченный, x86, как и большинство основных архитектур, не имеет инструкции, которая копирует данные из памяти в память [1]. Таким образом, вы должны копировать данные, используя отдельный нагрузка а также хранить. Анкет Сначала вы загружаете данные из исходной памяти в регистр, а затем сохраняете данные из этого регистра в память назначения. Это все, что здесь происходит.
1] Я знаю, я знаю, но давайте уйдем rep movs
Из этого и сохраняйте вещи простыми.