banner



How To Get Direct Value From Register Assembly

x86 Assembly Guide

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

This is a version adapted by Quentin Carbonneaux from David Evans' original document. The syntax was changed from Intel to AT&T, the standard syntax on UNIX systems, and the HTML code was purified.

This guide describes the basics of 32-fleck x86 assembly language programming, roofing a small merely useful subset of the available instructions and assembler directives. There are several dissimilar assembly languages for generating x86 automobile code. The ane we volition employ in CS421 is the GNU Assembler (gas) assembler. We will uses the standard AT&T syntax for writing x86 associates lawmaking.

The full x86 instruction fix is large and complex (Intel'due south x86 pedagogy ready manuals contain over 2900 pages), and nosotros do not encompass it all in this guide. For case, at that place is a 16-bit subset of the x86 pedagogy set. Using the 16-bit programming model can exist quite complex. Information technology has a segmented memory model, more restrictions on annals usage, and then on. In this guide, we will limit our attention to more than modern aspects of x86 programming, and delve into the pedagogy set simply in enough detail to get a basic experience for x86 programming.

Registers

Modernistic (i.due east 386 and across) x86 processors have eight 32-chip general purpose registers, as depicted in Figure 1. The register names are mostly historical. For example, EAX used to exist called the accumulator since information technology was used past a number of arithmetic operations, and ECX was known equally the counter since it was used to hold a loop index. Whereas most of the registers accept lost their special purposes in the modernistic instruction set up, past 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 case, the least significant 2 bytes of EAX tin can be treated every bit a 16-scrap register called AX. The to the lowest degree meaning byte of AX can be used equally a single 8-scrap register called AL, while the most significant byte of AX can be used as a unmarried 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-fleck versions of the educational activity set. Yet, they are sometimes convenient when dealing with information that are smaller than 32-bits (east.one thousand. 1-byte ASCII characters).


Figure 1. x86 Registers

Retentivity and Addressing Modes

Declaring Static Information Regions

You lot can declare static data regions (analogous to global variables) in x86 assembly using special assembler directives for this purpose. Data declarations should be preceded by the .data directive. Post-obit this directive, the directives .byte, .short, and .long can exist used to declare one, ii, and four byte information locations, respectively. To refer to the accost of the information created, we can characterization them. Labels are very useful and versatile in assembly, they give names to memory locations that will exist figured out later past the assembler or the linker. This is similar to declaring variables by name, but abides by some lower level rules. For case, locations declared in sequence will be located in retention side by side to one some other.

Case declarations:

.data
var:
.byte 64 /* Declare a byte, referred to as location var, containing the value 64. */
.byte ten /* Declare a byte with no label, containing the value 10. Its location is var + i. */
x:
.short 42 /* Declare a two-byte value initialized to 42, referred to as location x. */
y:
.long 30000 /* Declare a four-byte value, referred to every bit location y, initialized to 30000. */

Unlike in high level languages where arrays can take many dimensions and are accessed by indices, arrays in x86 assembly language are simply a number of cells located contiguously in retention. An array tin exist declared by just listing the values, every bit in the kickoff example beneath. For the special case of an array of bytes, string literals tin can be used. In case a large area of memory is filled with zeroes the .zero directive can exist used.

Some examples:

southward:
.long 1, 2, 3 /* Declare three four-byte values, initialized to 1, ii, and iii.
The value at location s + 8 will be three. */
barr:
.zero x /* Declare 10 bytes starting at location barr, initialized to 0. */
str:
.string "hello" /* Declare vi bytes starting at the accost str initialized to
the ASCII character values for hello followed by a nul (0) byte. */

Addressing Memory

Modern x86-compatible processors are capable of addressing up to 232 bytes of memory: memory addresses are 32-bits wide. In the examples to a higher place, where we used labels to refer to memory regions, these labels are really replaced by the assembler with 32-scrap quantities that specify addresses in memory. In improver to supporting referring to memory regions by labels (i.e. constant values), the x86 provides a flexible scheme for computing and referring to memory addresses: up to two of the 32-flake registers and a 32-scrap signed constant can be added together to compute a retention address. Ane of the registers tin can be optionally pre-multiplied by two, iv, or 8.

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

Some examples of mov instructions using accost computations are:

mov (%ebx), %eax /* Load iv bytes from the memory address in EBX into EAX. */
mov %ebx, var(,1) /* Move the contents of EBX into the 4 bytes at retentivity address var.
(Note, var is a 32-fleck constant). */
mov -four(%esi), %eax /* Motion iv bytes at retentiveness address ESI + (-4) into EAX. */
mov %cl, (%esi,%eax,ane) /* Movement the contents of CL into the byte at address ESI+EAX. */
mov (%esi,%ebx,4), %edx /* Move the 4 bytes of data at accost ESI+iv*EBX into EDX. */

Some examples of invalid address calculations include:

mov (%ebx,%ecx,-one), %eax /* Tin only add annals values. */
mov %ebx, (%eax,%esi,%edi,1) /* At most ii registers in address computation. */

Performance Suffixes

In general, the intended size of the of the information item at a given retention address can exist inferred from the assembly code pedagogy in which it is referenced. For case, in all of the in a higher place instructions, the size of the memory regions could be inferred from the size of the annals operand. When we were loading a 32-bit register, the assembler could infer that the region of retention nosotros were referring to was four bytes wide. When we were storing the value of a one byte register to memory, the assembler could infer that we wanted the address to refer to a unmarried byte in memory.

Nevertheless, in some cases the size of a referred-to retentivity region is ambiguous. Consider the instruction mov $two, (%ebx). Should this educational activity motility the value 2 into the unmarried byte at address EBX? Perhaps it should motility the 32-bit 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 prefixes b, due west, and l serve this purpose, indicating sizes of 1, 2, and four bytes respectively.

For instance:

movb $2, (%ebx) /* Move 2 into the unmarried byte at the address stored in EBX. */
movw $ii, (%ebx) /* Move the sixteen-scrap integer representation of ii into the 2 bytes starting at the address in EBX. */
movl $2, (%ebx) /* Move the 32-bit integer representation of two into the 4 bytes starting at the address in EBX. */

Instructions

Machine instructions more often than not fall into three categories: data movement, arithmetic/logic, and command-flow. In this department, we will expect at important examples of x86 instructions from each category. This section should non exist considered an exhaustive list of x86 instructions, but rather a useful subset. For a complete list, see Intel's instruction set reference.

We utilise the following notation:

<reg32> Any 32-bit annals (%eax, %ebx, %ecx, %edx, %esi, %edi, %esp, or %ebp)
<reg16> Any 16-bit register (%ax, %bx, %cx, or %dx)
<reg8> Any eight-fleck register (%ah, %bh, %ch, %dh, %al, %bl, %cl, or %dl)
<reg> Any register
<mem> A memory address (eastward.g., (%eax), 4+var(,1), or (%eax,%ebx,i))
<con32> Any 32-fleck immediate
<con16> Any 16-bit immediate
<con8> Any 8-bit firsthand
<con> Whatsoever viii-, xvi-, or 32-bit immediate

In associates language, all the labels and numeric constants used as immediate operands (i.e. not in an accost calculation like 3(%eax,%ebx,8)) are always prefixed by a dollar sign. When needed, hexadecimal note can be used with the 0x prefix (e.g. $0xABC). Without the prefix, numbers are interpreted in the decimal basis.

Data Motion Instructions

mov — Move

The mov instruction copies the data detail referred to past its first operand (i.eastward. annals contents, retentivity contents, or a constant value) into the location referred to by its second operand (i.e. a annals or retentivity). While register-to-register moves are possible, directly memory-to-retentivity moves are not. In cases where retention transfers are desired, the source retentivity contents must outset be loaded into a register, then can be stored to the destination memory address.

Syntax
mov <reg>, <reg>
mov <reg>, <mem>
mov <mem>, <reg>
mov <con>, <reg>
mov <con>, <mem>

Examples
mov %ebx, %eax — copy the value in EBX into EAX
movb $v, var(,ane) — store the value 5 into the byte at location var

push — Push on stack

The push pedagogy places its operand onto the meridian of the hardware supported stack in retentiveness. Specifically, button outset decrements ESP past 4, then places its operand into the contents of the 32-bit location at address (%esp). ESP (the stack pointer) is decremented by button since the x86 stack grows downwardly — i.e. the stack grows from loftier addresses to lower addresses.

Syntax
button <reg32>
button <mem>
push button <con32>

Examples
push %eax — push eax on the stack
push var(,ane) — push the 4 bytes at address var onto the stack

pop — Pop from stack

The popular instruction removes the 4-byte data element from the acme of the hardware-supported stack into the specified operand (i.e. register or retention location). It offset moves the 4 bytes located at memory location (%esp) into the specified register or memory location, and and so increments ESP by 4.

Syntax
popular <reg32>
popular <mem>

Examples
pop %edi — popular the top element of the stack into EDI.
pop (%ebx) — pop the height element of the stack into retentiveness at the 4 bytes starting at location EBX.

lea — Load effective address

The lea educational activity places the address specified by its first operand into the annals specified by its second operand. Note, the contents of the retention 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 or to perform simple arithmetic operations.

Syntax
lea <mem>, <reg32>

Examples
lea (%ebx,%esi,8), %edi — the quantity EBX+8*ESI is placed in EDI.
lea val(,1), %eax — the value val is placed in EAX.

Arithmetic and Logic Instructions

add together — Integer addition

The add together instruction adds together its two operands, storing the result in its second operand. Notation, whereas both operands may be registers, at well-nigh one operand may exist a retention location.

Syntax
add <reg>, <reg>
add together <mem>, <reg>
add <reg>, <mem>
add <con>, <reg>
add <con>, <mem>

Examples
add together $10, %eax — EAX is prepare to EAX + ten
addb $10, (%eax) — add ten to the single byte stored at retention address stored in EAX

sub — Integer subtraction

The sub instruction stores in the value of its second operand the result of subtracting the value of its beginning operand from the value of its 2nd operand. As with add, whereas both operands may be registers, at almost 1 operand may be a memory location.

Syntax
sub <reg>, <reg>
sub <mem>, <reg>
sub <reg>, <mem>
sub <con>, <reg>
sub <con>, <mem>

Examples
sub %ah, %al — AL is prepare to AL - AH
sub $216, %eax — subtract 216 from the value stored in EAX

inc, dec — Increment, Decrement

The inc instruction increments the contents of its operand by one. The december instruction decrements the contents of its operand past 1.

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

Examples
december %eax — subtract i from the contents of EAX
incl var(,1) — add one to the 32-bit integer stored at location var

imul — Integer multiplication

The imul education has two bones formats: 2-operand (offset two syntax listings in a higher place) and iii-operand (last two syntax listings higher up).

The 2-operand class multiplies its two operands together and stores the result in the 2d operand. The result (i.e. second) operand must be a register.

The three operand form multiplies its second and third operands together and stores the outcome in its last operand. Again, the outcome operand must be a register. Furthermore, the beginning operand is restricted to being a constant value.

Syntax
imul <reg32>, <reg32>
imul <mem>, <reg32>
imul <con>, <reg32>, <reg32>
imul <con>, <mem>, <reg32>

Examples

imul (%ebx), %eax — multiply the contents of EAX past the 32-bit contents of the retention at location EBX. Shop the result in EAX.

imul $25, %edi, %esi — ESI is ready to EDI * 25

idiv — Integer division

The idiv education divides the contents of the 64 chip integer EDX:EAX (synthetic by viewing EDX every bit the most significant four bytes and EAX every bit the least significant four bytes) past the specified operand value. The quotient result of the partition is stored into EAX, while the remainder is placed in EDX.

Syntax
idiv <reg32>
idiv <mem>

Examples

idiv %ebx — carve up the contents of EDX:EAX past the contents of EBX. Place the quotient in EAX and the residue in EDX.

idivw (%ebx) — divide the contents of EDX:EAS by the 32-bit value stored at the memory location in EBX. Place the caliber in EAX and the remainder in EDX.

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

These instructions perform the specified logical functioning (logical bitwise and, or, and exclusive or, respectively) on their operands, placing the result in the get-go operand location.

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

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

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

Examples
and $0x0f, %eax — clear all but the last 4 bits of EAX.
xor %edx, %edx — gear up the contents of EDX to zero.

not — Bitwise logical not

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

Syntax
not <reg>
non <mem>

Example
not %eax — flip all the $.25 of EAX

neg — Negate

Performs the ii's complement negation of the operand contents.

Syntax
neg <reg>
neg <mem>

Example
neg %eax — EAX is fix to (- EAX)

shl, shr — Shift left and right

These instructions shift the bits in their first operand's contents left and correct, padding the resulting empty fleck positions with zeros. The shifted operand can be shifted up to 31 places. The number of bits to shift is specified by the second operand, which tin can be either an 8-scrap abiding or the register CL. In either example, shifts counts of greater then 31 are performed modulo 32.

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

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

Examples

shl $ane, eax — Multiply the value of EAX past 2 (if the well-nigh significant bit is 0)

shr %cl, %ebx — Store in EBX the floor of upshot of dividing the value of EBX by 2 n where n is the value in CL. Caution: for negative integers, it is dissimilar from the C semantics of division!

Control Flow Instructions

The x86 processor maintains an instruction pointer (EIP) register that is a 32-scrap value indicating the location in memory where the current instruction starts. Normally, it increments to indicate to the next instruction in retentiveness begins after execution an educational activity. The EIP annals cannot exist manipulated directly, but is updated implicitly by provided command menstruation instructions.

We use the notation <label> to refer to labeled locations in the program text. Labels tin can exist inserted anywhere in x86 assembly code text by entering a label proper name followed by a colon. For example,

            mov 8(%ebp), %esi brainstorm:        xor %ecx, %ecx        mov (%esi), %eax          

The second teaching in this code fragment is labeled brainstorm. Elsewhere in the code, we can refer to the memory location that this pedagogy is located at in memory using the more convenient symbolic proper name begin. This label is just a user-friendly fashion of expressing the location instead of its 32-bit value.

jmp — Jump

Transfers program control flow to the instruction at the memory location indicated past the operand.

Syntax
jmp <label>

Instance
jmp brainstorm — Jump to the pedagogy labeled begin.

jcondition — Conditional leap

These instructions are conditional jumps that are based on the status of a set of condition codes that are stored in a special register chosen the automobile status word. The contents of the machine status word include information about the last arithmetic performance performed. For case, ane flake of this discussion indicates if the last result was zero. Another indicates if the terminal issue was negative. Based on these status codes, a number of conditional jumps tin can exist performed. For instance, the jz instruction performs a bound to the specified operand characterization if the event of the last arithmetic operation was zero. Otherwise, control proceeds to the next didactics in sequence.

A number of the conditional branches are given names that are intuitively based on the last operation performed being a special compare didactics, cmp (see below). For instance, conditional branches such as jle and jne are based on offset performing a cmp operation on the desired operands.

Syntax
je <characterization> (jump when equal)
jne <label> (jump when not equal)
jz <characterization> (jump when terminal result was nil)
jg <label> (jump 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 %ebx, %eax jle washed          

If the contents of EAX are less than or equal to the contents of EBX, spring to the label done. Otherwise, continue to the next instruction.

cmp — Compare

Compare the values of the two specified operands, setting the condition codes in the car status word accordingly. This instruction is equivalent to the sub pedagogy, except the result of the subtraction is discarded instead of replacing the first operand.

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

Example
cmpb $10, (%ebx)
jeq loop

If the byte stored at the retentivity location in EBX is equal to the integer constant 10, jump to the location labeled loop.

phone call, ret — Subroutine call and return

These instructions implement a subroutine call and render. The telephone call didactics first pushes the electric current code location onto the hardware supported stack in retention (encounter the button instruction for details), and then performs an unconditional spring to the code location indicated by the characterization operand. Dissimilar the uncomplicated jump instructions, the call didactics saves the location to return to when the subroutine completes.

The ret instruction implements a subroutine return mechanism. This instruction start pops a code location off the hardware supported in-memory stack (run across the pop educational activity for details). It and so performs an unconditional jump to the retrieved code location.

Syntax
phone call <label>
ret

Calling Convention

To allow split programmers to share code and develop libraries for use by many programs, and to simplify the employ of subroutines in general, programmers typically adopt a common calling convention. The calling convention is a protocol most how to call and return from routines. For example, given a set of calling convention rules, a programmer demand 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, high-level language compilers can be made to follow the rules, thus allowing hand-coded associates linguistic communication routines and loftier-level linguistic communication routines to call 1 some other.

In practice, many calling conventions are possible. We will describe the widely used C language calling convention. Following this convention volition allow you to write associates language subroutines that are safely callable from C (and C++) code, and will also enable yous to telephone call C library functions from your assembly linguistic communication code.

The C calling convention is based heavily on the employ of the hardware-supported stack. It 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 past subroutines are placed in memory on the stack. The vast majority of loftier-level procedural languages implemented on about processors have used like calling conventions.

The calling convention is cleaved into ii sets of rules. The first set 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 apace result in fatal program errors since the stack will be left in an inconsistent state; thus meticulous care should be used when implementing the phone call convention in your ain subroutines.


Stack during Subroutine Phone call

[Thank you to James Peterson for finding and fixing the bug in the original version of this figure!]

A good 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 higher up depicts the contents of the stack during the execution of a subroutine with three parameters and iii local variables. The cells depicted in the stack are 32-fleck wide memory locations, thus the retentivity addresses of the cells are 4 bytes apart. The first parameter resides at an offset of 8 bytes from the base of operations pointer. Above the parameters on the stack (and below the base pointer), the call instruction placed the render address, thus leading to an extra iv bytes of kickoff from the base pointer to the first parameter. When the ret didactics is used to render from the subroutine, it will 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 relieve the contents of certain registers that are designated caller-saved. The caller-saved registers are EAX, ECX, EDX. Since the chosen subroutine is allowed to modify these registers, if the caller relies on their values later the subroutine returns, the caller must push 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, push them onto the stack earlier the call. The parameters should be pushed in inverted society (i.e. terminal parameter first). Since the stack grows down, the first parameter will be stored at the lowest address (this inversion of parameters was historically used to allow functions to be passed a variable number of parameters).
  3. To telephone call the subroutine, use the telephone call instruction. This instruction places the return accost on top of the parameters on the stack, and branches to the subroutine lawmaking. This invokes the subroutine, which should follow the callee rules beneath.

After the subroutine returns (immediately post-obit the call instruction), the caller can look to discover the return value of the subroutine in the annals EAX. To restore the machine state, the caller should:

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

Example

The code below shows a function call that follows the caller rules. The caller is calling a office myFunc that takes three integer parameters. Get-go parameter is in EAX, the 2d parameter is the constant 216; the third parameter is in the memory location stored in EBX.

push (%ebx)    /* Push concluding parameter get-go */ button $216      /* Push the second parameter */ push %eax      /* Push first parameter last */  call myFunc    /* Call the function (assume C naming) */  add together $12, %esp          

Note that afterward the call returns, the caller cleans up the stack using the add instruction. We take 12 bytes (3 parameters * iv bytes each) on the stack, and the stack grows down. Thus, to get rid of the parameters, we can simply add 12 to the stack pointer.

The result produced by myFunc is at present available for use in the register EAX. The values of the caller-saved registers (ECX and EDX), may have been changed. If the caller uses them after the call, it would have needed to save them on the stack before the call and restore them afterward it.

Callee Rules

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

  1. Push the value of EBP onto the stack, and then re-create the value of ESP into EBP using the following instructions:
                  push %ebp     mov  %esp, %ebp            
    This initial action maintains the base of operations pointer, EBP. The base pointer is used past convention equally a indicate of reference for finding parameters and local variables on the stack. When a subroutine is executing, the base pointer holds a re-create of the stack pointer value from when the subroutine started executing. Parameters and local variables will always exist 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 arrow value for the caller when the subroutine returns. Remember, the caller is not expecting the subroutine to alter the value of the base pointer. We then motility the stack arrow into EBP to obtain our betoken of reference for accessing parameters and local variables.
  2. Next, allocate local variables past making infinite on the stack. Recall, the stack grows down, so to make space on the top of the stack, the stack pointer should be decremented. The amount past which the stack pointer is decremented depends on the number and size of local variables needed. For example, if three local integers (4 bytes each) were required, the stack pointer would need to exist decremented by 12 to make space for these local variables (i.due east., sub $12, %esp). Equally with parameters, local variables volition exist located at known offsets from the base pointer.
  3. Next, save the values of the callee-saved registers that volition be used by the function. To save registers, button 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 need not be pushed on the stack during this step).

Later on these three actions are performed, the body of the subroutine may proceed. When the subroutine is returns, it must follow these steps:

  1. Leave the render value in EAX.
  2. Restore the sometime values of any callee-saved registers (EDI and ESI) that were modified. The register contents are restored by popping them from the stack. The registers should exist popped in the inverse lodge that they were pushed.
  3. Deallocate local variables. The obvious way to do this might be to add the advisable value to the stack pointer (since the space was allocated past subtracting the needed corporeality from the stack pointer). In practice, a less error-prone style to deallocate the variables is to move the value in the base arrow into the stack pointer: mov %ebp, %esp. This works because the base pointer ever contains the value that the stack pointer independent immediately prior to the allocation of the local variables.
  4. Immediately before returning, restore the caller's base of operations pointer value by popping EBP off the stack. Recall that the first thing we did on entry to the subroutine was to push the base of operations pointer to save its erstwhile value.
  5. Finally, return to the caller past executing a ret educational activity. This education will find and remove the appropriate render accost from the stack.

Annotation that the callee's rules fall cleanly into two halves that are basically mirror images of one another. The first half of the rules apply to the kickoff of the function, and are commonly said to define the prologue to the function. The latter half of the rules apply to the finish of the function, and are thus commonly said to define the epilogue of the function.

Case

Here is an case function definition that follows the callee rules:

            /* Offset the code section */   .text    /* Define myFunc as a global (exported) function. */   .globl myFunc   .type myFunc, @part myFunc:    /* Subroutine Prologue */   push button %ebp      /* Save the sometime base pointer value. */   mov %esp, %ebp /* Set the new base of operations pointer value. */   sub $iv, %esp   /* Make room for i four-byte local variable. */   push %edi      /* Salve the values of registers that the office */   button %esi      /* will modify. This function uses EDI and ESI. */   /* (no need to salvage EBX, EBP, or ESP) */    /* Subroutine Trunk */   mov viii(%ebp), %eax   /* Move value of parameter 1 into EAX. */   mov 12(%ebp), %esi  /* Move value of parameter ii into ESI. */   mov 16(%ebp), %edi  /* Motility value of parameter 3 into EDI. */    mov %edi, -four(%ebp)  /* Move EDI into the local variable. */   add %esi, -iv(%ebp)  /* Add ESI into the local variable. */   add -4(%ebp), %eax  /* Add together the contents of the local variable */                       /* into EAX (final issue). */    /* Subroutine Epilogue */   pop %esi       /* Recover register values. */   pop %edi   mov %ebp, %esp /* Deallocate the local variable. */   popular %ebp       /* Restore the caller'south base pointer value. */   ret          

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

In the body of the subroutine we tin can see the employ of the base arrow. Both parameters and local variables are located at constant offsets from the base pointer for the duration of the subroutines execution. In particular, we observe that since parameters were placed onto the stack before the subroutine was chosen, they are always located below the base arrow (i.e. at higher addresses) on the stack. The first parameter to the subroutine can e'er be plant at memory location (EBP+8), the second at (EBP+12), the 3rd at (EBP+16). Similarly, since local variables are allocated later on the base arrow is set, they e'er reside above the base pointer (i.e. at lower addresses) on the stack. In item, the kickoff local variable is always located at (EBP-4), the second at (EBP-8), and so on. This conventional apply of the base pointer allows us to rapidly identify the use of local variables and parameters inside a office body.

The function epilogue is basically a mirror image of the function prologue. The caller'southward register 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 educational activity is used to return to the appropriate code location in the caller.

Credits: This guide was originally created past Adam Ferrari many years ago,
and since updated by Alan Batson, Mike Lack, and Anita Jones.
Information technology was revised for 216 Spring 2006 by David Evans.
It was finally modified past Quentin Carbonneaux to apply the AT&T syntax for Yale's CS421.

How To Get Direct Value From Register Assembly,

Source: https://flint.cs.yale.edu/cs421/papers/x86-asm/asm.html

Posted by: bullardwhictime.blogspot.com

0 Response to "How To Get Direct Value From Register Assembly"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel