global variables are variables that can be accessed and use by ANY function in a program. local variables are variables that can be accessed ONLY by the function in which they are defined. both are declared similarly in C, but look completely different in assembly
GLOBAL VARIABLES
EXAMPLE 1:
EXAMPLE 2:
the global variables are referenced by memory addresses
#C CODE SNIPPET
//these global declarations are stored in memory
int x = 1;
int y = 2;
void main()
{
x = x + y;
printf("total = %d\n", x);
}
#ASSEMBLY CODE SNIPPET
...
00401003 mov eax, dword_40CF60 ;dword_40CF60 represents x
00401008 add eax, dword_40C000 ;dword_40C000 represents y
0040100E mov dword_40CF60, eax (1) ;move the result of x + y into the memory address represented by x
00401013 mov ecx, dword_40CF60 ;move the result of x + y from memory to the ecx register
00401019 push ecx ;push the result into the stack
0040101A push offset aTotalD ;"total = %d\n"
0040101F call printf
* x is signified by "dword_40CF60" which is a memory location
- x is changed in memory when eax is moved into dword_40CF60 at marker (1)
- all subsequent functions that utilize this variable will be impacted
LOCAL VARIABLES
the local variables are referenced by the stack addresses...not the use of square brackets.
#C CODE SNIPPET
void main()
{
int x = 1;
int y = 2;
x = x + y;
printf("total = %d\n", x);
}
#ASSEMBLY CODE SNIPPET: WITHOUT IDA PRO LABELING
...
00401006 mov dword ptr [ebp-4], 1 ;ebp-4 represents x & is in the stack at a constant offset relative to ebp
0040100D mov dword prt [ebp-8], 2 ;ebp-8 represents y & is in the stack at a constant offset relative to ebp
00401014 mov eax, [ebp-4] ;move x from stack to eax
00401017 add eax, [ebp-8] ;store the result of x + y into eax
0040101A mov [ebp-4], eax ;store the result of x + y into x
0040101D mov ecx, [ebp-4] ;store the result of x + y into ecx
00401020 push ecx ;push the result into the stack
00401021 push offset aTotalD ;"total = %d\n"
00401026 call printf
* the memory location [ebp-4] is used consistently throughout this function
to reference the local variable x.
- this tells devs that ebp-4 is a stack-based local variable that is referenced
only in the function in which it is defined
#C CODE SNIPPET
void main()
{
int x = 1;
int y = 2;
x = x + y;
printf("total = %d\n", x);
}
#ASSEMBLY CODE SNIPPET: WITH IDA PRO LABELING
00401006 mov [ebp+var_4], 1 ;x = 1
0040100D mov [ebp+var_8], 2 ;y = 2
00401014 mov eax, [ebp+var_4] ;move x from stack to eax
00401017 add eax, [ebp+var_8] ;store the result of x + y into eax
0040101A mov [ebp+var_4], eax ;store the result of x + y into x
0040101D mov ecx, [ebp+var_4] ;store the result of x + y into ecx
00401020 push ecx ;push result into the stack
00401021 push offset aTotalD ;"total = %d\n"
00401026 call printf
* the dummy name var_4 is a label implemented by IDA Pro Disassembler
- dummy names can be renamed to meaningful names that reflect their function