Assembly Language for Beginners

(nextflipdebug2) #1

1.12 Pointers.


ptr_to_struct = dword ptr 4
a = dword ptr 8


mov edx, [esp+a]
mov eax, [esp+ptr_to_struct]
lea ecx, [edx+1]
mov [eax], ecx
lea ecx, [edx+2]
add edx, 3
mov [eax+4], ecx
mov [eax+8], edx
retn
_get_some_values endp


As we see, the function is just filling the structure’s fields allocated by the caller function, as if a pointer
to the structure has been passed. So there are no performance drawbacks.


1.12 Pointers


1.12.1 Swap input values


This will do the job:


#include <memory.h>
#include <stdio.h>


void swap_bytes (unsigned char first, unsigned char second)
{
unsigned char tmp1;
unsigned char tmp2;


tmp1=*first;
tmp2=*second;

first=tmp2;
second=tmp1;
};


int main()
{
// copy string into heap, so we will be able to modify it
char *s=strdup("string");


// swap 2nd and 3rd characters
swap_bytes (s+1, s+2);

printf ("%s\n", s);
};


As we can see, bytes are loaded into lower 8-bit parts ofECXandEBXusingMOVZX(so higher parts of these
registers will be cleared) and then bytes are written back swapped.


Listing 1.99: Optimizing GCC 5.4

swap_bytes:
push ebx
mov edx, DWORD PTR [esp+8]
mov eax, DWORD PTR [esp+12]
movzx ecx, BYTE PTR [edx]
movzx ebx, BYTE PTR [eax]
mov BYTE PTR [edx], bl
mov BYTE PTR [eax], cl
pop ebx
ret


Addresses of both bytes are taken from arguments and through execution of the function are located in
EDXandEAX.

Free download pdf