banner



Why Are Internal Registers Useful In Assembly Language?

x86 Associates Guide

Contents: Registers | Retentiveness and Addressing | Instructions | Calling Convention

This guide describes the basics of 32-bit x86 assembly language programming, covering a modest simply useful subset of the available instructions and assembler directives. In that location are several different assembly languages for generating x86 auto code. The one we will employ in CS216 is the Microsoft Macro Assembler (MASM) assembler. MASM uses the standard Intel syntax for writing x86 assembly lawmaking.

The full x86 instruction gear up is large and circuitous (Intel's x86 instruction fix manuals contain over 2900 pages), and we do not cover information technology all in this guide. For instance, in that location is a 16-scrap subset of the x86 instruction set. Using the xvi-bit programming model can exist quite complex. It has a segmented memory model, more restrictions on register usage, and and then on. In this guide, we will limit our attending to more modern aspects of x86 programming, and delve into the instruction set only in enough detail to get a basic experience for x86 programming.

Resources

  • Guide to Using Assembly in Visual Studio — a tutorial on building and debugging assembly code in Visual Studio
  • Intel x86 Instruction Prepare Reference
  • Intel'south Pentium Manuals (the full gory details)

Registers

Mod (i.e 386 and beyond) x86 processors accept eight 32-bit general purpose registers, equally depicted in Figure 1. The register names are generally historical. For instance, EAX used to be called the accumulator since it was used past a number of arithmetic operations, and ECX was known every bit the counter since it was used to hold a loop alphabetize. Whereas most of the registers have lost their special purposes in the mod instruction gear up, by convention, two are reserved for special purposes — the stack pointer (ESP) and the base pointer (EBP).

For the EAX, EBX, ECX, and EDX registers, subsections may be used. For instance, the to the lowest degree meaning 2 bytes of EAX tin can be treated as a 16-bit register called AX. The least significant byte of AX can be used as a single 8-bit register called AL, while the near meaning byte of AX can exist used as a single viii-bit register called AH. These names refer to the same physical register. When a two-byte quantity is placed into DX, the update affects the value of DH, DL, and EDX. These sub-registers are mainly hold-overs from older, 16-bit versions of the instruction gear up. Withal, they are sometimes convenient when dealing with data that are smaller than 32-$.25 (east.g. 1-byte ASCII characters).

When referring to registers in assembly language, the names are non case-sensitive. For example, the names EAX and eax refer to the same register.


Effigy one. x86 Registers

Memory and Addressing Modes

Declaring Static Data Regions

You can declare static data regions (analogous to global variables) in x86 assembly using special assembler directives for this purpose. Information declarations should be preceded by the .DATA directive. Post-obit this directive, the directives DB, DW, and DD tin can exist used to declare 1, 2, and four byte data locations, respectively. Declared locations can be labeled with names for later reference — this is like to declaring variables by proper name, but abides by some lower level rules. For instance, locations declared in sequence will be located in retentivity next to one another.

Case declarations:

.Data
var DB 64 ; Declare a byte, referred to as location var, containing the value 64.
var2 DB ? ; Declare an uninitialized byte, referred to as location var2.
DB ten ; Declare a byte with no label, containing the value 10. Its location is var2 + 1.
10 DW ? ; Declare a 2-byte uninitialized value, referred to equally location X.
Y DD 30000 ; Declare a 4-byte value, referred to equally location Y, initialized to 30000.

Unlike in high level languages where arrays can have many dimensions and are accessed by indices, arrays in x86 assembly linguistic communication are only a number of cells located contiguously in retentivity. An array can be alleged by merely listing the values, as in the first case below. Two other mutual methods used for declaring arrays of information are the DUP directive and the use of string literals. The DUP directive tells the assembler to indistinguishable an expression a given number of times. For case, 4 DUP(2) is equivalent to 2, 2, 2, 2.

Some examples:

Z DD 1, 2, iii ; Declare 3 4-byte values, initialized to ane, 2, and 3. The value of location Z + viii will be 3.
bytes DB 10 DUP(?) ; Declare 10 uninitialized bytes starting at location bytes.
arr DD 100 DUP(0) ; Declare 100 iv-byte words starting at location arr, all initialized to 0
str DB 'hello',0 ; Declare 6 bytes starting at the accost str, initialized to the ASCII character values for howdy and the null (0) byte.

Addressing Memory

Modern x86-compatible processors are capable of addressing up to ii32 bytes of retentiveness: retentivity addresses are 32-bits wide. In the examples above, where we used labels to refer to retentiveness regions, these labels are actually replaced by the assembler with 32-chip quantities that specify addresses in memory. In addition to supporting referring to retentiveness regions by labels (i.e. constant values), the x86 provides a flexible scheme for calculating and referring to memory addresses: upward to two of the 32-fleck registers and a 32-bit signed abiding can be added together to compute a memory address. One of the registers can exist optionally pre-multiplied by two, iv, or viii.

The addressing modes can exist used with many x86 instructions (we'll depict them in the next section). Hither we illustrate some examples using the mov instruction that moves data between registers and memory. This instruction has two operands: the first is the destination and the second specifies the source.

Some examples of mov instructions using address computations are:

mov eax, [ebx] ; Motion the 4 bytes in memory at the address contained in EBX into EAX
mov [var], ebx ; Move the contents of EBX into the 4 bytes at retention address var. (Note, var is a 32-bit constant).
mov eax, [esi-4] ; Move four bytes at retentivity accost ESI + (-4) into EAX
mov [esi+eax], cl ; Move the contents of CL into the byte at address ESI+EAX
mov edx, [esi+iv*ebx] ; Move the 4 bytes of data at accost ESI+four*EBX into EDX

Some examples of invalid accost calculations include:

mov eax, [ebx-ecx] ; Can simply add register values
mov [eax+esi+edi], ebx ; At most 2 registers in address computation

Size Directives

In full general, the intended size of the data item at a given memory accost can be inferred from the assembly code didactics in which it is referenced. For example, in all of the above instructions, the size of the retentivity regions could be inferred from the size of the register operand. When nosotros were loading a 32-bit register, the assembler could infer that the region of memory nosotros were referring to was iv bytes wide. When we were storing the value of a ane byte register to memory, the assembler could infer that nosotros wanted the address to refer to a unmarried byte in memory.

Withal, in some cases the size of a referred-to retentiveness region is ambiguous. Consider the instruction mov [ebx], ii. Should this instruction move the value 2 into the single byte at address EBX? Possibly it should motility the 32-flake integer representation of two into the 4-bytes starting at address EBX. Since either is a valid possible interpretation, the assembler must be explicitly directed as to which is right. The size directives BYTE PTR, Word PTR, and DWORD PTR serve this purpose, indicating sizes of ane, ii, and four bytes respectively.

For instance:

mov BYTE PTR [ebx], 2 ; Movement two into the single byte at the address stored in EBX.
mov WORD PTR [ebx], two ; Move the xvi-fleck integer representation of ii into the 2 bytes starting at the accost in EBX.
mov DWORD PTR [ebx], 2 ; Motion the 32-fleck integer representation of 2 into the 4 bytes starting at the accost in EBX.

Instructions

Machine instructions by and large fall into iii categories: information movement, arithmetic/logic, and control-menstruation. In this section, we will look at of import examples of x86 instructions from each category. This section should not be considered an exhaustive list of x86 instructions, but rather a useful subset. For a complete list, come across Intel's instruction set reference.

We use the following annotation:

<reg32> Any 32-fleck register (EAX, EBX, ECX, EDX, ESI, EDI, ESP, or EBP)
<reg16> Whatsoever 16-bit register (AX, BX, CX, or DX)
<reg8> Any 8-scrap annals (AH, BH, CH, DH, AL, BL, CL, or DL)
<reg> Any register
<mem> A memory address (e.1000., [eax], [var + four], or dword ptr [eax+ebx])
<con32> Whatever 32-flake constant
<con16> Any sixteen-bit constant
<con8> Any eight-bit abiding
<con> Whatever viii-, xvi-, or 32-bit constant

Information Motion Instructions

mov — Movement (Opcodes: 88, 89, 8A, 8B, 8C, 8E, ...)

The mov instruction copies the data item referred to by its second operand (i.eastward. annals contents, memory contents, or a constant value) into the location referred to by its first operand (i.due east. a annals or memory). While register-to-register moves are possible, direct retentivity-to-memory moves are not. In cases where retention transfers are desired, the source memory contents must first be loaded into a register, so tin be stored to the destination memory address.

Syntax
mov <reg>,<reg>
mov <reg>,<mem>
mov <mem>,<reg>
mov <reg>,<const>
mov <mem>,<const>

Examples
mov eax, ebx — copy the value in ebx into eax
mov byte ptr [var], five — store the value 5 into the byte at location var

button — Push stack (Opcodes: FF, 89, 8A, 8B, 8C, 8E, ...)

The button instruction places its operand onto the top of the hardware supported stack in memory. Specifically, push first decrements ESP by 4, then places its operand into the contents of the 32-bit location at accost [ESP]. ESP (the stack pointer) is decremented by push since the x86 stack grows downward - i.e. the stack grows from high addresses to lower addresses. Syntax
button <reg32>
push <mem>
push <con32>

Examples
push eax — push eax on the stack
push [var] — push the 4 bytes at accost var onto the stack

pop — Pop stack

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.east. annals or memory location). Information technology first moves the iv bytes located at memory location [SP] into the specified register or memory location, and so increments SP by 4.

Syntax
pop <reg32>
pop <mem>

Examples
pop edi — pop the summit element of the stack into EDI.
pop [ebx] — pop the top element of the stack into memory at the four bytes starting at location EBX.

lea — Load effective address

The lea teaching places the address specified by its second operand into the register specified by its outset operand. Annotation, the contents of the memory location are not loaded, only the effective address is computed and placed into the register. This is useful for obtaining a pointer into a memory region.

Syntax
lea <reg32>,<mem>

Examples
lea edi, [ebx+4*esi] — the quantity EBX+4*ESI is placed in EDI.
lea eax, [var] — the value in var is placed in EAX.
lea eax, [val] — the value val is placed in EAX.

Arithmetic and Logic Instructions

add — Integer Addition

The add instruction adds together its two operands, storing the effect in its first operand. Note, whereas both operands may be registers, at most one operand may be a memory location. Syntax
add together <reg>,<reg>
add <reg>,<mem>
add <mem>,<reg>
add together <reg>,<con>
add <mem>,<con>
Examples
add together eax, 10 — EAX ← EAX + ten
add BYTE PTR [var], ten — add 10 to the single byte stored at retentivity accost var

sub — Integer Subtraction

The sub pedagogy stores in the value of its get-go operand the result of subtracting the value of its 2nd operand from the value of its first operand. As with add Syntax
sub <reg>,<reg>
sub <reg>,<mem>
sub <mem>,<reg>
sub <reg>,<con>
sub <mem>,<con>
Examples
sub al, ah — AL ← AL - AH
sub eax, 216 — subtract 216 from the value stored in EAX

inc, dec — Increment, Decrement

The inc instruction increments the contents of its operand by one. The dec teaching decrements the contents of its operand by one.

Syntax
inc <reg>
inc <mem>
dec <reg>
december <mem>

Examples
december eax — subtract one from the contents of EAX.
inc DWORD PTR [var] — add one to the 32-bit integer stored at location var

imul — Integer Multiplication

The imul instruction has ii bones formats: 2-operand (first 2 syntax listings above) and iii-operand (last two syntax listings to a higher place). The ii-operand form multiplies its two operands together and stores the event in the kickoff operand. The consequence (i.e. start) operand must be a register. The 3 operand form multiplies its second and 3rd operands together and stores the result in its kickoff operand. Once more, the event operand must exist a register. Furthermore, the tertiary operand is restricted to being a abiding value. Syntax
imul <reg32>,<reg32>
imul <reg32>,<mem>
imul <reg32>,<reg32>,<con>
imul <reg32>,<mem>,<con>

Examples

imul eax, [var] — multiply the contents of EAX by the 32-bit contents of the memory location var. Store the result in EAX.

imul esi, edi, 25 — ESI → EDI * 25

idiv — Integer Division

The idiv educational activity divides the contents of the 64 bit integer EDX:EAX (synthetic past viewing EDX as the most meaning four bytes and EAX as the to the lowest degree meaning four bytes) by the specified operand value. The caliber result of the division is stored into EAX, while the remainder is placed in EDX.

Syntax
idiv <reg32>
idiv <mem>

Examples

idiv ebx — split up the contents of EDX:EAX past the contents of EBX. Place the quotient in EAX and the remainder in EDX.

idiv DWORD PTR [var] — divide the contents of EDX:EAX past the 32-chip value stored at memory location var. Place the quotient in EAX and the remainder in EDX.

and, or, xor — Bitwise logical and, or and exclusive or

These instructions perform the specified logical operation (logical bitwise and, or, and exclusive or, respectively) on their operands, placing the result in the first operand location.

Syntax
and <reg>,<reg>
and <reg>,<mem>
and <mem>,<reg>
and <reg>,<con>
and <mem>,<con>

or <reg>,<reg>
or <reg>,<mem>
or <mem>,<reg>
or <reg>,<con>
or <mem>,<con>

xor <reg>,<reg>
xor <reg>,<mem>
xor <mem>,<reg>
xor <reg>,<con>
xor <mem>,<con>

Examples
and eax, 0fH — articulate all but the terminal 4 bits of EAX.
xor edx, edx — set up the contents of EDX to goose egg.

not — Bitwise Logical Not

Logically negates the operand contents (that is, flips all fleck values in the operand).

Syntax
not <reg>
not <mem>

Instance
not BYTE PTR [var] — negate all bits in the byte at the memory location var.

neg — Negate

Performs the two'southward complement negation of the operand contents.

Syntax
neg <reg>
neg <mem>

Case
neg eax — EAX → - EAX

shl, shr — Shift Left, Shift Right

These instructions shift the bits in their first operand'south contents left and right, padding the resulting empty bit positions with zeros. The shifted operand tin can be shifted up to 31 places. The number of bits to shift is specified past the 2d operand, which tin can exist either an 8-flake constant or the register CL. In either instance, shifts counts of greater so 31 are performed modulo 32.

Syntax
shl <reg>,<con8>
shl <mem>,<con8>
shl <reg>,<cl>
shl <mem>,<cl>

shr <reg>,<con8>
shr <mem>,<con8>
shr <reg>,<cl>
shr <mem>,<cl>

Examples

shl eax, 1 — Multiply the value of EAX past 2 (if the most significant flake is 0)

shr ebx, cl — Store in EBX the flooring of issue of dividing the value of EBX by ii north wheredue north is the value in CL.

Control Menstruum Instructions

The x86 processor maintains an pedagogy pointer (IP) annals that is a 32-scrap value indicating the location in memory where the electric current instruction starts. Ordinarily, information technology increments to indicate to the next teaching in memory begins later execution an instruction. The IP register cannot be manipulated directly, but is updated implicitly by provided control period instructions.

We employ the annotation <characterization> to refer to labeled locations in the programme text. Labels tin be inserted anywhere in x86 assembly code text by entering a label name followed past a colon. For case,

            mov esi, [ebp+eight] begin: xor ecx, ecx        mov eax, [esi]          

The second pedagogy in this lawmaking fragment is labeled begin. Elsewhere in the code, we tin can refer to the memory location that this educational activity is located at in memory using the more convenient symbolic name begin. This label is just a convenient way of expressing the location instead of its 32-bit value.

jmp — Jump

Transfers program control flow to the instruction at the retention location indicated by the operand.

Syntax
jmp <label>

Case
jmp brainstorm — Jump to the instruction labeled begin.

jstatus — Conditional Jump

These instructions are conditional jumps that are based on the status of a fix of condition codes that are stored in a special register called the automobile status word. The contents of the auto status discussion include information almost the last arithmetics functioning performed. For example, i fleck of this discussion indicates if the last result was nil. Another indicates if the last result was negative. Based on these status codes, a number of conditional jumps can be performed. For example, the jz pedagogy performs a jump to the specified operand label if the result of the last arithmetics functioning was aught. Otherwise, command gain to the next instruction in sequence.

A number of the conditional branches are given names that are intuitively based on the concluding operation performed beingness a special compare instruction, cmp (see below). For example, conditional branches such every bit jle and jne are based on start performing a cmp operation on the desired operands.

Syntax
je <label> (leap when equal)
jne <label> (jump when not equal)
jz <characterization> (leap when last result was null)
jg <label> (spring when greater than)
jge <label> (jump when greater than or equal to)
jl <characterization> (jump when less than)
jle <label> (jump when less than or equal to)

Example
cmp eax, ebx
jle done

If the contents of EAX are less than or equal to the contents of EBX, leap to the label washed. Otherwise, go on to the next teaching.

cmp — Compare

Compare the values of the ii specified operands, setting the condition codes in the automobile condition word accordingly. This pedagogy is equivalent to the sub didactics, except the event of the subtraction is discarded instead of replacing the starting time operand.

Syntax
cmp <reg>,<reg>
cmp <reg>,<mem>
cmp <mem>,<reg>
cmp <reg>,<con>

Example
cmp DWORD PTR [var], 10
jeq loop

If the 4 bytes stored at location var are equal to the 4-byte integer constant 10, jump to the location labeled loop.

call, ret — Subroutine call and return

These instructions implement a subroutine call and return. The call pedagogy showtime pushes the current code location onto the hardware supported stack in memory (see the push button instruction for details), and and then performs an unconditional bound to the lawmaking location indicated past the characterization operand. Unlike the simple jump instructions, the call teaching saves the location to return to when the subroutine completes.

The ret instruction implements a subroutine return mechanism. This instruction beginning pops a code location off the hardware supported in-memory stack (see the pop education for details). Information technology then performs an unconditional jump to the retrieved code location.

Syntax
phone call <label>
ret

Calling Convention

To allow separate programmers to share lawmaking and develop libraries for use by many programs, and to simplify the use of subroutines in full general, programmers typically adopt a common calling convention. The calling convention is a protocol virtually how to call and render from routines. For case, given a set of calling convention rules, a programmer need not examine the definition of a subroutine to determine how parameters should be passed to that subroutine. Furthermore, given a set of calling convention rules, loftier-level linguistic communication compilers tin exist fabricated to follow the rules, thus allowing hand-coded assembly language routines and loftier-level linguistic communication routines to call ane another.

In practise, many calling conventions are possible. Nosotros will employ the widely used C language calling convention. Post-obit this convention will permit you to write assembly linguistic communication subroutines that are safely callable from C (and C++) code, and volition likewise enable y'all to phone call C library functions from your associates language code.

The C calling convention is based heavily on the use of the hardware-supported stack. Information technology is based on the push, pop, call, and ret instructions. Subroutine parameters are passed on the stack. Registers are saved on the stack, and local variables used by subroutines are placed in retentiveness on the stack. The vast majority of high-level procedural languages implemented on most processors have used like calling conventions.

The calling convention is cleaved into two sets of rules. The first fix of rules is employed by the caller of the subroutine, and the second prepare of rules is observed by the author of the subroutine (the callee). It should be emphasized that mistakes in the observance of these rules quickly result in fatal program errors since the stack volition be left in an inconsistent land; thus meticulous care should be used when implementing the phone call convention in your own subroutines.

>
Stack during Subroutine Call
[Thanks to Maxence Faldor for providing a right effigy and to James Peterson for finding and fixing the issues in the original version of this figure!]

A practiced way to visualize the operation of the calling convention is to draw the contents of the nearby region of the stack during subroutine execution. The image above depicts the contents of the stack during the execution of a subroutine with three parameters and three local variables. The cells depicted in the stack are 32-fleck wide retention locations, thus the retention addresses of the cells are 4 bytes apart. The first parameter resides at an offset of 8 bytes from the base pointer. Higher up the parameters on the stack (and below the base arrow), the phone call instruction placed the return address, thus leading to an extra iv bytes of offset from the base pointer to the outset parameter. When the ret instruction is used to render from the subroutine, it volition jump to the return address stored on the stack.

Caller Rules

To make a subrouting call, the caller should:

  1. Earlier calling a subroutine, the caller should save the contents of certain registers that are designated caller-saved. The caller-saved registers are EAX, ECX, EDX. Since the called subroutine is immune to alter these registers, if the caller relies on their values after the subroutine returns, the caller must button the values in these registers onto the stack (so they can be restore later on the subroutine returns.
  2. To pass parameters to the subroutine, button them onto the stack earlier the phone call. The parameters should be pushed in inverted gild (i.east. last parameter first). Since the stack grows downwardly, the start parameter will exist stored at the lowest accost (this inversion of parameters was historically used to permit functions to exist passed a variable number of parameters).
  3. To call the subroutine, utilise the call instruction. This teaching places the return address on top of the parameters on the stack, and branches to the subroutine lawmaking. This invokes the subroutine, which should follow the callee rules below.

Subsequently the subroutine returns (immediately following the call instruction), the caller tin wait to observe the return value of the subroutine in the register EAX. To restore the machine state, the caller should:

  1. Remove the parameters from stack. This restores the stack to its country before the call was performed.
  2. Restore the contents of caller-saved registers (EAX, ECX, EDX) by popping them off of the stack. The caller can presume that no other registers were modified past the subroutine.

Example
The code beneath shows a role phone call that follows the caller rules. The caller is calling a part _myFunc that takes iii integer parameters. Showtime parameter is in EAX, the second parameter is the constant 216; the third parameter is in retentivity location var.

push [var] ; Push last parameter beginning push 216   ; Push the second parameter button eax   ; Push first parameter terminal  call _myFunc ; Phone call the office (presume C naming)  add esp, 12          

Note that later on the call returns, the caller cleans up the stack using the add educational activity. Nosotros have 12 bytes (3 parameters * 4 bytes each) on the stack, and the stack grows down. Thus, to get rid of the parameters, nosotros can simply add 12 to the stack pointer.

The result produced by _myFunc is now bachelor for utilise in the register EAX. The values of the caller-saved registers (ECX and EDX), may take been changed. If the caller uses them later on the telephone call, it would accept needed to save them on the stack before the call and restore them after it.

Callee Rules

The definition of the subroutine should adhere to the following rules at the commencement of the subroutine:

  1. Push the value of EBP onto the stack, and and then copy the value of ESP into EBP using the following instructions:
                  button ebp     mov  ebp, esp            
    This initial activeness maintains the base pointer, EBP. The base of operations pointer is used past convention equally a point of reference for finding parameters and local variables on the stack. When a subroutine is executing, the base of operations pointer holds a copy of the stack pointer value from when the subroutine started executing. Parameters and local variables will always be located at known, constant offsets away from the base pointer value. We push the old base pointer value at the beginning of the subroutine so that we can later restore the advisable base pointer value for the caller when the subroutine returns. Remember, the caller is not expecting the subroutine to change the value of the base arrow. Nosotros then motion the stack pointer into EBP to obtain our indicate of reference for accessing parameters and local variables.
  2. Side by side, allocate local variables by making space on the stack. Recollect, the stack grows down, then to make space on the top of the stack, the stack pointer should be decremented. The amount by which the stack arrow is decremented depends on the number and size of local variables needed. For instance, if iii local integers (4 bytes each) were required, the stack arrow would need to be decremented by 12 to make space for these local variables (i.east., sub esp, 12). As with parameters, local variables will exist located at known offsets from the base pointer.
  3. Next, save the values of the callee-saved registers that will exist used past the role. To salvage registers, push them onto the stack. The callee-saved registers are EBX, EDI, and ESI (ESP and EBP volition also be preserved past the calling convention, just demand not be pushed on the stack during this step).

After these iii actions are performed, the body of the subroutine may go on. When the subroutine is returns, information technology must follow these steps:

  1. Go out the render value in EAX.
  2. Restore the old values of whatsoever callee-saved registers (EDI and ESI) that were modified. The register contents are restored by popping them from the stack. The registers should be popped in the changed club that they were pushed.
  3. Deallocate local variables. The obvious mode to do this might be to add the appropriate value to the stack pointer (since the infinite was allocated by subtracting the needed amount from the stack pointer). In practice, a less error-decumbent way to deallocate the variables is to move the value in the base pointer into the stack arrow: mov esp, ebp. This works because the base pointer always contains the value that the stack pointer independent immediately prior to the allotment of the local variables.
  4. Immediately before returning, restore the caller's base pointer value past popping EBP off the stack. Recall that the first affair we did on entry to the subroutine was to push the base of operations arrow to save its old value.
  5. Finally, return to the caller past executing a ret instruction. This instruction will notice and remove the appropriate return address from the stack.

Note that the callee'southward rules fall cleanly into two halves that are basically mirror images of one another. The commencement half of the rules apply to the kickoff of the function, and are commonly said to define the prologue to the office. The latter half of the rules utilise to the end of the role, and are thus usually said to define the epilogue of the function.

Instance
Here is an instance function definition that follows the callee rules:

.486 .MODEL FLAT .CODE PUBLIC _myFunc _myFunc PROC   ; Subroutine Prologue   push ebp     ; Save the sometime base pointer value.   mov ebp, esp ; Set the new base pointer value.   sub esp, 4   ; Make room for one four-byte local variable.   push button edi     ; Save the values of registers that the part   push esi     ; volition modify. This function uses EDI and ESI.   ; (no demand to save EBX, EBP, or ESP)    ; Subroutine Body   mov eax, [ebp+8]   ; Move value of parameter 1 into EAX   mov esi, [ebp+12]  ; Move value of parameter 2 into ESI   mov edi, [ebp+16]  ; Move value of parameter 3 into EDI    mov [ebp-4], edi   ; Motility EDI into the local variable   add together [ebp-4], esi   ; Add ESI into the local variable   add eax, [ebp-4]   ; Add the contents of the local variable                      ; into EAX (concluding upshot)    ; Subroutine Epilogue    popular esi      ; Recover annals values   pop  edi   mov esp, ebp ; Deallocate local variables   pop ebp ; Restore the caller'south base arrow value   ret _myFunc ENDP Terminate          

The subroutine prologue performs the standard actions of saving a snapshot of the stack pointer in EBP (the base pointer), allocating local variables past decrementing the stack pointer, and saving register values on the stack.

In the trunk of the subroutine we can meet the use of the base of operations arrow. Both parameters and local variables are located at constant offsets from the base of operations pointer for the duration of the subroutines execution. In item, we notice that since parameters were placed onto the stack before the subroutine was called, they are always located beneath the base pointer (i.e. at higher addresses) on the stack. The first parameter to the subroutine tin can always be found at memory location EBP + 8, the second at EBP + 12, the third at EBP + sixteen. Similarly, since local variables are allocated after the base pointer is set, they always reside higher up the base of operations pointer (i.due east. at lower addresses) on the stack. In particular, the offset local variable is always located at EBP - 4, the second at EBP - 8, and then on. This conventional use of the base pointer allows us to quickly place the use of local variables and parameters within a function body.

The office epilogue is basically a mirror image of the function prologue. The caller's annals values are recovered from the stack, the local variables are deallocated by resetting the stack arrow, the caller's base pointer value is recovered, and the ret instruction is used to return to the appropriate lawmaking location in the caller.

Using these Materials

These materials are released under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 U.s.a. License. We are delighted when people desire to use or suit the course materials we developed, and you are welcome to reuse and adapt these materials for whatsoever not-commercial purposes (if you would like to employ them for a commercial purpose, please contact David Evans for more information). If you do adapt or use these materials, please include a credit like "Adapted from materials developed for University of Virginia cs216 past David Evans. This guide was revised for cs216 by David Evans, based on materials originally created past Adam Ferrari many years agone, and since updated past Alan Batson, Mike Lack, and Anita Jones." and a link back to this page.


Source: http://cs.virginia.edu/~evans/cs216/guides/x86.html

Posted by: fosterrismustriog.blogspot.com

0 Response to "Why Are Internal Registers Useful In Assembly Language?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel