banner



How To Print The Value Inside A Register In Assembly

x86 Assembly Guide

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

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

This guide describes the nuts of 32-chip x86 assembly language programming, covering a pocket-sized merely useful subset of the available instructions and assembler directives. There are several dissimilar assembly languages for generating x86 automobile lawmaking. The one we will apply in CS421 is the GNU Assembler (gas) assembler. We will uses the standard AT&T syntax for writing x86 assembly code.

The full x86 education set is large and complex (Intel's x86 instruction set manuals comprise over 2900 pages), and we do not embrace information technology all in this guide. For example, at that place is a 16-bit subset of the x86 pedagogy set. Using the 16-bit programming model can be quite complex. It has a segmented memory model, more restrictions on register usage, and and so on. In this guide, we will limit our attention to more modern aspects of x86 programming, and delve into the instruction ready only in enough particular to go a basic feel for x86 programming.

Registers

Mod (i.e 386 and across) x86 processors accept eight 32-bit general purpose registers, as depicted in Figure ane. The register names are more often than not historical. For example, EAX used to be chosen the accumulator since information technology was used by a number of arithmetics operations, and ECX was known as the counter since it was used to hold a loop index. Whereas most of the registers take lost their special purposes in the mod pedagogy gear up, by convention, 2 are reserved for special purposes — the stack pointer (ESP) and the base of operations pointer (EBP).

For the EAX, EBX, ECX, and EDX registers, subsections may be used. For example, the least significant 2 bytes of EAX can be treated equally a 16-chip register called AX. The least significant byte of AX can be used as a single 8-flake register called AL, while the nearly significant byte of AX can be used as a single eight-flake annals chosen 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 teaching set. However, they are sometimes user-friendly when dealing with data that are smaller than 32-bits (eastward.1000. 1-byte ASCII characters).


Effigy 1. x86 Registers

Retentiveness and Addressing Modes

Declaring Static Information Regions

Y'all tin can declare static information regions (coordinating to global variables) in x86 associates using special assembler directives for this purpose. Information declarations should be preceded past the .data directive. Following this directive, the directives .byte, .short, and .long can be used to declare ane, two, and 4 byte data locations, respectively. To refer to the accost of the data created, we can label them. Labels are very useful and versatile in assembly, they give names to memory locations that will be figured out later past the assembler or the linker. This is like to declaring variables by proper noun, but abides by some lower level rules. For instance, locations alleged in sequence will be located in memory next to ane another.

Example declarations:

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

Dissimilar in high level languages where arrays can have 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 list the values, as in the first example below. For the special case of an array of bytes, string literals can exist used. In instance a large surface area of retentiveness is filled with zeroes the .cipher directive can be used.

Some examples:

southward:
.long one, 2, 3 /* Declare 3 four-byte values, initialized to one, 2, and iii.
The value at location s + 8 will be 3. */
barr:
.naught 10 /* Declare x bytes starting at location barr, initialized to 0. */
str:
.string "hello" /* Declare 6 bytes starting at the address 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 two32 bytes of retentiveness: memory addresses are 32-bits wide. In the examples in a higher place, where we used labels to refer to retentiveness regions, these labels are really replaced by the assembler with 32-bit quantities that specify addresses in memory. In addition to supporting referring to memory regions past labels (i.east. constant values), the x86 provides a flexible scheme for computing and referring to memory addresses: up to 2 of the 32-bit registers and a 32-bit signed constant tin can be added together to compute a memory accost. One of the registers can be optionally pre-multiplied by ii, 4, or eight.

The addressing modes tin can be used with many x86 instructions (we'll describe them in the next department). Hither we illustrate some examples using the mov teaching that moves information 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 address computations are:

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

Some examples of invalid address calculations include:

mov (%ebx,%ecx,-1), %eax /* Can only add register values. */
mov %ebx, (%eax,%esi,%edi,1) /* At most two registers in accost computation. */

Performance Suffixes

In general, the intended size of the of the information item at a given retention accost can exist inferred from the associates code teaching in which it is referenced. For example, in all of the to a higher place instructions, the size of the memory regions could exist inferred from the size of the register operand. When nosotros were loading a 32-fleck register, the assembler could infer that the region of retentiveness we were referring to was 4 bytes wide. When we were storing the value of a one byte annals to memory, the assembler could infer that we wanted the address to refer to a single byte in memory.

However, in some cases the size of a referred-to memory region is cryptic. Consider the education mov $ii, (%ebx). Should this instruction move the value 2 into the single byte at address EBX? Maybe information technology should move the 32-bit integer representation of 2 into the iv-bytes starting at accost EBX. Since either is a valid possible interpretation, the assembler must be explicitly directed equally to which is correct. The size prefixes b, westward, and fifty serve this purpose, indicating sizes of 1, ii, and 4 bytes respectively.

For example:

movb $2, (%ebx) /* Move 2 into the single byte at the accost stored in EBX. */
movw $2, (%ebx) /* Motility the 16-bit integer representation of 2 into the 2 bytes starting at the address in EBX. */
movl $2, (%ebx) /* Motion the 32-bit integer representation of two into the 4 bytes starting at the accost in EBX. */

Instructions

Car instructions generally fall into three categories: data movement, arithmetics/logic, and control-flow. In this section, nosotros will await at important examples of x86 instructions from each category. This section should not be considered an exhaustive listing of x86 instructions, merely rather a useful subset. For a complete list, come across Intel'south education ready reference.

We use the post-obit note:

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

In assembly linguistic communication, all the labels and numeric constants used as immediate operands (i.e. not in an address calculation like iii(%eax,%ebx,8)) are always prefixed by a dollar sign. When needed, hexadecimal notation can exist used with the 0x prefix (e.g. $0xABC). Without the prefix, numbers are interpreted in the decimal ground.

Information Movement Instructions

mov — Move

The mov didactics copies the data detail referred to by its get-go operand (i.east. register contents, retentiveness contents, or a constant value) into the location referred to by its second operand (i.e. a register or retentivity). While register-to-register moves are possible, directly memory-to-retentiveness moves are not. In cases where memory transfers are desired, the source memory contents must first be loaded into a register, so can exist 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 — re-create the value in EBX into EAX
movb $v, var(,1) — store the value 5 into the byte at location var

button — Button on stack

The push instruction places its operand onto the top of the hardware supported stack in retention. Specifically, button first decrements ESP past four, and so 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 down — i.eastward. the stack grows from loftier addresses to lower addresses.

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

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

pop — Pop from stack

The pop didactics removes the 4-byte data element from the tiptop of the hardware-supported stack into the specified operand (i.e. annals or retentivity location). Information technology kickoff moves the 4 bytes located at memory location (%esp) into the specified annals or memory location, and then increments ESP by 4.

Syntax
pop <reg32>
pop <mem>

Examples
pop %edi — pop the summit element of the stack into EDI.
pop (%ebx) — pop the peak chemical element of the stack into retentiveness at the iv bytes starting at location EBX.

lea — Load effective address

The lea instruction places the address specified by its first operand into the register specified past its second operand. Note, the contents of the retention location are not loaded, simply 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+eight*ESI is placed in EDI.
lea val(,1), %eax — the value val is placed in EAX.

Arithmetic and Logic Instructions

add — Integer addition

The add instruction adds together its ii operands, storing the result in its 2nd operand. Notation, whereas both operands may be registers, at most one operand may exist a memory location.

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

Examples
add $10, %eax — EAX is set to EAX + 10
addb $x, (%eax) — add 10 to the single byte stored at memory accost stored in EAX

sub — Integer subtraction

The sub instruction stores in the value of its 2d operand the outcome of subtracting the value of its commencement operand from the value of its second operand. As with add together, whereas both operands may be registers, at most one 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 fix to AL - AH
sub $216, %eax — subtract 216 from the value stored in EAX

inc, dec — Increase, Decrement

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

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

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

imul — Integer multiplication

The imul instruction has two basic formats: two-operand (offset two syntax listings above) and three-operand (last 2 syntax listings higher up).

The ii-operand form multiplies its 2 operands together and stores the result in the second operand. The effect (i.e. second) operand must be a register.

The iii operand form multiplies its 2nd and third operands together and stores the result in its last operand. Again, the result operand must be a register. Furthermore, the first operand is restricted to existence a abiding 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 retentiveness at location EBX. Shop the result in EAX.

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

idiv — Integer segmentation

The idiv educational activity divides the contents of the 64 bit integer EDX:EAX (constructed by viewing EDX equally the most significant four bytes and EAX as the to the lowest degree significant four bytes) by 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 — divide 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 past the 32-chip value stored at the retention location in EBX. 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 <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 cipher.

non — Bitwise logical not

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

Syntax
not <reg>
not <mem>

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

neg — Negate

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

Syntax
neg <reg>
neg <mem>

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

shl, shr — Shift left and right

These instructions shift the $.25 in their first operand's contents left and right, padding the resulting empty chip positions with zeros. The shifted operand can be shifted up to 31 places. The number of bits to shift is specified by the 2d operand, which tin be either an 8-bit constant or the register CL. In either case, 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 $1, eax — Multiply the value of EAX by 2 (if the most significant flake is 0)

shr %cl, %ebx — Store in EBX the floor of effect of dividing the value of EBX past ii n where n is the value in CL. Caution: for negative integers, information technology is unlike from the C semantics of division!

Command Flow Instructions

The x86 processor maintains an education arrow (EIP) register that is a 32-bit value indicating the location in memory where the electric current instruction starts. Usually, it increments to signal to the side by side pedagogy in memory begins later execution an instruction. The EIP register cannot exist manipulated directly, merely is updated implicitly by provided control period instructions.

We apply the notation <label> to refer to labeled locations in the program text. Labels can be inserted anywhere in x86 associates code text by entering a label name followed by a colon. For example,

            mov viii(%ebp), %esi begin:        xor %ecx, %ecx        mov (%esi), %eax          

The second instruction in this code fragment is labeled begin. Elsewhere in the lawmaking, nosotros can refer to the retentivity location that this pedagogy is located at in memory using the more convenient symbolic proper noun begin. This characterization is only a convenient way of expressing the location instead of its 32-flake value.

jmp — Jump

Transfers programme control flow to the instruction at the retention location indicated past the operand.

Syntax
jmp <label>

Example
jmp begin — Jump to the educational activity labeled begin.

jcondition — 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 machine status word. The contents of the auto status word include information about the terminal arithmetics operation performed. For example, one bit of this discussion indicates if the last issue was zero. 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 instruction performs a jump to the specified operand characterization if the result of the last arithmetics operation was zero. Otherwise, control proceeds to the side by side didactics in sequence.

A number of the conditional branches are given names that are intuitively based on the terminal operation performed existence a special compare education, cmp (encounter below). For case, 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 non equal)
jz <label> (jump when terminal result was cypher)
jg <characterization> (leap when greater than)
jge <label> (jump when greater than or equal to)
jl <characterization> (jump when less than)
jle <label> (bound when less than or equal to)

Example

cmp %ebx, %eax jle done          

If the contents of EAX are less than or equal to the contents of EBX, bound 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 motorcar status discussion appropriately. This instruction is equivalent to the sub education, except the result of the subtraction is discarded instead of replacing the offset 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 memory location in EBX is equal to the integer constant ten, jump to the location labeled loop.

call, ret — Subroutine call and return

These instructions implement a subroutine call and render. The call instruction commencement pushes the current lawmaking location onto the hardware supported stack in memory (see the button didactics for details), and and then performs an unconditional jump to the code location indicated by the label operand. Unlike the simple jump instructions, the call instruction saves the location to return to when the subroutine completes.

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

Syntax
call <characterization>
ret

Calling Convention

To let separate programmers to share lawmaking and develop libraries for utilise by many programs, and to simplify the use of subroutines in general, programmers typically adopt a common calling convention. The calling convention is a protocol about how to phone call and return from routines. For example, given a set of calling convention rules, a programmer need not examine the definition of a subroutine to make up one's mind how parameters should be passed to that subroutine. Furthermore, given a set of calling convention rules, high-level language compilers can exist made to follow the rules, thus allowing hand-coded assembly language routines and high-level language routines to call one another.

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

The C calling convention is based heavily on the use of the hardware-supported stack. It is based on the push button, popular, 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 bulk of high-level procedural languages implemented on most processors take used like calling conventions.

The calling convention is cleaved into two sets of rules. The first set of rules is employed past the caller of the subroutine, and the second set up of rules is observed by the writer of the subroutine (the callee). It should be emphasized that mistakes in the observance of these rules quickly consequence in fatal program errors since the stack will be left in an inconsistent state; thus meticulous care should exist used when implementing the phone call convention in your own subroutines.


Stack during Subroutine Call

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

A proficient style 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 iii parameters and three local variables. The cells depicted in the stack are 32-bit wide memory locations, thus the memory addresses of the cells are 4 bytes apart. The commencement parameter resides at an commencement of eight bytes from the base of operations arrow. Above the parameters on the stack (and beneath the base pointer), the call didactics placed the return address, thus leading to an extra 4 bytes of offset from the base pointer to the starting time parameter. When the ret pedagogy is used to return from the subroutine, it will spring to the render address stored on the stack.

Caller Rules

To brand a subrouting call, the caller should:

  1. Before 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 immune to modify these registers, if the caller relies on their values afterwards the subroutine returns, the caller must push button the values in these registers onto the stack (so they can be restore after the subroutine returns.
  2. To pass parameters to the subroutine, push them onto the stack earlier the telephone call. The parameters should be pushed in inverted order (i.e. concluding parameter showtime). Since the stack grows down, the outset parameter will be stored at the lowest accost (this inversion of parameters was historically used to allow functions to exist passed a variable number of parameters).
  3. To call the subroutine, utilize the phone call instruction. This instruction places the return address on meridian of the parameters on the stack, and branches to the subroutine code. This invokes the subroutine, which should follow the callee rules beneath.

After the subroutine returns (immediately following the telephone call instruction), the caller can wait to find 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 state 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 by the subroutine.

Case

The code below shows a office call that follows the caller rules. The caller is calling a role myFunc that takes three integer parameters. Beginning parameter is in EAX, the second parameter is the abiding 216; the third parameter is in the memory location stored in EBX.

push (%ebx)    /* Button last parameter starting time */ push $216      /* Button the second parameter */ push %eax      /* Button beginning parameter concluding */  phone call myFunc    /* Call the function (presume C naming) */  add $12, %esp          

Note that after the call returns, the caller cleans up the stack using the add together instruction. We have 12 bytes (iii parameters * 4 bytes each) on the stack, and the stack grows downwards. Thus, to get rid of the parameters, we can merely add together 12 to the stack arrow.

The result produced by myFunc is now 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 afterward the call, it would accept needed to relieve them on the stack before the call and restore them after it.

Callee Rules

The definition of the subroutine should adhere to the post-obit rules at the beginning of the subroutine:

  1. Push the value of EBP onto the stack, and so re-create the value of ESP into EBP using the following instructions:
                  push %ebp     mov  %esp, %ebp            
    This initial action maintains the base pointer, EBP. The base of operations pointer is used by convention equally a indicate of reference for finding parameters and local variables on the stack. When a subroutine is executing, the base of operations arrow holds a copy of the stack arrow 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 of operations pointer value at the offset of the subroutine so that we tin later restore the appropriate base pointer value for the caller when the subroutine returns. Call up, the caller is not expecting the subroutine to change the value of the base of operations arrow. We then move the stack arrow into EBP to obtain our point 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 superlative of the stack, the stack arrow should be decremented. The amount by which the stack pointer is decremented depends on the number and size of local variables needed. For example, if 3 local integers (4 bytes each) were required, the stack pointer would need to be decremented by 12 to make space for these local variables (i.e., sub $12, %esp). Every bit with parameters, local variables will exist located at known offsets from the base pointer.
  3. Next, relieve the values of the callee-saved registers that will exist used past the function. To save registers, push them onto the stack. The callee-saved registers are EBX, EDI, and ESI (ESP and EBP volition likewise exist preserved by the calling convention, but demand not be pushed on the stack during this step).

Afterwards these iii actions are performed, the trunk of the subroutine may continue. When the subroutine is returns, it must follow these steps:

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

Annotation that the callee'due south rules autumn cleanly into 2 halves that are basically mirror images of one another. The first half of the rules apply to the beginning of the function, and are commonly said to define the prologue to the role. The latter half of the rules apply to the end of the function, and are thus commonly said to define the epilogue of the function.

Example

Here is an example role definition that follows the callee rules:

            /* Start the code section */   .text    /* Define myFunc as a global (exported) function. */   .globl myFunc   .blazon myFunc, @function myFunc:    /* Subroutine Prologue */   push %ebp      /* Save the onetime base pointer value. */   mov %esp, %ebp /* Set the new base pointer value. */   sub $4, %esp   /* Make room for one iv-byte local variable. */   push button %edi      /* Relieve the values of registers that the part */   push %esi      /* will modify. This role uses EDI and ESI. */   /* (no need to save EBX, EBP, or ESP) */    /* Subroutine Trunk */   mov viii(%ebp), %eax   /* Movement value of parameter 1 into EAX. */   mov 12(%ebp), %esi  /* Move value of parameter 2 into ESI. */   mov 16(%ebp), %edi  /* Move value of parameter 3 into EDI. */    mov %edi, -4(%ebp)  /* Move EDI into the local variable. */   add %esi, -4(%ebp)  /* Add together ESI into the local variable. */   add -4(%ebp), %eax  /* Add the contents of the local variable */                       /* into EAX (final upshot). */    /* Subroutine Epilogue */   pop %esi       /* Recover annals values. */   pop %edi   mov %ebp, %esp /* Deallocate the local variable. */   pop %ebp       /* Restore the caller's base pointer value. */   ret          

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

In the body of the subroutine we can see the apply 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 earlier the subroutine was called, they are always located below the base pointer (i.e. at higher addresses) on the stack. The first parameter to the subroutine can e'er be found at memory location (EBP+viii), the 2nd at (EBP+12), the 3rd at (EBP+16). Similarly, since local variables are allocated afterward the base pointer is set up, they always reside above the base pointer (i.e. at lower addresses) on the stack. In detail, the first local variable is ever located at (EBP-4), the 2d at (EBP-8), and and then on. This conventional utilize of the base pointer allows usa to quickly place the use of local variables and parameters inside a function body.

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

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

How To Print The Value Inside A Register In Assembly,

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

Posted by: beasleypecom1994.blogspot.com

0 Response to "How To Print The Value Inside A Register In Assembly"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel