70 likes | 169 Views
ICS51 Introductory Computer Organization. Another Function Call Example and Logical Operations. The caller should. • Before calling a procedure: • pass parameters to the procedure: push to the stack in reverse order ( the last parameter is pushed first )
E N D
ICS51Introductory Computer Organization Another Function Call Example and Logical Operations
The caller should • Before calling a procedure: • pass parameters to the procedure: push to the stack in reverse order(the last parameter is pushed first) • execute call (to perform the procedure call) • After the procedure returns: • pop parameters from the stack (to restore the stack to its state before call was performed) • the return value is in EAX
The callee should • At the beginning of procedure: • access passed parameters using ESP • When the procedure is done: •the return value should be placed in EAX • execute ret instruction (return to the caller)
Another example • Save registers used inside the function on the stack then restore them after • Accessing parameters: To access the a location on the stack, use an instruction likemov REG, dword ptr[ESP+OFFSET] • Passing parameters using the stack: • Pushed on the stack from right to left • The return address of the procedure is also on the stack!! • The “ret” instruction • Return value in the “eax” register
void main(void) { int arr[] = {0,1,2,3,4}; int sum = firstpass(arr,5); printf(" The sum is = %d\n",sum); } __declspec(naked) int firstpass (int *arr, int len){ __asm{ /* Save the registers that may be modified by the called function*/ push ecx push edx /* Get parameters from the stack */ mov ecx, dword ptr[esp + 12] // load the arr parameter from the stack mov edx, dword ptr[esp + 16] // load the len parameter from the stack /* put the parameters on the stack for the add2nums function */ push edx // edx contains length push ecx // ecx contains array call add2nums /* pop the parameters of the stack after the call – to restore the stack*/ pop ecx pop edx /* restore the saved registers from the stack*/ pop edx pop ecx ret } }
__declspec(naked) int add2nums(int *array, int length) { __asm { /* Save the registers used in this function to the stack Do not save eax ! */ push edi xor eax,eax xor edi,edi /* this accesses the "array" parameter on the stack */ mov ebx, dword ptr[esp + 8] /* load the "length" parameter from the stack */ mov edx, dword ptr[esp + 12] loop1: cmp edx,edi je all_done /* copies i-th element or an array */ mov ecx, dword ptr[ebx+4*edi] /* the value returned by this function is put in eax */ add eax,ecx inc edi jmp loop1 all_done: /* restore the saved registers from the stack */ pop edi ret } }
Logical Operations • Get a bit • Using AND/OR • Count number of ones • Using DIV • Using AND and SHR • Be creative!