Assume we have a C program that has a function that accepts 4 integer values and
ID: 3702659 • Letter: A
Question
Assume we have a C program that has a function that accepts 4 integer values and finds the max of these values and return max. Write the same procedure in assembly language. The main code of the assembly language mustpass the 4 values using the stack and then call the procedure max. You should have a local variable in procedure max for finding the maximum of the 4 numbers. Use ebp register in the procedure and show the cut and paste of memory to show the array. Cut and paste the stack before the function call and after the function call and explain all the values such as the return address and passed values.
Explanation / Answer
Here is the assembly code that finds the maximum value in an array using function call
Assembly Code
.LC0:
.string "Enter the size of the array maximum up to 30: "
.LC1:
.string "%d"
.LC2:
.string "Enter the %d integer numbers: "
.LC3:
.string " The largest element is: %d "
main:
push rbp
mov rbp, rsp
sub rsp, 144
mov edi, OFFSET FLAT:.LC0
mov eax, 0
call printf
lea rax, [rbp-132]
mov rsi, rax
mov edi, OFFSET FLAT:.LC1
mov eax, 0
call scanf
mov eax, DWORD PTR [rbp-132]
mov esi, eax
mov edi, OFFSET FLAT:.LC2
mov eax, 0
call printf
mov DWORD PTR [rbp-4], 0
.L3:
mov eax, DWORD PTR [rbp-132]
cmp DWORD PTR [rbp-4], eax
jge .L2
lea rax, [rbp-128]
mov edx, DWORD PTR [rbp-4]
movsx rdx, edx
sal rdx, 2
add rax, rdx
mov rsi, rax
mov edi, OFFSET FLAT:.LC1
mov eax, 0
call scanf
add DWORD PTR [rbp-4], 1
jmp .L3
.L2:
mov edx, DWORD PTR [rbp-132]
lea rax, [rbp-128]
mov esi, edx
mov rdi, rax
call max(int*, int)
mov DWORD PTR [rbp-8], eax
mov eax, DWORD PTR [rbp-8]
mov esi, eax
mov edi, OFFSET FLAT:.LC3
mov eax, 0
call printf
mov eax, 0
leave
ret
max(int*, int):
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-24], rdi
mov DWORD PTR [rbp-28], esi
mov rax, QWORD PTR [rbp-24]
mov eax, DWORD PTR [rax]
mov DWORD PTR [rbp-8], eax
mov DWORD PTR [rbp-4], 1
.L8:
mov eax, DWORD PTR [rbp-4]
cmp eax, DWORD PTR [rbp-28]
jge .L6
mov eax, DWORD PTR [rbp-4]
cdqe
lea rdx, [0+rax*4]
mov rax, QWORD PTR [rbp-24]
add rax, rdx
mov edx, DWORD PTR [rax]
mov eax, DWORD PTR [rbp-8]
cmp edx, eax
jle .L7
mov eax, DWORD PTR [rbp-4]
cdqe
lea rdx, [0+rax*4]
mov rax, QWORD PTR [rbp-24]
add rax, rdx
mov eax, DWORD PTR [rax]
mov DWORD PTR [rbp-8], eax
.L7:
add DWORD PTR [rbp-4], 1
jmp .L8
.L6:
mov eax, DWORD PTR [rbp-8]
pop rbp
ret