# X86 Disassembly/Calling Conventions

## Calling Conventions

**Calling conventions** are a standardized method for functions to be
implemented and called by the machine. A calling convention specifies
the method that a compiler sets up to access a subroutine. In theory,
code from any compiler can be interfaced together, so long as the
functions all have the same calling conventions. In practice however,
this is not always the case.

Calling conventions specify how arguments are passed to a function, how
return values are passed back out of a function, how the function is
called, and how the function manages the stack and its stack frame. In
short, the calling convention specifies how a function call in C or C++
is converted into assembly language. Needless to say, there are many
ways for this translation to occur, which is why it\'s so important to
specify certain standard methods. If these standard conventions did not
exist, it would be nearly impossible for programs created using
different compilers to communicate and interact with one another.

There are three major calling conventions that are used with the C
language on 32-bit x86 processors: STDCALL, CDECL, and FASTCALL. In
addition, there is another calling convention typically used with C++:
THISCALL.[^1] There are other calling conventions as well, including
PASCAL and FORTRAN conventions, among others.

Other processors, such as AMD64 processors (also called x86-64
processors), each have their own calling convention.[^2][^3]

## Notes on Terminology

There are a few terms that we are going to be using which are mostly
common sense, but which are worthy of stating directly:

Passing arguments : \"passing arguments\" is a way of saying that the calling function is writing data in the place where the called function will look for them. Arguments are passed before the *call* instruction is executed.

```{=html}
<!-- -->
```

Right-to-Left and Left-to-Right : These describe the manner in which arguments are passed to the subroutine, in terms of the High-level code. For instance, the following C function call:

``` C
MyFunction1(a, b);
```

will generate the following code if passed Left-to-Right:

``` asm
push a
push b
call _MyFunction
```

and will generate the following code if passed Right-to-Left:

``` asm
push b
push a
call _MyFunction
```

Return value : Some functions return a value, and that value must be received reliably by the function\'s caller. The called function places its return value in a place where the calling function can get it when execution returns. The called function stores the return value before executing the *ret* instruction.

```{=html}
<!-- -->
```

Cleaning the stack : When arguments are pushed onto the stack, eventually they must be popped back off again. Whichever function, the caller or the callee, is responsible for cleaning the stack must reset the stack pointer to eliminate the passed arguments.

```{=html}
<!-- -->
```

Calling function (the caller): The \"parent\" function that calls the subroutine. Execution resumes in the calling function directly after the subroutine call, unless the program terminates inside the subroutine.

```{=html}
<!-- -->
```

Called function (the callee): The \"child\" function that gets called by the \"parent.\"

```{=html}
<!-- -->
```

Name Decoration : When C code is translated to assembly code, the compiler will often \"decorate\" the function name by adding extra information that the linker will use to find and link to the correct functions. For most calling conventions, the decoration is very simple (often only an extra symbol or two to denote the calling convention), but in some extreme cases (notably C++ \"thiscall\" convention), the names are \"mangled\" severely.

```{=html}
<!-- -->
```

Entry sequence (the function prologue): a few instructions at the beginning of a function, which prepare the stack and registers for use within the function.

```{=html}
<!-- -->
```

Exit sequence (the function epilogue): a few instructions at the end of a function, which restore the stack and registers to the state expected by the caller, and return to the caller. Some calling conventions clean the stack in the exit sequence.

```{=html}
<!-- -->
```

Call sequence: a few instructions in the middle of a function (the caller) which pass the arguments and call the called function. After the called function has returned, some calling conventions have one more instruction in the call sequence to clean the stack.

## Standard C Calling Conventions

The C language, by default, uses the CDECL calling convention, but most
compilers allow the programmer to specify another convention via a
specifier keyword. These keywords **are not** part of the ISO-ANSI C
standard, so you should always check with your compiler documentation
about implementation specifics.

If a calling convention other than CDECL is to be used, or if CDECL is
not the default for your compiler, and you want to manually use it, you
must specify the calling convention keyword in the function declaration
itself, and in any prototypes for the function. This is important
because both the calling function and the called function need to know
the calling convention.

### CDECL

In the CDECL calling convention the following holds:

-   Arguments are passed on the stack in Right-to-Left order, and return
    values are passed in eax.
-   The *calling* function cleans the stack. This allows CDECL functions
    to have *variable-length argument lists* (aka variadic functions).
    For this reason the number of arguments is not appended to the name
    of the function by the compiler, and the assembler and the linker
    are therefore unable to determine if an incorrect number of
    arguments is used.

Variadic functions usually have special entry code, generated by the
va_start(), va_arg() C pseudo-functions.

Consider the following C instructions:

``` C
_cdecl int MyFunction1(int a, int b)
{
  return a + b;
}
```

and the following function call:

``` C
 x = MyFunction1(2, 3);
```

These would produce the following assembly listings, respectively:

``` asm
_MyFunction1:
push ebp
mov ebp, esp
mov eax, [ebp + 8]
mov edx, [ebp + 12]
add eax, edx
pop ebp
ret
```

and

``` asm
push 3
push 2
call _MyFunction1
add esp, 8
```

When translated to assembly code, CDECL functions are almost always
prepended with an underscore (that\'s why all previous examples have
used \"\_\" in the assembly code).

### STDCALL

STDCALL, also known as \"WINAPI\" (and a few other names, depending on
where you are reading it) is used almost exclusively by Microsoft as the
standard calling convention for the Win32 API. Since STDCALL is strictly
defined by Microsoft, all compilers that implement it do it the same
way.

-   STDCALL passes arguments right-to-left, and returns the value in
    eax. (The Microsoft documentation erroneously claimed that arguments
    are passed left-to-right, but this is not the case.)
-   The called function cleans the stack, unlike CDECL. This means that
    STDCALL doesn\'t allow variable-length argument lists.

Consider the following C function:

``` C
_stdcall int MyFunction2(int a, int b)
{
   return a + b;
}
```

and the calling instruction:

``` C
 x = MyFunction2(2, 3);
```

These will produce the following respective assembly code fragments:

``` asm
:_MyFunction2@8
push ebp
mov ebp, esp
mov eax, [ebp + 8]
mov edx, [ebp + 12]
add eax, edx
pop ebp
ret 8
```

and

``` asm
push 3
push 2
call _MyFunction2@8
```

There are a few important points to note here:

1.  In the function body, the *ret* instruction has an (optional)
    argument that indicates how many bytes to pop off the stack when the
    function returns.
2.  STDCALL functions are name-decorated with a leading underscore,
    followed by an @, and then the number (in bytes) of arguments passed
    on the stack. This number will always be a multiple of 4, on a
    32-bit aligned machine.

### FASTCALL

The FASTCALL calling convention is not completely standard across all
compilers, so it should be used with caution. In FASTCALL, the first 2
or 3 32-bit (or smaller) arguments are passed in registers, with the
most commonly used registers being edx, eax, and ecx. Additional
arguments, or arguments larger than 4-bytes are passed on the stack,
often in Right-to-Left order (similar to CDECL). The calling function
most frequently is responsible for cleaning the stack, if needed.

Because of the ambiguities, it is recommended that FASTCALL be used only
in situations with 1, 2, or 3 32-bit arguments, where speed is
essential.

The following C function:

``` C
_fastcall int MyFunction3(int a, int b)
{
   return a + b;
}
```

and the following C function call:

``` C
x = MyFunction3(2, 3);
```

Will produce the following assembly code fragments for the called, and
the calling functions, respectively:

``` asm
:@MyFunction3@8
push ebp
mov ebp, esp ;many compilers create a stack frame even if it isn't used
add eax, edx ;a is in eax, b is in edx
pop ebp
ret
```

and

``` asm
;the calling function
mov eax, 2
mov edx, 3
call @MyFunction3@8
```

The name decoration for FASTCALL prepends an @ to the function name, and
follows the function name with \@x, where x is the number (in bytes) of
arguments passed to the function.

Many compilers still produce a stack frame for FASTCALL functions,
especially in situations where the FASTCALL function itself calls
another subroutine. However, if a FASTCALL function doesn\'t need a
stack frame, optimizing compilers are free to omit it.

Commonly gcc and Windows FASTCALL convention pushes parameters one and
two into ecx and edx, respectively, before pushing any remaining
parameters onto the stack. Calling MyFunction3 using this standard would
look like:

``` asm
;the calling function
mov ecx, 2
mov edx, 3
call @MyFunction3@8
```

## C++ Calling Convention

C++ requires that non-static methods of a class be called by an instance
of the class. Therefore it uses its own standard calling convention to
ensure that pointers to the object are passed to the function:
**THISCALL**.

### THISCALL

In THISCALL, the pointer to the class object is passed in ecx, the
arguments are passed Right-to-Left on the stack, and the return value is
passed in eax.

For instance, the following C++ instruction:

``` Cpp
 MyObj.MyMethod(a, b, c);
```

Would form the following asm code:

``` asm
mov ecx, MyObj
push c
push b
push a
call _MyMethod
```

At least, it *would* look like the assembly code above if it weren\'t
for **name mangling**.

### Name Mangling

Because of the complexities inherent in function overloading, C++
functions are heavily name-decorated to the point that people often
refer to the process as \"Name Mangling.\" Unfortunately C++ compilers
are free to do the name-mangling differently since the standard does not
enforce a convention. Additionally, other issues such as exception
handling are also not standardized.

Since every compiler does the name-mangling differently, this book will
not spend too much time discussing the specifics of the algorithm.
Notice that in many cases, it\'s possible to determine which compiler
created the executable by examining the specifics of the name-mangling
format. We will not cover this topic in this much depth in this book,
however.

Here are a few general remarks about THISCALL name-mangled functions:

-   They are recognizable on sight because of their complexity when
    compared to CDECL, FASTCALL, and STDCALL function name decorations
-   They sometimes include the name of that function\'s class.
-   They almost always include the number and type of the arguments, so
    that overloaded functions can be differentiated by the arguments
    passed to it.

Here is an example of a C++ class and function declaration:

``` Cpp
 class MyClass {
  MyFunction(int a) { }
 };
```

And here is the resultant mangled name:

`?MyFunction@MyClass@@QAEHH@Z`

### Extern \"C\"

In a C++ source file, functions placed in an `extern "C"` block are
guaranteed not to be mangled. This is done frequently when libraries are
written in C++, and the functions need to be exported without being
mangled. Even though the program is written in C++ and compiled with a
C++ compiler, some of the functions might therefore not be mangled and
will use one of the ordinary C calling conventions (typically CDECL).

## Note on Name Decorations

We\'ve been discussing name decorations in this chapter, but the fact is
that in pure disassembled code there typically are no names whatsoever,
especially not names with fancy decorations. The assembly stage removes
all these readable identifiers, and replaces them with the binary
locations instead. Function names really only appear in two places:

1.  Listing files produced during compilation
2.  In export tables, if functions are exported

When disassembling raw machine code, there will be no function names and
no name decorations to examine. For this reason, you will need to pay
more attention to the way parameters are passed, the way the stack is
cleaned, and other similar details.

While we haven\'t covered optimizations yet, suffice it to say that
optimizing compilers can even make a mess out of these details.
Functions which are not exported do not necessarily need to maintain
standard interfaces, and if it is determined that a particular function
does not need to follow a standard convention, some of the details will
be optimized away. In these cases, it can be difficult to determine what
calling conventions were used (if any), and it is even difficult to
determine where a function begins and ends. This book cannot account for
all possibilities, so we try to show as much information as possible,
with the knowledge that much of the information provided here will not
be available in a true disassembly situation.

## Further reading

-   x86 Disassembly/Calling Convention
    Examples
-   Embedded Systems/Mixed C and Assembly
    Programming
    describes calling conventions on other CPUs.

[^1]: Josh Lospinoso. \"Common x86 Calling
    Conventions\".

[^2]: \"C to assembly call convention 32bit vs
    64bit\".

[^3]: \"ASM call
    conventions\".


# X86 Disassembly/Calling Convention Examples

## Microsoft C Compiler

Here is a simple function in C:

``` C
 int MyFunction(int x, int y)
 {
    return (x * 2) + (y * 3);
 }
```

Using cl.exe, we are going to generate 3 separate listings for
MyFunction, one with CDECL, one with FASTCALL, and one with STDCALL
calling conventions. On the commandline, there are several switches that
you can use to force the compiler to change the default:

-   `/Gd` : The default calling convention is CDECL
-   `/Gr` : The default calling convention is FASTCALL
-   `/Gz` : The default calling convention is STDCALL

Using these commandline options, here are the listings:

### CDECL

``` C
 int MyFunction(int x, int y)
 {
    return (x * 2) + (y * 3);
 }
```

becomes:

``` {.asm .numberLines}
 PUBLIC _MyFunction
 _TEXT  SEGMENT
 _x$ = 8                        ; size = 4
 _y$ = 12                       ; size = 4
 _MyFunction    PROC NEAR
 ; Line 4
    push  ebp
    mov   ebp, esp
 ; Line 5
    mov   eax, _y$[ebp]
    imul  eax, 3
    mov   ecx, _x$[ebp]
    lea   eax, [eax+ecx*2]
 ; Line 6
    pop   ebp
    ret   0
 _MyFunction    ENDP
 _TEXT  ENDS
 END
```

On entry of a function, ESP points to the return address pushed on the
stack by the `call` instruction (that is, previous contents of EIP). Any
argument in stack of higher address than entry ESP is pushed by caller
before the call is made; in this example, the first argument is at
offset +4 from ESP (EIP is 4 bytes wide), plus 4 more bytes once the EBP
is pushed on the stack. Thus, at line 5, ESP points to the saved frame
pointer EBP, and arguments are located at addresses ESP+8 (x) and ESP+12
(y).

For CDECL, caller pushes arguments into stack in a right to left order.
Because ret 0 is used, it must be the caller who cleans up the stack.

As a point of interest, notice how **lea** is used in this function to
simultaneously perform the multiplication (ecx \* 2), and the addition
of that quantity to eax. Unintuitive instructions like this will be
explored further in the chapter on unintuitive
instructions.

### FASTCALL

``` C
 int MyFunction(int x, int y)
 {
    return (x * 2) + (y * 3);
 }
```

becomes:

``` asm
 PUBLIC @MyFunction@8
 _TEXT  SEGMENT
 _y$ = -8                       ; size = 4
 _x$ = -4                       ; size = 4
 @MyFunction@8 PROC NEAR
 ; _x$ = ecx
 ; _y$ = edx
 ; Line 4
    push   ebp
    mov    ebp, esp
    sub    esp, 8
    mov    _y$[ebp], edx
    mov    _x$[ebp], ecx
 ; Line 5
    mov    eax, _y$[ebp]
    imul   eax, 3
    mov    ecx, _x$[ebp]
    lea    eax, [eax+ecx*2]
 ; Line 6
    mov    esp, ebp
    pop    ebp
    ret    0
 @MyFunction@8 ENDP
 _TEXT  ENDS
 END
```

This function was compiled with optimizations turned off. Here we see
arguments are first saved in stack then fetched from stack, rather than
be used directly. This is because the compiler wants a consistent way to
use all arguments via stack access, not only one compiler does like
that.

There is no argument is accessed with positive offset to entry SP, it
seems caller doesn't pushed in them, thus it can use ret 0. Let's do
further investigation:

``` C
 int FastTest(int x, int y, int z, int a, int b, int c)
 {
     return x * y * z * a * b * c;
 }
```

and the corresponding listing:

``` asm
 PUBLIC @FastTest@24
 _TEXT  SEGMENT
 _y$ = -8                       ; size = 4
 _x$ = -4                       ; size = 4
 _z$ = 8                        ; size = 4
 _a$ = 12                       ; size = 4
 _b$ = 16                       ; size = 4
 _c$ = 20                       ; size = 4
 @FastTest@24 PROC NEAR
 ; _x$ = ecx
 ; _y$ = edx
 ; Line 2
    push    ebp
    mov     ebp, esp
    sub     esp, 8
    mov     _y$[ebp], edx
    mov     _x$[ebp], ecx
 ; Line 3
    mov     eax, _x$[ebp]
    imul    eax, DWORD PTR _y$[ebp]
    imul    eax, DWORD PTR _z$[ebp]
    imul    eax, DWORD PTR _a$[ebp]
    imul    eax, DWORD PTR _b$[ebp]
    imul    eax, DWORD PTR _c$[ebp]
 ; Line 4
    mov     esp, ebp
    pop     ebp
    ret     16                  ; 00000010H
```

Now we have 6 arguments, four are pushed in by caller from right to
left, and last two are passed again in cx/dx, and processed the same way
as previous example. Stack cleanup is done by ret 16, which
corresponding to 4 arguments pushed before call executed.

For FASTCALL, compiler will try to pass arguments in registers, if not
enough caller will pushed them into stack still in an order from right
to left. Stack cleanup is done by callee. It is called FASTCALL because
if arguments can be passed in registers (for 64bit CPU the maximum
number is 6), no stack push/clean up is needed.

The name-decoration scheme of the function: \@MyFunction@n, here n is
stack size needed for all arguments.

### STDCALL

``` C
 int MyFunction(int x, int y)
 {
    return (x * 2) + (y * 3);
 }
```

becomes:

``` asm
 PUBLIC _MyFunction@8
 _TEXT  SEGMENT
 _x$ = 8                        ; size = 4
 _y$ = 12                       ; size = 4
 _MyFunction@8 PROC NEAR
 ; Line 4
    push    ebp
    mov     ebp, esp
 ; Line 5
    mov     eax, _y$[ebp]
    imul    eax, 3
    mov     ecx, _x$[ebp]
    lea     eax, [eax+ecx*2]
 ; Line 6
    pop     ebp
    ret     8
 _MyFunction@8 ENDP
 _TEXT  ENDS
 END
```

The STDCALL listing has only one difference than the CDECL listing that
it uses \"ret 8\" for self clean up of stack. Lets do an example with
more parameters:

``` C
 int STDCALLTest(int x, int y, int z, int a, int b, int c)
 {
    return x * y * z * a * b * c;
 }
```

Let\'s take a look at how this function gets translated into assembly by
cl.exe:

``` asm
 PUBLIC _STDCALLTest@24
 _TEXT  SEGMENT
 _x$ = 8                        ; size = 4
 _y$ = 12                       ; size = 4
 _z$ = 16                       ; size = 4
 _a$ = 20                       ; size = 4
 _b$ = 24                       ; size = 4
 _c$ = 28                       ; size = 4
 _STDCALLTest@24 PROC NEAR
 ; Line 2
    push    ebp
    mov     ebp, esp
 ; Line 3
    mov     eax, _x$[ebp]
    imul    eax, DWORD PTR _y$[ebp]
    imul    eax, DWORD PTR _z$[ebp]
    imul    eax, DWORD PTR _a$[ebp]
    imul    eax, DWORD PTR _b$[ebp]
    imul    eax, DWORD PTR _c$[ebp]
 ; Line 4
    pop     ebp
    ret     24                  ; 00000018H
 _STDCALLTest@24 ENDP
 _TEXT  ENDS
 END
```

Yes the only difference between STDCALL and CDECL is that the former
does stack clean up in callee, the later in caller. This saves a little
bit in X86 due to its \"ret n\".

## GNU C Compiler

We will be using 2 example C functions to demonstrate how GCC implements
calling conventions:

``` C
 int MyFunction1(int x, int y)
 {
    return (x * 2) + (y * 3);
 }
```

and

``` C
 int MyFunction2(int x, int y, int z, int a, int b, int c)
 {
    return x * y * (z + 1) * (a + 2) * (b + 3) * (c + 4);
 }
```

GCC does not have commandline arguments to force the default calling
convention to change from CDECL (for C), so they will be manually
defined in the text with the directives: \_\_cdecl, \_\_fastcall, and
\_\_stdcall.

### CDECL

The first function (MyFunction1) provides the following assembly
listing:

``` asm
 _MyFunction1:
    pushl   %ebp
    movl    %esp, %ebp
    movl    8(%ebp), %eax
    leal    (%eax,%eax), %ecx
    movl    12(%ebp), %edx
    movl    %edx, %eax
    addl    %eax, %eax
    addl    %edx, %eax
    leal    (%eax,%ecx), %eax
    popl    %ebp
    ret
```

First of all, we can see the name-decoration is the same as in cl.exe.
We can also see that the ret instruction doesn\'t have an argument, so
the calling function is cleaning the stack. However, since GCC doesn\'t
provide us with the variable names in the listing, we have to deduce
which parameters are which. After the stack frame is set up, the first
instruction of the function is \"movl 8(%ebp), %eax\". One we remember
(or learn for the first time) that GAS instructions have the general
form:

`instruction src, dest`

We realize that the value at offset +8 from ebp (the last parameter
pushed on the stack) is moved into eax. The leal instruction is a little
more difficult to decipher, especially if we don\'t have any experience
with GAS instructions. The form \"leal(reg1,reg2), dest\" adds the
values in the parenthesis together, and stores the value in *dest*.
Translated into Intel syntax, we get the instruction:

``` asm
 lea ecx, [eax + eax]
```

Which is clearly the same as a multiplication by 2. The first value
accessed must then have been the last value passed, which would seem to
indicate that values are passed right-to-left here. To prove this, we
will look at the next section of the listing:

``` asm
 movl   12(%ebp), %edx
 movl   %edx, %eax
 addl   %eax, %eax
 addl   %edx, %eax
 leal   (%eax,%ecx), %eax
```

the value at offset +12 from ebp is moved into edx. edx is then moved
into eax. eax is then added to itselt (eax \* 2), and then is added back
to edx (edx + eax). remember though that eax = 2 \* edx, so the result
is edx \* 3. This then is clearly the y parameter, which is furthest on
the stack, and was therefore the first pushed. CDECL then on GCC is
implemented by passing arguments on the stack in right-to-left order,
same as cl.exe.

### FASTCALL

``` asm
 .globl @MyFunction1@8
    .def    @MyFunction1@8; .scl    2;  .type   32; .endef
 @MyFunction1@8:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $8, %esp
    movl    %ecx, -4(%ebp)
    movl    %edx, -8(%ebp)
    movl    -4(%ebp), %eax
    leal    (%eax,%eax), %ecx
    movl    -8(%ebp), %edx
    movl    %edx, %eax
    addl    %eax, %eax
    addl    %edx, %eax
    leal    (%eax,%ecx), %eax
    leave
    ret
```

Notice first that the same name decoration is used as in cl.exe. The
astute observer will already have realized that GCC uses the same trick
as cl.exe, of moving the fastcall arguments from their registers (ecx
and edx again) onto a negative offset on the stack. Again, optimizations
are turned off. ecx is moved into the first position (-4) and edx is
moved into the second position (-8). Like the CDECL example above, the
value at -4 is doubled, and the value at -8 is tripled. Therefore, -4
(ecx) is x, and -8 (edx) is y. It would seem from this listing then that
values are passed left-to-right, although we will need to take a look at
the larger, MyFunction2 example:

``` asm
 .globl @MyFunction2@24
    .def    @MyFunction2@24;    .scl    2;  .type   32; .endef
 @MyFunction2@24:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $8, %esp
    movl    %ecx, -4(%ebp)
    movl    %edx, -8(%ebp)
    movl    -4(%ebp), %eax
    imull   -8(%ebp), %eax
    movl    8(%ebp), %edx
    incl    %edx
    imull   %edx, %eax
    movl    12(%ebp), %edx
    addl    $2, %edx
    imull   %edx, %eax
    movl    16(%ebp), %edx
    addl    $3, %edx
    imull   %edx, %eax
    movl    20(%ebp), %edx
    addl    $4, %edx
    imull   %edx, %eax
    leave
    ret     $16
```

By following the fact that in MyFunction2, successive parameters are
added to increasing constants, we can deduce the positions of each
parameter. -4 is still x, and -8 is still y. +8 gets incremented by 1
(z), +12 gets increased by 2 (a). +16 gets increased by 3 (b), and +20
gets increased by 4 (c). Let\'s list these values then:

`z = [ebp + 8]`\
`a = [ebp + 12]`\
`b = [ebp + 16]`\
`c = [ebp + 20]`

c is the furthest down, and therefore was the first pushed. z is the
highest to the top, and was therefore the last pushed. Arguments are
therefore pushed in right-to-left order, just like cl.exe.

### STDCALL

Let\'s compare then the implementation of MyFunction1 in GCC:

``` asm
 .globl _MyFunction1@8
    .def    _MyFunction1@8; .scl    2;  .type   32; .endef
 _MyFunction1@8:
    pushl   %ebp
    movl    %esp, %ebp
    movl    8(%ebp), %eax
    leal    (%eax,%eax), %ecx
    movl    12(%ebp), %edx
    movl    %edx, %eax
    addl    %eax, %eax
    addl    %edx, %eax
    leal    (%eax,%ecx), %eax
    popl    %ebp
    ret     $8
```

The name decoration is the same as in cl.exe, so STDCALL functions (and
CDECL and FASTCALL for that matter) can be assembled with either
compiler, and linked with either linker, it seems. The stack frame is
set up, then the value at \[ebp + 8\] is doubled. After that, the value
at \[ebp + 12\] is tripled. Therefore, +8 is x, and +12 is y. Again,
these values are pushed in right-to-left order. This function also
cleans its own stack with the \"ret 8\" instruction.

Looking at a bigger example:

``` asm
 .globl _MyFunction2@24
    .def    _MyFunction2@24;    .scl    2;  .type   32; .endef
 _MyFunction2@24:
    pushl   %ebp
    movl    %esp, %ebp
    movl    8(%ebp), %eax
    imull   12(%ebp), %eax
    movl    16(%ebp), %edx
    incl    %edx
    imull   %edx, %eax
    movl    20(%ebp), %edx
    addl    $2, %edx
    imull   %edx, %eax
    movl    24(%ebp), %edx
    addl    $3, %edx
    imull   %edx, %eax
    movl    28(%ebp), %edx
    addl    $4, %edx
    imull   %edx, %eax
    popl    %ebp
    ret     $24
```

We can see here that values at +8 and +12 from ebp are still x and y,
respectively. The value at +16 is incremented by 1, the value at +20 is
incremented by 2, etc all the way to the value at +28. We can therefore
create the following table:

`x = [ebp + 8]`\
`y = [ebp + 12]`\
`z = [ebp + 16]`\
`a = [ebp + 20]`\
`b = [ebp + 24]`\
`c = [ebp + 28]`

With c being pushed first, and x being pushed last. Therefore, these
parameters are also pushed in right-to-left order. This function then
also cleans 24 bytes off the stack with the \"ret 24\" instruction.

## Example: C Calling Conventions

## Example: Named Assembly Function

## Example: Unnamed Assembly Function

## Example: Another Unnamed Assembly Function

## Example: Name Mangling


# X86 Disassembly/Branches

## Branching

Computer science professors tell their students to avoid jumps and
**goto** instructions, to avoid the proverbial \"spaghetti code.\"
Unfortunately, assembly only has jump instructions to control program
flow. This chapter will explore the subject that many people avoid like
the plague, and will attempt to show how the spaghetti of assembly can
be translated into the more familiar control structures of high-level
language. Specifically, this chapter will focus on **If-Then-Else** and
**Switch** branching instructions.

## If-Then

Let\'s consider a generic **if** statement in pseudo-code followed by
its equivalent form using jumps:

+----------------------------------+----------------------------------+
| `if (condition) then`\           | ![](_C_langu                     |
| ` do_action;`                    | age_if.png "_C_language_if.png") |
|                                  |                                  |
| `if                              |                                  |
| not (condition) then goto end;`\ |                                  |
| `  do_action;`\                  |                                  |
| `end:`                           |                                  |
+----------------------------------+----------------------------------+

What does this code do? In English, the code checks the condition and
performs a jump only if it is *false*. With that in mind, let\'s compare
some actual C code and its Assembly translation:

+-------------+--------------+
| ``` C       | ``` asm      |
|  if(x == 0) |  mov eax, $x |
|  {          |  cmp eax, 0  |
|    x = 1;   |  jne end     |
|  }          |  mov eax, 1  |
|  x++;       |  end:        |
| ```         |  inc eax     |
|             |  mov $x, eax |
|             | ```          |
+-------------+--------------+

Note that when we translate to assembly, we need to *negate* the
condition of the jump because\--like we said above\--we only jump if the
condition is false. To recreate the high-level code, simply negate the
condition once again.

Negating a comparison may be tricky if you\'re not paying attention.
Here are the correct dual forms:

  Instruction   Meaning
  ------------- ----------------------------------------
  JNE           **J**ump if **n**ot **e**qual
  JE            **J**ump if **e**qual
  JG            **J**ump if **g**reater
  JLE           **J**ump if **l**ess than or **e**qual
  JL            **J**ump if **l**ess than
  JGE           **J**ump if **g**reater or **e**qual

And here are some examples.

``` asm
 mov eax, $x                     //move x into eax
 cmp eax, $y                     //compare eax with y
 jg end                          //jump if greater than
 inc eax
 mov $x, eax                    //increment x
 end:
 ...
```

Is produced by these C statements:

``` C
 if(x <= y)
 {
    x++;
 }
```

As you can see, x is incremented only if it is **less than or equal to**
y. Thus, if it is greater than y, it will not be incremented as in the
assembler code. Similarly, the C code

``` C
 if(x < y)
 {
    x++;
 }
```

produces this assembler code:

``` asm
 mov eax, $x                        //move x into eax
 cmp eax, $y                        //compare eax with y
 jge end                            //jump if greater than or equal to
 inc eax
 move $x, eax                       //increment x
 end:
 ...
```

X is incremented in the C code only if it is **less than** y, so the
assembler code now jumps if it\'s greater than or equal to y. This kind
of thing takes practice, so we will try to include lots of examples in
this section.

## If-Then-Else

Let us now look at a more complicated case: the **If-Then-Else**
instruction.

+----------------------------------+----------------------------------+
| `if (condition) then`\           | ![](C_language_if_el             |
| `  do_action`\                   | se.png "C_language_if_else.png") |
| `else`\                          |                                  |
| `  do_alternative_action;`       |                                  |
|                                  |                                  |
| `if not (condition) goto else;`\ |                                  |
| `  do_action;`\                  |                                  |
| `  goto end;`\                   |                                  |
| `else:`\                         |                                  |
| `  do_alternative_action;`\      |                                  |
| `end:`                           |                                  |
+----------------------------------+----------------------------------+

Now, what happens here? Like before, the if statement only jumps to the
else clause when the condition is false. However, we must also install
an *unconditional* jump at the end of the \"then\" clause, so we don\'t
perform the else clause directly afterwards.

Now, here is an example of a real C If-Then-Else:

``` C
 if(x == 10)
 {
    x = 0;
 }
 else
 {
    x++;
 }
```

Which gets translated into the following assembly code:

``` asm
 mov eax, $x
 cmp eax, 0x0A ;0x0A = 10
 jne else
 mov eax, 0
 jmp end
 else:
 inc eax
 end:
 mov $x, eax
```

As you can see, the addition of a single unconditional jump can add an
entire extra option to our conditional.

## Switch-Case

**Switch-Case** structures can be very complicated when viewed in
assembly language, so we will examine a few examples. First, keep in
mind that in C, there are several keywords that are commonly used in a
switch statement. Here is a recap:

Switch : This keyword tests the argument, and starts the switch structure\
Case : This creates a label that execution will switch to, depending on the value of the argument.\
Break : This statement jumps to the end of the switch block\
Default : This is the label that execution jumps to if and only if it doesn\'t match up to any other conditions

Lets say we have a general switch statement, but with an extra label at
the end, as such:

``` C
 switch (x)
 {
 //body of switch statement
 }
 end_of_switch:
```

Now, every **break** statement will be immediately replaced with the
statement

``` asm
 jmp end_of_switch
```

But what do the rest of the statements get changed to? The case
statements can each resolve to any number of arbitrary integer values.
How do we test for that? The answer is that we use a \"Switch Table\".
Here is a simple, C example:

``` C
 int main(int argc, char **argv)
 { //line 10
    switch(argc)
    {
        case 1:
            MyFunction(1);
            break;
        case 2:
            MyFunction(2);
            break;
        case 3:
            MyFunction(3);
            break;
        case 4:
            MyFunction(4);
            break;
        default:
            MyFunction(5);
    }
    return 0;
 }
```

And when we compile this with **cl.exe**, we can generate the following
listing file:

``` asm
 tv64 = -4      ; size = 4
 _argc$ = 8     ; size = 4
 _argv$ = 12        ; size = 4
 _main  PROC NEAR
 ; Line 10
    push    ebp
    mov ebp, esp
    push    ecx
 ; Line 11
    mov eax, DWORD PTR _argc$[ebp]
    mov DWORD PTR tv64[ebp], eax
    mov ecx, DWORD PTR tv64[ebp]
    sub ecx, 1
    mov DWORD PTR tv64[ebp], ecx
    cmp DWORD PTR tv64[ebp], 3
    ja  SHORT $L810
    mov edx, DWORD PTR tv64[ebp]
    jmp DWORD PTR $L818[edx*4]
 $L806:
 ; Line 14
    push    1
    call    _MyFunction
    add esp, 4
 ; Line 15
    jmp SHORT $L803
 $L807:
 ; Line 17
    push    2
    call    _MyFunction
    add esp, 4
 ; Line 18
        jmp     SHORT $L803
 $L808:
 ; Line 19
    push    3
    call    _MyFunction
    add esp, 4
 ; Line 20
    jmp SHORT $L803
 $L809:
 ; Line 22
    push    4
    call    _MyFunction
    add esp, 4
 ; Line 23
    jmp SHORT $L803
 $L810:
 ; Line 25
    push    5
    call    _MyFunction
    add esp, 4
 $L803:
 ; Line 27
    xor eax, eax
 ; Line 28
    mov esp, ebp
    pop ebp
    ret 0
 $L818:
    DD  $L806
    DD  $L807
    DD  $L808
    DD  $L809
 _main  ENDP
```

Lets work our way through this. First, we see that line 10 sets up our
standard stack frame, and it also saves ecx. Why does it save ecx?
Scanning through the function, we never see a corresponding \"pop ecx\"
instruction, so it seems that the value is never restored at all. In
fact, the compiler isn\'t saving ecx at all, but is instead simply
reserving space on the stack: it\'s creating a local variable. The
original C code didn\'t have any local variables, however, so perhaps
the compiler just needed some extra scratch space to store intermediate
values. Why doesn\'t the compiler execute the more familiar \"sub esp,
4\" command to create the local variable? **push ecx** is just a faster
instruction that does the same thing. This \"scratch space\" is being
referenced by a *negative offset* from ebp. **tv64** was defined in the
beginning of the listing as having the value -4, so every call to
\"tv64\[ebp\]\" is a call to this scratch space.

There are a few things that we need to notice about the function in
general:

-   Label \$L803 is the end_of_switch label. Therefore, every \"jmp
    SHORT \$L803\" statement is a **break**. This is verifiable by
    comparing with the C code line-by-line.
-   Label \$L818 contains a list of hard-coded memory addresses, which
    here are labels in the code section! Remember, labels resolve to the
    memory address of the instruction. This must be an important part of
    our puzzle.

To solve this puzzle, we will take an in-depth look at line 11:

``` asm
 mov    eax, DWORD PTR _argc$[ebp]
 mov    DWORD PTR tv64[ebp], eax
 mov    ecx, DWORD PTR tv64[ebp]
 sub    ecx, 1
 mov    DWORD PTR tv64[ebp], ecx
 cmp    DWORD PTR tv64[ebp], 3
 ja SHORT $L810
 mov    edx, DWORD PTR tv64[ebp]
 jmp    DWORD PTR $L818[edx*4]
```

This sequence performs the following pseudo-C operation:

`if( argc - 1 >= 4 )`\
`{`\
`   goto $L810;   /* the default */`\
`}`\
`label *L818[] = { $L806, $L807, $L808, $L809 };  /* define a table of jumps, one per each case */`\
`//`\
`goto L818[argc - 1];   /* use the address from the table to jump to the correct case */`

Here\'s why\...

### The Setup

``` asm
 mov    eax, DWORD PTR _argc$[ebp]
 mov    DWORD PTR tv64[ebp], eax
 mov    ecx, DWORD PTR tv64[ebp]
 sub    ecx, 1
 mov    DWORD PTR tv64[ebp], ecx
```

The value of argc is moved into eax. The value of eax is then
immediately moved to the scratch space. The value of the scratch space
is then moved into ecx. Sounds like an awfully convoluted way to get the
same value into so many different locations, but remember: I turned off
the optimizations. The value of ecx is then decremented by 1. Why
didn\'t the compiler use a **dec** instruction instead? Perhaps the
statement is a general statement, that in this case just happens to have
an argument of 1. We don\'t know why exactly, all we know is this:

-   **eax = \"scratch pad\"**
-   **ecx = eax - 1**

Finally, the last line moves the new, decremented value of ecx *back
into the scratch pad*. Very inefficient.

### The Compare and Jumps

``` asm
 cmp    DWORD PTR tv64[ebp], 3
 ja SHORT $L810
```

The value of the scratch pad is compared with the value 3, and if the
*unsigned* value is above 3 (4 or more), execution jumps to label
\$L810. How do I know the value is unsigned? I know because **ja** is an
unsigned conditional jump. Let\'s look back at the original C code
switch:

``` C
        switch(argc)
    {
        case 1:
            MyFunction(1);
            break;
        case 2:
            MyFunction(2);
            break;
        case 3:
            MyFunction(3);
            break;
        case 4:
            MyFunction(4);
            break;
        default:
            MyFunction(5);
    }
```

Remember, the scratch pad contains the value (argc - 1), which means
that this condition is only triggered when argc \> 4. What happens when
argc is greater than 4? The function goes to the default condition. Now,
let\'s look at the next two lines:

``` asm
 mov    edx, DWORD PTR tv64[ebp]
 jmp    DWORD PTR $L818[edx*4]
```

**edx** gets the value of the scratch pad (argc - 1), and then there is
a very weird jump that takes place: execution jumps to a location
pointed to by the value (edx \* 4 + \$L818). What is \$L818? We will
examine that right now.

### The Switch Table

``` asm
 $L818:
    DD  $L806
    DD  $L807
    DD  $L808
    DD  $L809
```

\$L818 is a pointer, in the code section, to a list of other code
section pointers. These pointers are all 32bit values (DD is a DWORD).
Let\'s look back at our jump statement:

``` asm
 jmp    DWORD PTR $L818[edx*4]
```

In this jump, \$L818 *isn\'t the offset, it\'s the base*, edx\*4 is the
offset. As we said earlier, edx contains the value of (argc - 1). If
argc == 1, we jump to \[\$L818 + 0\] which is \$L806. If argc == 2, we
jump to \[\$L818 + 4\], which is \$L807. Get the picture? A quick look
at labels \$L806, \$L807, \$L808, and \$L809 shows us exactly what we
expect to see: the bodies of the **case** statements from the original C
code, above. Each one of the case statements calls the function
\"MyFunction\", then breaks, and then jumps to the end of the switch
block.

## Ternary Operator ?:

Again, the best way to learn is by doing. Therefore we will go through a
mini example to explain the ternary operator. Consider the following C
code program:

``` C
 int main(int argc, char **argv)
 {
    return (argc > 1)?(5):(0);
 }
```

**cl.exe** produces the following assembly listing file:

``` asm
 _argc$ = 8                     ; size = 4
 _argv$ = 12                        ; size = 4
 _main  PROC NEAR
 ; File c:\documents and settings\andrew\desktop\test2.c
 ; Line 2
    push    ebp
    mov ebp, esp
 ; Line 3
    xor eax, eax

        cmp DWORD PTR _argc$[ebp], 1
        setle   al
        dec eax
        and eax, 5
 ; Line 4
    pop ebp
    ret 0
 _main  ENDP
```

Line 2 sets up a stack frame, and line 4 is a standard exit sequence.
There are no local variables. It is clear that Line 3 is where we want
to look.

The instruction \"xor eax, eax\" simply sets eax to 0. For more
information on that line, see the chapter on unintuitive
instructions. The **cmp** instruction
tests the condition of the ternary operator. The **setle** function is
one of a set of x86 functions that works like a conditional move: al
gets the value 1 if argc \<= 1. Isn\'t that the exact opposite of what
we wanted? In this case, it is. Let\'s look at what happens when argc =
0: **al** gets the value 1. **al** is decremented (al = 0), and then eax
is logically anded with 5. 5 & 0 = 0. When argc == 2 (greater than 1),
the **setle** instruction doesn\'t do anything, and eax still is zero.
eax is then decremented, which means that eax == -1. What is -1?

In x86 processors, negative numbers are stored in **two\'s-complement**
format. For instance, let\'s look at the following C code:

``` C
 BYTE x;
 x = -1;
```

At the end of this C code, **x** will have the value 11111111: all ones!

When argc is greater than 1, setle sets al to zero. Decrementing this
value sets every bit in eax to a logical 1. Now, when we perform the
logical **and** function we get:

` ...11111111`\
`&...00000101     ;101 is 5 in binary`\
`------------`\
` ...00000101`

eax gets the value 5. In this case, it\'s a roundabout method of doing
it, but as a reverser, this is the stuff you need to worry about.

For reference, here is the GCC assembly output of the same ternary
operator from above:

``` asm
 _main:
 pushl  %ebp
 movl   %esp, %ebp
 subl   $8, %esp
 xorl   %eax, %eax
 andl   $-16, %esp
 call   __alloca
 call   ___main
 xorl   %edx, %edx
 cmpl   $2, 8(%ebp)
 setge  %dl
 leal   (%edx,%edx,4), %eax
 leave
 ret
```

Notice that GCC produces slightly different code than cl.exe produces.
However, the stack frame is set up the same way. Notice also that GCC
doesn\'t give us line numbers, or other hints in the code. The ternary
operator line occurs after the instruction \"call \_\_main\". Let\'s
highlight that section here:

``` asm
 xorl   %edx, %edx
 cmpl   $2, 8(%ebp)
 setge  %dl
 leal   (%edx,%edx,4), %eax
```

Again, **xor** is used to set edx to 0 quickly. Argc is tested against 2
(instead of 1), and dl is set if argc is *greater then or equal*. If dl
gets set to 1, the **leal** instruction directly thereafter will move
the value of 5 into eax (because lea (edx,edx,4) means edx + edx \* 4,
i.e. edx \* 5).


# X86 Disassembly/Loops

## Loops

To complete repetitive tasks, programmers often implement **loops**.
There are many sorts of loops, but they can all be boiled down to a few
similar formats in assembly code. This chapter will discuss loops, how
to identify them, and how to \"decompile\" them back into high-level
representations.

## Do-While Loops

It seems counterintuitive that this section will consider **Do-While**
loops first, considering that they might be the least used of all the
variations in practice. However, there is method to our madness, so read
on.

Consider the following generic Do-While loop:

+---+---+
| ` | ! |
| ` | [ |
| ` | ] |
|   | ( |
| C | C |
|   | _ |
| d | l |
| o | a |
|   | n |
| { | g |
|   | u |
|   | a |
|   | g |
|   | e |
| a | _ |
| c | d |
| t | o |
| i | _ |
| o | w |
| n | h |
| ; | i |
|   | l |
| } | e |
|   | . |
| w | p |
| h | n |
| i | g |
| l |   |
| e | " |
| ( | C |
| c | _ |
| o | l |
| n | a |
| d | n |
| i | g |
| t | u |
| i | a |
| o | g |
| n | e |
| ) | _ |
| ; | d |
| ` | o |
| ` | _ |
| ` | w |
|   | h |
|   | i |
|   | l |
|   | e |
|   | . |
|   | p |
|   | n |
|   | g |
|   | " |
|   | ) |
+---+---+

What does this loop do? The loop body simply executes, the condition is
tested at the end of the loop, and the loop jumps back to the beginning
of the loop if the condition is satisfied. Unlike **if** statements,
Do-While conditions are not reversed.

Let us now take a look at the following C code:

``` C
 do
 {
   x++;
 } while(x != 10);
```

Which can be translated into assembly language as such:

``` asm
 mov eax, $x
 beginning:
 inc eax
 cmp eax, 0x0A ;0x0A = 10
 jne beginning
 mov $x, eax
```

## While Loops

**While** loops look almost as simple as a **Do-While** loop, but in
reality they aren\'t as simple at all. Let\'s examine a generic
while-loop:

``` C
 while(x)
 {
    //loop body
 }
```

What does this loop do? First, the loop checks to make sure that x is
true. If x is not true, the loop is skipped. The loop body is then
executed, followed by another check: is x still true? If x is still
true, execution jumps back to the top of the loop, and execution
continues. Keep in mind that there needs to be a jump at the bottom of
the loop (to get back up to the top), but it makes no sense to jump back
to the top, retest the conditional, and then jump *back to the bottom of
the loop* if the conditional is found to be false. The while-loop then,
performs the following steps:

1.  check the condition. if it is false, go to the end
2.  perform the loop body
3.  check the condition, if it is true, jump to 2.
4.  if the condition is not true, fall-through the end of the loop.

Here is a while-loop in C code:

``` C
 while(x <= 10)
 {
    x++;
 }
```

And here then is that same loop translated into assembly:

``` asm
 mov eax, $x
 cmp eax, 0x0A
 jg end
 beginning:
 inc eax
 cmp eax, 0x0A
 jle beginning
 end:
```

If we were to translate that assembly code **back into C**, we would get
the following code:

``` C
 if(x <= 10) //remember: in If statements, we reverse the condition from the asm
 {
   do
   {
     x++;
   } while(x <= 10)
 }
```

See why we covered the Do-While loop first? Because the While-loop
becomes a Do-While when it gets assembled.

So why can\'t the jump label occur before the test?

``` asm
mov eax, $x
beginning:
cmp eax, 0x0A
jg end
inc eax
jmp beginning
end:
mov $x, eax
```

## For Loops

What is a For-Loop? In essence, it\'s a While-Loop with an initial
state, a condition, and an iterative instruction. For instance, the
following generic For-Loop:

+---+---+
| ` | ! |
| ` | [ |
| ` | ] |
|   | ( |
| C | C |
|   | _ |
| f | l |
| o | a |
| r | n |
| ( | g |
| i | u |
| n | a |
| i | g |
| t | e |
| i | _ |
| a | f |
| l | o |
| i | r |
| z | . |
| a | p |
| t | n |
| i | g |
| o |   |
| n | " |
| ; | C |
|   | _ |
| c | l |
| o | a |
| n | n |
| d | g |
| i | u |
| t | a |
| i | g |
| o | e |
| n | _ |
| ; | f |
|   | o |
| i | r |
| n | . |
| c | p |
| r | n |
| e | g |
| m | " |
| e | ) |
| n |   |
| t |   |
| ) |   |
|   |   |
| { |   |
|   |   |
|   |   |
|   |   |
| a |   |
| c |   |
| t |   |
| i |   |
| o |   |
| n |   |
|   |   |
| } |   |
| ` |   |
| ` |   |
| ` |   |
+---+---+

gets translated into the following pseudocode while-loop:

``` C
 initialization;
 while(condition)
 {
   action;
   increment;
 }
```

Which in turn gets translated into the following Do-While Loop:

``` C
 initialization;
 if(condition)
 {
    do
    {
       action;
       increment;
    } while(condition);
 }
```

Note that often in for() loops you assign an initial constant value in A
(for example x = 0), and then compare that value with another constant
in B (for example x \< 10). Most optimizing compilers will be able to
notice that the first time x IS less than 10, and therefore there is no
need for the initial if(B) statement. In such cases, the compiler will
simply generate the following sequence:

``` C
 initialization;
 do
 {
    action
    increment;
 } while(condition);
```

rendering the code indistinguishable from a while() loop.

## Other Loop Types

C only has Do-While, While, and For Loops, but some other languages may
very well implement their own types. Also, a good C-Programmer could
easily \"home brew\" a new type of loop using a series of good macros,
so they bear some consideration:

### Do-Until Loop

A common Do-Until Loop will take the following form:

``` C
 do
 {
   //loop body
 } until(x);
```

which essentially becomes the following Do-While loop:

``` C
 do
 {
   //loop body
 } while(!x);
```

### Until Loop

Like the Do-Until loop, the standard Until-Loop looks like the
following:

``` C
 until(x)
 {
   //loop body
 }
```

which (likewise) gets translated to the following While-Loop:

``` C
 while(!x)
 {
   //loop body
 }
```

### Do-Forever Loop

A Do-Forever loop is simply an unqualified loop with a condition that is
always true. For instance, the following pseudo-code:

``` C
 doforever
 {
   //loop body
 }
```

will become the following while-loop:

``` C
 while(1)
 {
   //loop body
 }
```

Which can actually be reduced to a simple unconditional jump statement:

``` asm
 beginning:
 ;loop body
 jmp beginning
```

Notice that some non-optimizing compilers will produce nonsensical code
for this:

``` asm
 mov ax, 1
 cmp ax, 1
 jne loopend
 beginning:
 ;loop body
 cmp ax, 1
 je beginning
 loopend:
```

Notice that a lot of the comparisons here are not needed since the
condition is a constant. Most compilers will optimize cases like this.


# X86 Disassembly/Variables

## Variables

We\'ve already seen some mechanisms to create local storage on the
stack. This chapter will talk about some other variables, including
**global variables**, **static variables**, variables labelled
\"**const**,\" \"**register**,\" and \"**volatile**.\" It will also
consider some general techniques concerning variables, including
accessor and setter methods (to borrow from object-oriented
terminology). This section may also talk about setting memory
breakpoints in a debugger to track memory I/O on a variable.

## How to Spot a Variable

Variables come in 2 distinct flavors: those that are created on the
stack (local variables), and those that are accessed via a hardcoded
memory address (global variables). Any memory that is accessed via a
hard-coded address is usually a global variable. Variables that are
accessed as an offset from esp, or ebp are frequently local variables.

Hardcoded address : Anything hardcoded is a value that is stored as-is in the binary, and is not changed at runtime. For instance, the value 0x2054 is hardcoded, whereas the current value of variable X is not hard-coded and may change at runtime.

Example of a hardcoded address:

``` asm
 mov eax, [0x77651010]
```

OR:

``` asm
 mov ecx, 0x77651010
 mov eax, [ecx]
```

Example of a non-hardcoded (softcoded?) address:

``` asm
 mov ecx, [esp + 4]
 add ecx, ebx
 mov eax, [ecx]
```

In the last example, the value of ecx is calculated at run-time, whereas
in the first 2 examples, the value is the same every time. RVAs are
considered hard-coded addresses, even though the loader needs to \"fix
them up\" to point to the correct locations.

## .BSS and .DATA sections

Both .bss and .data sections contain values which can change at run-time
(e.g. *variables*). Typically, variables that are initialized to a
non-zero value in the source are allocated in the .data section (e.g.
\"int a = 10;\"). Variables that are not initialized, or initialized
with a zero value, can be allocated to the .bss section (e.g. \"int
arr\[100\];\"). Because all values of .bss variables are guaranteed to
be zero at the start of the program, there is no need for the linker to
allocate space in the binary file. Therefore, .bss sections do not take
space in the binary file, regardless of their size.

## \"Static\" Local Variables

Local variables labeled **static** maintain their value across function
calls, and therefore cannot be created on the stack like other local
variables are. How are static variables created? Let\'s take a simple
example C function:

``` C
 void MyFunction(int a)
 {
    static int x = 0;
    printf("my number: ");
    printf("%d, %d\n", a, x);
 }
```

Compiling to a listing file with **cl.exe** gives us the following code:

``` asm
 _BSS   SEGMENT
 ?x@?1??MyFunction@@9@9 DD 01H DUP (?)      ; `MyFunction'::`2'::x
 _BSS   ENDS
 _DATA  SEGMENT
 $SG796 DB  'my number: ', 00H
 $SG797 DB  '%d, %d', 0aH, 00H
 _DATA  ENDS
 PUBLIC _MyFunction
 EXTRN  _printf:NEAR
 ; Function compile flags: /Odt
 _TEXT  SEGMENT
 _a$ = 8                    ; size = 4
 _MyFunction PROC NEAR
 ; Line 4
    push    ebp
    mov ebp, esp
 ; Line 6
    push    OFFSET FLAT:$SG796
    call    _printf
    add esp, 4
 ; Line 7
    mov eax, DWORD PTR ?x@?1??MyFunction@@9@9
    push    eax
    mov ecx, DWORD PTR _a$[ebp]
    push    ecx
    push    OFFSET FLAT:$SG797
    call    _printf
    add esp, 12                 ; 0000000cH
 ; Line 8
    pop ebp
    ret 0
 _MyFunction ENDP
 _TEXT  ENDS
```

Normally when assembly listings are posted in this wikibook, most of the
code gibberish is discarded to aid readability, but in this instance,
the \"gibberish\" contains the answer we are looking for. As can be
clearly seen, this function creates a standard stack frame, and it
doesn\'t create any local variables on the stack. In the interests of
being complete, we will take baby-steps here, and work to the conclusion
logically.

In the code for Line 7, there is a call to \_printf with 3 arguments.
Printf is a standard **libc** function, and it therefore can be assumed
to be cdecl calling convention. Arguments are pushed, therefore, from
right to left. Three arguments are pushed onto the stack before \_printf
is called:

-   `DWORD PTR ?x@?1??MyFunction@@9@9`
-   `DWORD PTR _a$[ebp]`
-   `OFFSET FLAT:$SG797`

The second one, \_a\$\[ebp\] is partially defined in this assembly
instruction:

`_a$ = 8`

And therefore \_a\$\[ebp\] is the variable located at offset +8 from
ebp, or the first argument to the function. OFFSET FLAT:\$SG797 likewise
is declared in the assembly listing as such:

``` asm
 SG797  DB  '%d, %d', 0aH, 00H
```

If you have your ASCII table handy, you will notice that 0aH = 0x0A =
\'\\n\'. OFFSET FLAT:\$SG797 then is the format string to our printf
statement. Our last option then is the mysterious-looking
\"?x@?1??MyFunction@@9@9\", which is defined in the following assembly
code section:

``` asm
 _BSS   SEGMENT
 ?x@?1??MyFunction@@9@9 DD 01H DUP (?)
 _BSS   ENDS
```

This shows that the Microsoft C compiler creates static variables in the
.bss section. This might not be the same for all compilers, but the
lesson is the same: local static variables are created and used in a
very similar, if not the exact same, manner as global values. In fact,
as far as the reverser is concerned, the two are usually
interchangeable. Remember, the only real difference between static
variables and global variables is the idea of \"scope\", which is only
used by the compiler.

## Signed and Unsigned Variables

Integer formatted variables, such as **int**, **char**, **short** and
**long** may be declared signed or unsigned variables in the C source
code. There are two differences in how these variables are treated:

1.  Signed variables use signed instructions such as **add**, and
    **sub**. Unsigned variables use unsigned arithmetic instructions
    such as **addi**, and **subi**.
2.  Signed variables use signed branch instructions such as **jge** and
    **jl**. Unsigned variables use unsigned branch instructions such as
    **jae**, and **jb**.

The difference between signed and unsigned instructions is the
conditions under which the various flags for greater-than or less-than
(overflow flags) are set. The integer result values are exactly the same
for both signed and unsigned data.

## Floating-Point Values

Floating point values tend to be 32-bit data values (for **float**) or
64-bit data values (for **double**). These values are distinguished from
ordinary integer-valued variables because they are used with
floating-point instructions. Floating point instructions typically start
with the letter *f*. For instance, **fadd**, **fcmp**, and similar
instructions are used with floating point values. Of particular note are
the **fload** instruction and variants. These instructions take an
integer-valued variable and converts it into a floating point variable.

We will discuss floating point variables in more detail in a later
chapter.

## Global Variables

Global variables do not have a limited scope like lexical variables do
inside a function body. Since the notion of lexical scope implies the
use of the system stack, and since global variables are not lexical in
nature, they are typically not found on the stack. Global variables tend
to exist in the program as a hard-coded memory address, a location which
never changes throughout program execution. These could exist in the
DATA segment of the executable, or anywhere else that a hard-coded
memory address can be used to store data.

In C, global variables are defined outside the body of any function.
There is no \"global\" keyword. Any variable which is not defined inside
a function is global. In C however, a variable which is not defined
inside a function is only global to the particular source code file in
which it is defined. For example, we have two files `Foo.c` and `Bar.c`,
and a global variable `MyGlobalVar`:

+-----------------------+------------------------+
| Foo.c                 | Bar.c                  |
+=======================+========================+
| ``` c                 | ``` c                  |
| int MyGlobalVar;      | int GetVarBar(void)    |
|                       | {                      |
| int GetVarFoo(void)   |   //wrong!             |
| {                     |   return MyGlobalVar;  |
|   //right!            | }                      |
|   return MyGlobalVar; | ```                    |
| }                     |                        |
| ```                   |                        |
+-----------------------+------------------------+

In the example above, the variable `MyGlobalVar` is visible inside the
file `Foo.c`, but is not visible inside the file `Bar.c`. To make
`MyGlobalVar` visible inside all project files, we need to use the
`extern` keyword, which we will discuss below.

### \"`static`\" Variables

The C programming language specifies a special keyword \"`static`\" to
define variables which are lexical to the function (they cannot be
referenced from outside the function) but they maintain their values
across function calls. Unlike ordinary lexical variables which are
created on the stack when the function is entered and are destroyed from
the stack when the function returns, static variables are created once
and are never destroyed.

``` c
int MyFunction(void)
{
  static int x;
  ...
}
```

Static variables in C are global variables, except the compiler takes
precautions to prevent the variable from being accessed outside of the
parent function\'s scope. Like global variables, static variables are
referenced using a hardcoded memory address, not a location on the stack
like ordinary variables. However unlike globals, static variables are
only used inside a single function. There is no difference between a
global variable which is only used in a single function, and a static
variable inside that same function. However, it\'s good programming
practice to limit the number of global variables, so when disassembling,
you should prefer interpreting these variables as static instead of
global.

### \"`extern`\" Variables

The `extern` keyword is used by a C compiler to indicate that a
particular variable is global to the entire project, not just to a
single source code file. Besides this distinction, and the slightly
larger lexical scope of extern variables, they should be treated like
ordinary global variables.

In static libraries, variables marked as being extern might be available
for use with programs which are linked to the library.

### Global Variables Summary

Here is a table to summarize some points about global variables:

  -------------------- -------------------------------------------------- --------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                       How it\'s referenced                               Lexical scope               Notes
  `static` variables   Hard-coded memory address, only in one function    One function only           In disassembly, indistinguishable from global variables except that it\'s only used in one function. A global variable is only static if it\'s never used in another function.
  Global variables     Hard-coded memory address, only in one file        One source code file only   Global variables are only used in a single file. This can help you when disassembling to get a rough estimate for how the original source code was arranged.
  `extern` variables   Hard-coded memory address, in the entire project   The entire project          Extern variables are available for use in all functions of a project, and in programs linked to the project (external libraries, for example).
  -------------------- -------------------------------------------------- --------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

When disassembling, a hard-coded memory address should be considered to
be an ordinary global variable unless you can determine from the scope
of the variable that it is static or extern.

## Constants

Variables qualified with the **const** keyword (in C) are frequently
stored in the .data section of the executable. Constant values can be
distinguished because they are initialized at the beginning of the
program, and are never modified by the program itself. For this reasons,
some compilers may choose to store constant variables (especially
strings) in the .text section of the executable, thus allowing the
sharing of these variables across multiple instances of the same
process. This creates a big problem for the reverser, who now has to
decide whether the code he\'s looking at is part of a constant variable
or part of a subroutine.

## \"Volatile\" memory

In C and C++, variables can be declared \"volatile,\" which tells the
compiler that the memory location can be accessed from *external* or
*concurrent* processes, and that the compiler should not perform any
optimizations on the variable. For instance, if multiple threads were
all accessing and modifying a single global value, it would be bad for
the compiler to store that variable in a register sometimes, and flush
it to memory infrequently. In general, Volatile memory must be flushed
to memory after every calculation, to ensure that the most current
version of the data is in memory when other processes come to look for
it.

It is not always possible to determine from a disassembly listing
whether a given variable is a volatile variable. However, if the
variable is accessed frequently from memory, and its value is constantly
updated in memory (especially if there are free registers available),
that\'s a good hint that the variable might be volatile.

## Simple Accessor Methods

An Accessor Method is a tool derived from OO theory and practice. In its
most simple form, an accessor method is a function that receives no
parameters (or perhaps simply an offset), and returns the value of a
variable. Accessor and Setter methods are ways to restrict access to
certain variables. The only standard way to get the value of the
variable is to use the Accessor.

Accessors can prevent some simple problems, such as out-of-bounds array
indexing, and using uninitialized data. Frequently, Accessors contain
little or no error-checking.

Here is an example:

``` asm
 push ebp
 mov ebp, esp
 mov eax, [ecx + 8] ;THISCALL function, passes "this" pointer in ecx
 mov esp, ebp
 pop ebp
 ret
```

Because they are so simple, accessor methods are frequently heavily
optimized (they generally don\'t need a stack frame), and are even
occasionally *inlined* by the compiler.

## Simple Setter (Manipulator) Methods

Setter methods are the antithesis of an accessor method, and provide a
unified way of altering the value of a given variable. Setter methods
will often take as a parameter the value to be set to the variable,
although some methods (Initializers) simply set the variable to a
pre-defined value. Setter methods often do bounds checking, and error
checking on the variable before it is set, and frequently either a)
return no value, or b) return a simple boolean value to determine
success.

Here is an example:

``` asm
 push ebp
 mov ebp, esp
 cmp [ebp + 8], 0
 je error
 mov eax, [ebp + 8]
 mov [ecx + 0], eax
 mov eax, 1
 jmp end
 :error
 mov eax, 0
 :end
 mov esp, ebp
 pop ebp
 ret
```


# X86 Disassembly/Data Structures

## Data Structures

Few programs can work by using simple memory storage; most need to
utilize complex data objects, including **pointers**, **arrays**,
**structures**, and other complicated types. This chapter will talk
about how compilers implement complex data objects, and how the reverser
can identify these objects.

## Arrays

Arrays are simply a storage scheme for multiple data objects of the same
type. Data objects are stored sequentially, often as an offset from a
pointer to the beginning of the array. Consider the following C code:

``` C
 x = array[25];
```

Which is identical to the following asm code:

``` asm
 mov ebx, $array
 mov eax, [ebx + 25]
 mov $x, eax
```

Now, consider the following example:

``` C
 int MyFunction1()
 {
    int array[20];
    ...
```

This (roughly) translates into the following asm pseudo-code:

``` asm
 :_MyFunction1
 push ebp
 mov ebp, esp
 sub esp, 80 ;the whole array is created on the stack!!!
 lea $array, [esp + 0] ;a pointer to the array is saved in the array variable
 ...
```

The entire array is created on the stack, and the pointer to the bottom
of the array is stored in the variable \"array\". An optimizing compiler
could ignore the last instruction, and simply refer to the array via a
+0 offset from esp (in this example), but we will do things verbosely.

Likewise, consider the following example:

``` C
 void MyFunction2()
 {
    char buffer[4];
    ...
```

This will translate into the following asm pseudo-code:

``` asm
 :_MyFunction2
 push ebp
 mov ebp, esp
 sub esp, 4
 lea $buffer, [esp + 0]
 ...
```

Which looks harmless enough. But, what if a program inadvertantly
accesses buffer\[4\]? what about buffer\[5\]? what about buffer\[8\]?
This is the makings of a buffer overflow vulnerability, and (might) will
be discussed in a later section. However, this section won\'t talk about
security issues, and instead will focus only on data structures.

### Spotting an Array on the Stack

To spot an array on the stack, look for large amounts of local storage
allocated on the stack (\"sub esp, 1000\", for example), and look for
large portions of that data being accessed by an offset from a different
register from esp. For instance:

``` asm
 :_MyFunction3
 push ebp
 mov ebp, esp
 sub esp, 256
 lea ebx, [esp + 0x00]
 mov [ebx + 0], 0x00
```

is a good sign of an array being created on the stack. Granted, an
optimizing compiler might just want to offset from esp instead, so you
will need to be careful.

### Spotting an Array in Memory

Arrays in memory, such as global arrays, or arrays which have initial
data (remember, initialized data is created in the .data section in
memory) and will be accessed as offsets from a hardcoded address in
memory:

``` asm
 :_MyFunction4
 push ebp
 mov ebp, esp
 mov esi, 0x77651004
 mov ebx, 0x00000000
 mov [esi + ebx], 0x00
```

It needs to be kept in mind that structures and classes might be
accessed in a similar manner, so the reverser needs to remember that all
the data objects in an array are of the same type, that they are
sequential, and they will often be handled in a loop of some sort. Also,
(and this might be the most important part), each elements in an array
may be accessed by a *variable offset from the base*.

Since most times an array is accessed through a computed index, not
through a constant, the compiler will likely use the following to access
an element of the array:

``` asm
 mov [ebx + eax], 0x00
```

If the array holds elements larger than 1 byte (for char), the index
will need to be multiplied by the size of the element, yielding code
similar to the following:

``` asm
 mov [ebx + eax * 4], 0x11223344   # access to an array of DWORDs, e.g.    arr[i] = 0x11223344
 ...
 mul eax, $20                      # access to an array of structs, each 20 bytes long
 lea edi, [ebx + eax]              # e.g.     ptr = &arr[i]
```

This pattern can be used to distinguish between accesses to arrays and
accesses to structure data members.

## Structures

All C programmers are going to be familiar with the following syntax:

``` C
 struct MyStruct
 {
    int FirstVar;
    double SecondVar;
    unsigned short int ThirdVar;
 }
```

It\'s called a **structure** (Pascal programmers may know a similar
concept as a \"record\").

Structures may be very big or very small, and they may contain all sorts
of different data. Structures may look very similar to arrays in memory,
but a few key points need to be remembered: structures do not need to
contain data fields of all the same type, structure fields are often
4-byte aligned (not sequential), and each element in a structure has its
own offset. It therefore makes no sense to reference a structure element
by a variable offset from the base.

Take a look at the following structure definition:

``` C
 struct MyStruct2
 {
    long value1;
    short value2;
    long value3;
 }
```

Assuming the pointer to the base of this structure is loaded into ebx,
we can access these members in one of two schemes:

+---+---+
| ` | ` |
| ` | ` |
| ` | ` |
|   |   |
| a | a |
| s | s |
| m | m |
|   |   |
| ; | ; |
| d | d |
| a | a |
| t | t |
| a | a |
|   |   |
| i | i |
| s | s |
|   |   |
| 3 | " |
| 2 | p |
| - | a |
| b | c |
| i | k |
| t | e |
|   | d |
| a | " |
| l |   |
| i | [ |
| g | e |
| n | b |
| e | x |
| d |   |
|   | + |
| [ |   |
| e | 0 |
| b | ] |
| x |   |
|   | ; |
| + | v |
|   | a |
| 0 | l |
| ] | u |
|   | e |
| ; | 1 |
| v |   |
| a | [ |
| l | e |
| u | b |
| e | x |
| 1 |   |
|   | + |
| [ |   |
| e | 4 |
| b | ] |
| x |   |
|   | ; |
| + | v |
|   | a |
| 4 | l |
| ] | u |
|   | e |
| ; | 2 |
| v |   |
| a | [ |
| l | e |
| u | b |
| e | x |
| 2 |   |
|   | + |
| [ |   |
| e | 6 |
| b | ] |
| x |   |
|   | ; |
| + | v |
|   | a |
| 8 | l |
| ] | u |
|   | e |
| ; | 3 |
| v | ` |
| a | ` |
| l | ` |
| u |   |
| e |   |
| 3 |   |
| ` |   |
| ` |   |
| ` |   |
+---+---+

The first arrangement is the most common, but it clearly leaves open an
entire memory word (2 bytes) at offset +6, which is not used at all.
Compilers occasionally allow the programmer to manually specify the
offset of each data member, but this isn\'t always the case. The second
example also has the benefit that the reverser can easily identify that
each data member in the structure is a different size.

Consider now the following function:

``` asm
 :_MyFunction
 push ebp
 mov ebp, esp
 lea ecx, SS:[ebp + 8]
 mov [ecx + 0], 0x0000000A
 mov [ecx + 4], ecx
 mov [ecx + 8], 0x0000000A
 mov esp, ebp
 pop ebp
```

The function clearly takes a pointer to a data structure as its first
argument. Also, each data member is the same size (4 bytes), so how can
we tell if this is an array or a structure? To answer that question, we
need to remember one important distinction between structures and
arrays: the elements in an array are all of the same type, the elements
in a structure do not need to be the same type. Given that rule, it is
clear that one of the elements in this structure is a pointer (it points
to the base of the structure itself!) and the other two fields are
loaded with the hex value 0x0A (10 in decimal), which is certainly not a
valid pointer on any system I have ever used. We can then partially
recreate the structure and the function code below:

``` C
 struct MyStruct3
 {
    long value1;
    void *value2;
    long value3;
 }

 void MyFunction2(struct MyStruct3 *ptr)
 {
    ptr->value1 = 10;
    ptr->value2 = ptr;
    ptr->value3 = 10;
 }
```

As a quick aside note, notice that this function doesn\'t load anything
into eax, and therefore it doesn\'t return a value.

## Advanced Structures

Lets say we have the following situation in a function:

``` asm
 :MyFunction1
 push ebp
 mov ebp, esp
 mov esi, [ebp + 8]
 lea ecx, SS:[esi + 8]
 ...
```

what is happening here? First, esi is loaded with the value of the
function\'s first parameter (ebp + 8). Then, ecx is loaded with a
pointer to the offset +8 from esi. It looks like we have 2 pointers
accessing the same data structure!

The function in question could easily be one of the following 2
prototypes:

``` C
 struct MyStruct1
 {
   DWORD value1;
   DWORD value2;
   struct MySubStruct1
   {
      ...
```

``` C
 struct MyStruct2
 {
    DWORD value1;
    DWORD value2;
    DWORD array[LENGTH];
    ...
```

one pointer offset from another pointer in a structure often means a
complex data structure. There are far too many combinations of
structures and arrays, however, so this wikibook will not spend too much
time on this subject.

## Identifying Structs and Arrays

Array elements and structure fields are both accessed as offsets from
the array/structure pointer. When disassembling, how do we tell these
data structures apart? Here are some pointers:

1.  Array elements are not meant to be accessed individually. Array
    elements are typically accessed using a variable offset
2.  Arrays are frequently accessed in a loop. Because arrays typically
    hold a series of similar data items, the best way to access them all
    is usually a loop. Specifically,
    `for(x = 0; x < length_of_array; x++)` style loops are often used to
    access arrays, although there can be others.
3.  All the elements in an array have the same data type.
4.  Struct fields are typically accessed using constant offsets.
5.  Struct fields are typically not accessed in order, and are also not
    accessed using loops.
6.  Struct fields are not typically all the same data type, or the same
    data width

## Linked Lists and Binary Trees

Two common structures used when programming are linked lists and binary
trees. These two structures in turn can be made more complicated in a
number of ways. Shown in the images below are examples of a linked list
structure and a binary tree structure.

+---+---+
| ! | ! |
| [ | [ |
| ] | ] |
| ( | ( |
| C | t |
| _ | r |
| l | e |
| a | e |
| n | - |
| g | d |
| u | a |
| a | t |
| g | a |
| e | - |
| _ | s |
| l | t |
| i | r |
| n | u |
| k | c |
| e | t |
| d | u |
| _ | r |
| l | e |
| i | . |
| s | s |
| t | v |
| . | g |
| p |   |
| n | " |
| g | t |
|   | r |
| " | e |
| C | e |
| _ | - |
| l | d |
| a | a |
| n | t |
| g | a |
| u | - |
| a | s |
| g | t |
| e | r |
| _ | u |
| l | c |
| i | t |
| n | u |
| k | r |
| e | e |
| d | . |
| _ | s |
| l | v |
| i | g |
| s | " |
| t | ) |
| . | { |
| p | w |
| n | i |
| g | d |
| " | t |
| ) | h |
| { | = |
| w | " |
| i | 3 |
| d | 0 |
| t | 0 |
| h | " |
| = | } |
| " |   |
| 4 |   |
| 0 |   |
| 0 |   |
| " |   |
| } |   |
+---+---+

Each node in a linked list or a binary tree contains some amount of
data, and a pointer (or pointers) to other nodes. Consider the following
asm code example:

``` asm
loop_top:
cmp [ebp + 0], 10
je loop_end
mov ebp, [ebp + 4]
jmp loop_top
loop_end:
```

At each loop iteration, a data value at \[ebp + 0\] is compared with the
value 10. If the two are equal, the loop is ended. If the two are not
equal, however, the pointer in ebp is updated with a pointer at an
offset from ebp, and the loop is continued. This is a classic
linked-loop search technique. This is analagous to the following C code:

``` c
struct node
{
  int data;
  struct node *next;
};

struct node *x;
...
while(x->data != 10)
{
  x = x->next;
}
```

Binary trees are the same, except two different pointers will be used
(the right and left branch pointers).


# X86 Disassembly/Objects and Classes

## Object-Oriented Programming

**Object-Oriented** (OO) programming provides for us a new unit of
program structure to contend with: the **Object**. This chapter will
look at disassembled classes from C++. This chapter will not deal
directly with COM, but it will work to set a lot of the groundwork for
future discussions in reversing COM components (Windows users only).

## Classes

A basic class that has not inherited anything can be broken into two
parts, the variables and the methods. The non-static variables are
shoved into a simple data structure while the methods are compiled and
called like every other function.

When you start adding in inheritance and polymorphism, things get a
little more complicated. For the purposes of simplicity, the structure
of an object will be described in terms of having no inheritance. At the
end, however, inheritance and polymorphism will be covered.

### Variables

All static variables defined in a class resides in the static region of
memory for the entire duration of the application. Every other variable
defined in the class is placed into a data structure known as an object.
Typically when the constructor is called, the variables are placed into
the object in sequential order, see **Figure 1**.

`<small>`{=html}A:`</small>`{=html}

``` cpp
class ABC123 {
public:
    int a, b, c;
    ABC123():a(1), b(2), c(3) {};
};
```

`<small>`{=html}B:`</small>`{=html}

``` asm
0x00200000  dd  1   ;int a
0x00200004  dd  2   ;int b
0x00200008  dd  3   ;int c
```

```{=html}
<table width=95%>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<small>`{=html}**Figure 1**: An example of what an object looks like in
memory`</br>`{=html} **Figure 1.A**: The definition for the class
\"ABC123.\" This class has three integers, a, b, and c. The constructor
sets \'a\' to equal 1, \'b\' to equal 2, and \'c\' to equal
3.`</br>`{=html} **Figure 1.B**: How the object ABC123 might be placed
in memory, ordering the variables from the class sequentially. At memory
address 0x00200000 there is a double word integer (32 bits) with a value
of 1, representing the variable \'a\'. Memory address 0x00200004 has a
double word integer with the value of 2, representing the variable
\'b\'. And at memory address 0x00200008 there is a double word integer
with a value of 3, representing the variable \'c\'.`</small>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
However, the compiler typically needs the variables to be separated into
sizes that are multiples of a word (2 bytes) in order to locate them.
Not all variables fit this requirement, namely char arrays; some unused
bits might be used pad the variables so they meet this size requirement.
This is illustrated in **Figure 2**.

`<small>`{=html}A:`</small>`{=html}

``` cpp
class ABC123{
public:
    int a;
    char b[3];
    double c;

    ABC123():a(1),c(3) { strcpy(b,"02"); };
};
```

`<small>`{=html}B:`</small>`{=html}

``` asm
0x00200000  dd  1       ;int a              ; offset = abc123 + 0*word_size
0x00200004  db  '0'     ;b[0] = '0'         ; offset = abc123 + 2*word_size
0x00200005  db  '2'     ;b[1] = '2'
0x00200006  db  0       ;b[2] = null
0x00200007  db  0       ;<= UNUSED BYTE
0x00200008  dd  0x00000000  ;double c,  lower 32 bits   ; offset = abc123 + 4*word_size
0x0020000C  dd  0x40080000  ;double c,  upper 32 bits
```

```{=html}
<table width=95%>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<small>`{=html}**Figure 2**: An example of an object having a padded
variable`</br>`{=html} **Figure 2.A**: A new definition for the class
\"ABC123.\" This class has one 32 bit integer, a. One 3 byte char array,
b. And one 64 bit double, c. The constrictor sets \'a\' to 1, \'b\' to
\"02\", and \'c\' to 3.`</br>`{=html} **Figure 2.B** Shows how ABC123
might be stored in memory. The first double word in the object is the
variable \'a\' at location 0x00200000 with a value of 1. Variable \'b\'
starts at the memory location 0x00200004. It\'s three bytes containing
three chars, \'0\',\'2\', and the null value. The next available
address, 0x00200007, is unused since it\'s not a multiple of a word. The
last variable \'c\', starts at 0x00200008 and it two double words (64
bits). It contains the value 3.`</small>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
In order for the application to access one of these object variables, an
object pointer needs to be offset to find the desired variable. The
offset of every variable is known by the compiler and written into the
object code wherever it\'s needed. **Figure 3** shows how to offset a
pointer to retrieve variables.

``` asm
;abc123 = pointer to object
mov eax, [abc123]   ;eax = &a   ;offset = abc123+0*word_size    = abc123
mov ebx, [abc123+4] ;ebx = &b   ;offset = abc123+2*word_size    = abc123+4
mov ecx, [abc123+8] ;ecx = &c   ;offset = abc123+4*word_size    = abc123+8
```

**Figure 3**: This shows how to offset a pointer to retrieve variables.
The first line places the address of variable \'a\' into eax. The second
line places the address of variable \'b\' into ebx. And the last line
places the variable \'c\' into ecx.

### Methods

At a low level, there is almost no difference between a function and a
method. When decompiling, it can sometimes be hard to tell a difference
between the two. They both reside in the text memory space, and both are
called the same way. An example of how a method is called can be seen in
**Figure 4**.

`<small>`{=html}A:`</small>`{=html}

``` cpp
//method call
abc123->foo(1, 2, 3);
```

`<small>`{=html}B:`</small>`{=html}

``` asm
push 3          ; int c
push 2          ; int b
push 1          ; int a
push [ebp-4]        ; the address of the object
call 0x00434125 ; call to method
```

```{=html}
<table width=95%>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<small>`{=html}**Figure 4**: A method call.`</br>`{=html} **Figure
4.A**: A method call in the C++ syntax. abc123 is a pointer to an object
that has a method, foo(). foo() is taking three integer arguments, 1, 2,
and 3.`</br>`{=html} **Figure 4.B** The same method call in x86
assembly. It takes four arguments, the address of the object and three
integers. The pointer to the object is at ebp-4 and the method is at
address 0x00434125. `</small>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
A notable characteristic in a method call is the address of the object
being passed in as an argument. This, however, is not a always a good
indicator. **Figure 5** shows function with the first argument being an
object passed in by reference. The result is function that looks
identical to a method call.

`<small>`{=html}A:`</small>`{=html}

``` cpp
//function call
foo(abc123, 1, 2, 3);
```

`<small>`{=html}B:`</small>`{=html}

``` asm
push 3          ; int c
push 2          ; int b
push 1          ; int a
push [ebp+4]        ; the address of the object
call 0x00498372 ; call to function
```

```{=html}
<table width=95%>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<small>`{=html}**Figure 5**: A function call.`</br>`{=html} **Figure
5.A:** A function call in the C++ syntax. foo() is taking four
arguments, one pointer and three integer arguments.`</br>`{=html}
**Figure 5.B:** The same function call in x86 assembly. It takes four
arguments, the address of the object and three integers. The pointer to
the object is at ebp-4 and the method is at address 0x00498372.
`</small>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
### Inheritance & Polymorphism

Inheritance and polymorphism completely changes the structure of a
class, the object no longer contains just variables, they also contain
pointers to the inherited methods. This is due to the fact that
polymorphism requires the address of a method or inner object to be
figured out at runtime.

Take **Figure 6** into consideration. How does the application know to
call D::one or C::one? The answer is that the compiler figures out a
convention in which to order variables and method pointers inside the
object such that when they\'re referenced, the offsets are the same for
any object that has inherited its methods and variables.

```{=html}
<center>
```
```{=html}
<table border=0 margin=0 padding=0 width=95%>
```
```{=html}
<tr>
```
```{=html}
<td>
```
``` cpp
A *obj[2];
obj[0] = new C();
obj[1] = new D();

for(int i=0; i<2; i++)
    obj[i]->one();
```

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<small>`{=html}**Figure 6**: A small C++ polymorphic loop that calls a
function, one. The classes C and D both inherit an abstract class, A.
The class A, for this code to work, must have a virtual method with the
name, \"one.\" `</small>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
```{=html}
</center>
```
The abstract class A acts as a blueprint for the compiler, defining an
expected structure for any class that inherits it. Every variable
defined in class A and every virtual method defined in A will have the
exact same offset for any of its children. **Figure 7** declares a
possible inheritance scheme as well as it structure in memory. Notice
how the offset to C::one is the same as D::one, and the offset to C\'s
copy of A::a is the same as D\'s copy. In this, our polymorphic loop can
just iterate through the array of pointers and know exactly where to
find each method.

`<small>`{=html}A:`</small>`{=html}

``` cpp
class A{
public:
    int a;
    virtual void one() = 0;
};
class B{
public:
    int b;
    int c;
    virtual void two() = 0;
};
class C: public A{
public:
    int d;
    void one();
};
class D: public A, public B{
public:
    int e;
    void one();
    void two();
};
```

`<small>`{=html}B:`</small>`{=html}

``` asm
;Object C
0x00200000  dd  0x00423848  ; address of C::one ;offset = 0*word_size
0x00200004  dd  1       ; C's copy of A::a  ;offset = 2*word_size
0x00200008  dd  4       ; C::d          ;offset = 4*word_size

;Object D
0x00200100  dd  0x00412348  ; address of D::one ;offset = 0*word_size
0x00200104  dd  1       ; D's copy of A::a  ;offset = 2*word_size
0x00200108  dd  0x00431255  ; address of D::two ;offset = 4*word_size
0x0020010C  dd  2       ; D's copy of B::b  ;offset = 6*word_size
0x00200110  dd  3       ; D's copy of B::c  ;offset = 8*word_size
0x00200114  dd  5       ; D::e          ;offset = 10*word_size
```

```{=html}
<table width=95%>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<small>`{=html}**Figure 7**: A polymorphic inheritance
scheme.`</br>`{=html} **Figure 7.A** defines the inheritance scheme. It
shows that class C inherits class A, and class D inherits class A and
class B.`</br>`{=html} **Figure 7.B** shows how the inheritance scheme
might be structured in memory. Class C\'s object has everything that was
declared in class A in the first two double words. The remainder of the
object was defined by class C. Class D\'s object also has everything
that was declared in class A in the first two double words. Then the
next three double words is everything declared in class B. And the last
double word is the variable defined by class D.`</small>`{=html}

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## Classes Vs. Structs