How To Get One Byte Of Register
x86 Assembly Guide
Contents: Registers | Memory and Addressing | Instructions | Calling Convention
This is a version adapted past Quentin Carbonneaux from David Evans' original certificate. 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-bit x86 assembly language programming, covering a small but useful subset of the available instructions and assembler directives. There are several different associates languages for generating x86 machine lawmaking. The 1 we will utilize in CS421 is the GNU Assembler (gas) assembler. Nosotros will uses the standard AT&T syntax for writing x86 associates code.
The total x86 teaching fix is large and circuitous (Intel's x86 instruction set up manuals contain over 2900 pages), and we exercise not cover it all in this guide. For example, in that location is a sixteen-bit subset of the x86 instruction set. Using the xvi-bit programming model can be quite complex. It has a segmented retentiveness 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 education set only in enough detail to become a basic feel for x86 programming.
Registers
Modern (i.east 386 and beyond) x86 processors have eight 32-flake general purpose registers, as depicted in Figure 1. The annals names are generally historical. For example, EAX used to exist called the accumulator since it was used by a number of arithmetic operations, and ECX was known equally the counter since it was used to concur a loop alphabetize. Whereas about of the registers have lost their special purposes in the modernistic instruction gear up, by convention, two are reserved for special purposes — the stack arrow (ESP) and the base of operations pointer (EBP).
For the EAX, EBX, ECX, and EDX registers, subsections may be used. For example, the to the lowest degree significant 2 bytes of EAX can be treated as a xvi-bit register called AX. The to the lowest degree significant byte of AX can be used as a single eight-flake annals called AL, while the almost significant byte of AX tin can be used every bit a single 8-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-scrap versions of the educational activity set. Nonetheless, they are sometimes convenient when dealing with data that are smaller than 32-$.25 (e.g. 1-byte ASCII characters).
Figure 1. x86 Registers
Memory and Addressing Modes
Declaring Static Information Regions
You can declare static information regions (analogous to global variables) in x86 associates using special assembler directives for this purpose. Data declarations should be preceded by the .data directive. Following this directive, the directives .byte, .short, and .long can exist used to declare ane, two, and four byte data locations, respectively. To refer to the accost of the information created, we can characterization them. Labels are very useful and versatile in associates, they requite names to memory locations that volition exist figured out later past the assembler or the linker. This is like to declaring variables by name, just abides by some lower level rules. For example, locations declared in sequence will be located in retention adjacent to one another.
Example declarations:
.information 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. */ x: .brusk 42 /* Declare a 2-byte value initialized to 42, referred to as location x. */ y: .long 30000 /* Declare a 4-byte value, referred to as location y, initialized to 30000. */
Unlike in loftier level languages where arrays can have many dimensions and are accessed past indices, arrays in x86 assembly language are only a number of cells located contiguously in retentiveness. An array tin can be declared by just listing the values, as in the kickoff example below. For the special case of an assortment of bytes, cord literals tin be used. In case a big area of retention is filled with zeroes the .zilch directive tin be used.
Some examples:
s: .long 1, 2, 3 /* Declare iii iv-byte values, initialized to 1, two, and three.
The value at location southward + viii will be 3. */barr: .zero x /* Declare 10 bytes starting at location barr, initialized to 0. */ str: .string "hi" /* Declare 6 bytes starting at the address str initialized to
the ASCII character values for hello followed by a nul (0) byte. */
Addressing Retention
Modern x86-uniform processors are capable of addressing upwards to ii32 bytes of retentiveness: retention addresses are 32-bits wide. In the examples above, where nosotros used labels to refer to memory regions, these labels are really replaced past the assembler with 32-bit quantities that specify addresses in retentivity. In add-on 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-bit registers and a 32-chip signed constant can be added together to compute a memory address. I of the registers can be optionally pre-multiplied by ii, 4, or 8.
The addressing modes tin exist used with many x86 instructions (we'll describe them in the next section). Here we illustrate some examples using the mov instruction that moves information between registers and memory. This instruction has two operands: the commencement 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 memory address in EBX into EAX. */ mov %ebx, var(,1) /* Move the contents of EBX into the 4 bytes at memory address var.
(Note, var is a 32-bit abiding). */mov -4(%esi), %eax /* Move 4 bytes at memory accost ESI + (-4) into EAX. */ mov %cl, (%esi,%eax,1) /* Movement the contents of CL into the byte at address ESI+EAX. */ mov (%esi,%ebx,4), %edx /* Move the 4 bytes of data at address ESI+4*EBX into EDX. */
Some examples of invalid address calculations include:
mov (%ebx,%ecx,-1), %eax /* Tin can only add register values. */ mov %ebx, (%eax,%esi,%edi,ane) /* At most 2 registers in address computation. */
Operation Suffixes
In general, the intended size of the of the data item at a given memory address tin be inferred from the assembly lawmaking didactics in which information technology is referenced. For example, in all of the higher up instructions, the size of the retentivity regions could be inferred from the size of the register operand. When nosotros were loading a 32-chip register, the assembler could infer that the region of memory we were referring to was 4 bytes broad. When we were storing the value of a i byte register to retentivity, the assembler could infer that nosotros wanted the accost to refer to a unmarried byte in retention.
However, in some cases the size of a referred-to memory region is ambiguous. Consider the instruction mov $ii, (%ebx). Should this pedagogy move the value ii into the single byte at address EBX? Perhaps it should move 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 exist explicitly directed as to which is correct. The size prefixes b, w, and fifty serve this purpose, indicating sizes of ane, ii, and iv bytes respectively.
For case:
movb $2, (%ebx) /* Movement 2 into the unmarried byte at the accost stored in EBX. */ movw $2, (%ebx) /* Move the 16-chip integer representation of 2 into the ii bytes starting at the address in EBX. */ movl $2, (%ebx) /* Motion the 32-flake integer representation of two into the 4 bytes starting at the address in EBX. */
Instructions
Car instructions generally autumn into iii categories: data movement, arithmetic/logic, and control-menstruation. In this section, we will await at important examples of x86 instructions from each category. This section should not be considered an exhaustive listing of x86 instructions, but rather a useful subset. For a complete list, encounter Intel's didactics set reference.
We use the following notation:
<reg32> Whatever 32-scrap annals (%eax, %ebx, %ecx, %edx, %esi, %edi, %esp, or %ebp) <reg16> Whatever sixteen-bit annals (%ax, %bx, %cx, or %dx) <reg8> Whatever eight-bit register (%ah, %bh, %ch, %dh, %al, %bl, %cl, or %dl) <reg> Whatsoever register <mem> A retentiveness accost (e.chiliad., (%eax), 4+var(,1), or (%eax,%ebx,1)) <con32> Any 32-bit immediate <con16> Any xvi-bit immediate <con8> Whatever 8-bit immediate <con> Whatever 8-, 16-, or 32-bit immediate
In assembly linguistic communication, all the labels and numeric constants used as immediate operands (i.e. not in an address calculation like 3(%eax,%ebx,eight)) are always prefixed by a dollar sign. When needed, hexadecimal notation tin can be used with the 0x prefix (e.g. $0xABC). Without the prefix, numbers are interpreted in the decimal basis.
Data Movement Instructions
mov — Move
The mov instruction copies the information item referred to by its kickoff operand (i.e. register contents, memory contents, or a abiding value) into the location referred to by its second operand (i.east. a register or memory). While register-to-register moves are possible, direct memory-to-memory moves are not. In cases where retentiveness transfers are desired, the source memory contents must showtime exist loaded into a annals, and then can be stored to the destination memory accost.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 $five, var(,one) — store the value 5 into the byte at location var
push button — Button on stack
The push instruction places its operand onto the top of the hardware supported stack in memory. Specifically, push offset 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 push since the x86 stack grows downwardly — i.east. the stack grows from high addresses to lower addresses.Syntax
push <reg32>
push <mem>
push button <con32>Examples
push button %eax — push eax on the stack
push var(,1) — push the four bytes at address var onto the stack
pop — Pop from stack
The popular didactics removes the 4-byte information chemical element from the acme of the hardware-supported stack into the specified operand (i.e. register or memory location). Information technology first moves the iv bytes located at retentiveness location (%esp) into the specified annals or memory location, and and so increments ESP by 4.Syntax
Examples
popular <reg32>
pop <mem>
popular %edi — pop the top 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 accost
The lea pedagogy places the accost specified past its beginning operand into the register specified past its second operand. Notation, the contents of the memory location are not loaded, just the effective address is computed and placed into the register. This is useful for obtaining a arrow into a memory region or to perform simple arithmetics 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 — Integer improver
The add instruction adds together its ii operands, storing the result in its 2d operand. Note, whereas both operands may be registers, at most 1 operand may be a memory location.Syntax
add <reg>, <reg>
add <mem>, <reg>
add <reg>, <mem>
add together <con>, <reg>
add <con>, <mem>
Examples
add $10, %eax — EAX is prepare to EAX + ten
addb $ten, (%eax) — add 10 to the single byte stored at memory 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 outset operand from the value of its 2nd operand. As with add together, whereas both operands may exist registers, at well-nigh 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 set to AL - AH
sub $216, %eax — subtract 216 from the value stored in EAX
inc, dec — Increment, Decrement
The inc teaching increments the contents of its operand by one. The december instruction decrements the contents of its operand by one.Syntax
inc <reg>
inc <mem>
dec <reg>
dec <mem>Examples
dec %eax — subtract one from the contents of EAX
incl var(,1) — add one to the 32-fleck integer stored at location var
imul — Integer multiplication
The imul instruction has 2 basic formats: two-operand (start two syntax listings above) and three-operand (last two syntax listings above).The two-operand class multiplies its two operands together and stores the result in the second operand. The issue (i.due east. second) operand must be a register.
The three operand grade multiplies its second and 3rd operands together and stores the result in its concluding operand. Again, the result operand must be a register. Furthermore, the first operand is restricted to existence 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 by the 32-bit contents of the memory at location EBX. Store the upshot in EAX.
imul $25, %edi, %esi — ESI is gear up to EDI * 25
idiv — Integer division
The idiv education divides the contents of the 64 scrap integer EDX:EAX (constructed past viewing EDX every bit the most significant four bytes and EAX as the least meaning 4 bytes) by the specified operand value. The quotient upshot of the division is stored into EAX, while the rest is placed in EDX.Syntax
idiv <reg32>
idiv <mem>Examples
idiv %ebx — divide the contents of EDX:EAX by 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 retention location in EBX. Place the quotient in EAX and the residual 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 outset 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 — articulate all but the last 4 bits of EAX.
xor %edx, %edx — ready the contents of EDX to nil.
not — Bitwise logical not
Logically negates the operand contents (that is, flips all bit values in the operand).Syntax
not <reg>
not <mem>Example
not %eax — flip all the bits of EAX
neg — Negate
Performs the two's complement negation of the operand contents.Syntax
neg <reg>
neg <mem>Example
neg %eax — EAX is ready to (- EAX)
shl, shr — Shift left and right
These instructions shift the bits in their showtime operand's contents left and correct, padding the resulting empty bit positions with zeros. The shifted operand can be shifted up to 31 places. The number of bits to shift is specified by the 2nd operand, which tin can be either an eight-bit constant or the annals 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 $ane, eax — Multiply the value of EAX by two (if the nigh significant chip is 0)
shr %cl, %ebx — Store in EBX the floor of result of dividing the value of EBX by 2 n where northward is the value in CL. Caution: for negative integers, it is different from the C semantics of division!
Control Period Instructions
The x86 processor maintains an instruction pointer (EIP) register that is a 32-bit value indicating the location in memory where the current instruction starts. Commonly, it increments to point to the adjacent instruction in retentiveness begins later on execution an instruction. The EIP annals cannot be manipulated directly, but is updated implicitly past provided control menstruum instructions.
Nosotros utilise the notation <label> to refer to labeled locations in the program text. Labels can exist inserted anywhere in x86 associates code text by entering a label name followed past a colon. For example,
mov 8(%ebp), %esi begin: xor %ecx, %ecx mov (%esi), %eax
The second instruction in this code fragment is labeled begin. Elsewhere in the code, we can refer to the retentivity location that this educational activity is located at in retentivity using the more convenient symbolic name begin. This label is just a convenient style of expressing the location instead of its 32-bit value.
jmp — Leap
Transfers program control period to the educational activity at the memory location indicated by the operand.Syntax
jmp <label>Instance
jmp begin — Spring to the instruction labeled begin.
jstatus — Conditional jump
These instructions are conditional jumps that are based on the status of a fix of status codes that are stored in a special register called the machine condition word. The contents of the machine condition word include information about the last arithmetics operation performed. For example, one bit of this word indicates if the last result was zero. Another indicates if the terminal event was negative. Based on these condition codes, a number of conditional jumps tin can be performed. For example, the jz education performs a jump to the specified operand label if the outcome of the last arithmetic operation was zero. Otherwise, command proceeds to the next teaching in sequence.A number of the conditional branches are given names that are intuitively based on the last operation performed being a special compare pedagogy, cmp (see beneath). For example, conditional branches such as jle and jne are based on first performing a cmp functioning on the desired operands.
Syntax
je <label> (jump when equal)
jne <label> (bound when not equal)
jz <label> (jump when last result was cipher)
jg <label> (leap when greater than)
jge <label> (jump when greater than or equal to)
jl <label> (jump when less than)
jle <label> (jump when less than or equal to)Example
cmp %ebx, %eax jle doneIf the contents of EAX are less than or equal to the contents of EBX, jump to the label done. Otherwise, continue to the next teaching.
cmp — Compare
Compare the values of the two specified operands, setting the condition codes in the machine condition word accordingly. This instruction is equivalent to the sub education, 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>Instance
cmpb $10, (%ebx)
jeq loopIf the byte stored at the memory location in EBX is equal to the integer constant 10, jump to the location labeled loop.
call, ret — Subroutine telephone call and return
These instructions implement a subroutine call and return. The call instruction outset pushes the electric current lawmaking location onto the hardware supported stack in memory (see the push educational activity for details), so performs an unconditional jump to the code location indicated past the label operand. Dissimilar the unproblematic jump instructions, the call teaching saves the location to return to when the subroutine completes.The ret instruction implements a subroutine return machinery. This instruction beginning pops a code location off the hardware supported in-retention stack (encounter the popular instruction for details). It then performs an unconditional jump to the retrieved lawmaking location.
Syntax
call <label>
ret
Calling Convention
To let separate programmers to share code and develop libraries for use 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 call and return from routines. For instance, given a set of calling convention rules, a programmer need non 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 tin be made to follow the rules, thus allowing hand-coded assembly linguistic communication routines and high-level language routines to telephone call one some other.
In practice, many calling conventions are possible. We will depict the widely used C language calling convention. Following this convention will allow you to write associates language subroutines that are safely callable from C (and C++) lawmaking, and will also enable you to telephone call C library functions from your associates linguistic communication code.
The C calling convention is based heavily on the use 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 by subroutines are placed in memory on the stack. The vast majority of high-level procedural languages implemented on nearly processors have used similar calling conventions.
The calling convention is broken into ii sets of rules. The first set of rules is employed by the caller of the subroutine, and the second set of rules is observed by the author of the subroutine (the callee). Information technology should be emphasized that mistakes in the observance of these rules speedily event in fatal program errors since the stack will be left in an inconsistent state; thus meticulous intendance should exist used when implementing the call convention in your ain subroutines.
Stack during Subroutine Phone call
[Thank you to James Peterson for finding and fixing the problems in the original version of this effigy!]
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 epitome 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-scrap wide memory locations, thus the memory addresses of the cells are 4 bytes apart. The first parameter resides at an commencement of 8 bytes from the base arrow. In a higher place the parameters on the stack (and beneath the base of operations pointer), the phone call didactics placed the render address, thus leading to an actress 4 bytes of outset from the base arrow to the first parameter. When the ret educational activity is used to return from the subroutine, information technology will jump to the render address stored on the stack.
Caller Rules
To brand a subrouting telephone call, the caller should:
- Before calling a subroutine, the caller should salve 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 afterwards the subroutine returns, the caller must push the values in these registers onto the stack (and so they can be restore after the subroutine returns.
- To laissez passer parameters to the subroutine, push them onto the stack earlier the call. The parameters should exist pushed in inverted society (i.eastward. last parameter first). Since the stack grows down, the get-go parameter will be stored at the lowest accost (this inversion of parameters was historically used to permit functions to be passed a variable number of parameters).
- To call the subroutine, utilize the call education. This teaching places the return address on pinnacle of the parameters on the stack, and branches to the subroutine code. This invokes the subroutine, which should follow the callee rules below.
Later the subroutine returns (immediately following the telephone call didactics), the caller can look to notice the render value of the subroutine in the annals EAX. To restore the machine country, the caller should:
- Remove the parameters from stack. This restores the stack to its state earlier the call was performed.
- 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 beneath shows a role call that follows the caller rules. The caller is calling a function myFunc that takes three integer parameters. First 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 outset */ push $216 /* Push the 2nd parameter */ push button %eax /* Push starting time parameter final */ call myFunc /* Call the function (assume C naming) */ add together $12, %esp
Annotation that after the call returns, the caller cleans upward the stack using the add together education. We have 12 bytes (3 parameters * four bytes each) on the stack, and the stack grows down. Thus, to become rid of the parameters, we can simply add 12 to the stack pointer.
The result produced by myFunc is now available for utilise in the register EAX. The values of the caller-saved registers (ECX and EDX), may accept been changed. If the caller uses them later the call, it would have needed to relieve them on the stack before the telephone call and restore them afterwards it.
Callee Rules
The definition of the subroutine should adhere to the following rules at the first of the subroutine:
- Push button the value of EBP onto the stack, and so copy the value of ESP into EBP using the post-obit instructions:
button %ebp mov %esp, %ebp
This initial activity maintains the base pointer, EBP. The base pointer is used by convention every bit 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 re-create of the stack pointer value from when the subroutine started executing. Parameters and local variables will always be located at known, abiding offsets away from the base of operations arrow value. We push button the old base pointer value at the beginning of the subroutine so that we can later restore the appropriate 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 pointer. We then motion the stack pointer into EBP to obtain our point of reference for accessing parameters and local variables. - Next, allocate local variables by making space on the stack. Call up, the stack grows down, then to make infinite 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 instance, if iii local integers (4 bytes each) were required, the stack pointer would need to be decremented past 12 to make space for these local variables (i.due east., sub $12, %esp). As with parameters, local variables will exist located at known offsets from the base of operations pointer.
- Next, save the values of the callee-saved registers that volition be used by the office. To save registers, push button them onto the stack. The callee-saved registers are EBX, EDI, and ESI (ESP and EBP will also be preserved by the calling convention, but need not exist pushed on the stack during this pace).
After these iii actions are performed, the body of the subroutine may proceed. When the subroutine is returns, information technology must follow these steps:
- Get out the return value in EAX.
- Restore the onetime 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 order that they were pushed.
- Deallocate local variables. The obvious mode to practice this might be to add the advisable value to the stack arrow (since the space was allocated by subtracting the needed amount from the stack pointer). In practice, a less error-prone style to deallocate the variables is to motion the value in the base pointer into the stack pointer: mov %ebp, %esp. This works because the base of operations arrow ever contains the value that the stack arrow contained immediately prior to the allocation of the local variables.
- Immediately earlier returning, restore the caller's base pointer value by popping EBP off the stack. Recall that the outset thing we did on entry to the subroutine was to push the base pointer to relieve its former value.
- Finally, return to the caller past executing a ret instruction. This instruction will find and remove the appropriate return accost from the stack.
Note that the callee'south rules autumn cleanly into two halves that are basically mirror images of one some other. The first half of the rules use to the beginning of the function, and are commonly said to define the prologue to the role. The latter one-half of the rules apply to the end of the function, and are thus commonly said to define the epilogue of the office.
Example
Here is an example part definition that follows the callee rules:
/* Start the code section */ .text /* Define myFunc every bit a global (exported) office. */ .globl myFunc .type myFunc, @office myFunc: /* Subroutine Prologue */ push %ebp /* Save the erstwhile base pointer value. */ mov %esp, %ebp /* Set the new base pointer value. */ sub $4, %esp /* Make room for 1 4-byte local variable. */ push %edi /* Salvage the values of registers that the role */ push button %esi /* volition alter. This office uses EDI and ESI. */ /* (no need to save EBX, EBP, or ESP) */ /* Subroutine Body */ mov 8(%ebp), %eax /* Move value of parameter 1 into EAX. */ mov 12(%ebp), %esi /* Motility value of parameter two into ESI. */ mov 16(%ebp), %edi /* Move value of parameter 3 into EDI. */ mov %edi, -four(%ebp) /* Motion EDI into the local variable. */ add %esi, -4(%ebp) /* Add together ESI into the local variable. */ add together -4(%ebp), %eax /* Add the contents of the local variable */ /* into EAX (final event). */ /* Subroutine Epilogue */ pop %esi /* Recover register values. */ pop %edi mov %ebp, %esp /* Deallocate the local variable. */ pop %ebp /* Restore the caller'south base of operations arrow 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 annals values on the stack.
In the body of the subroutine we can run into the employ of the base pointer. Both parameters and local variables are located at abiding offsets from the base of operations pointer for the elapsing of the subroutines execution. In item, we discover that since parameters were placed onto the stack before the subroutine was called, they are always located below the base of operations pointer (i.eastward. at higher addresses) on the stack. The first parameter to the subroutine tin always be found at memory location (EBP+eight), the second at (EBP+12), the 3rd at (EBP+16). Similarly, since local variables are allocated afterward the base of operations pointer is set, they always reside in a higher place the base pointer (i.e. at lower addresses) on the stack. In particular, the first local variable is always located at (EBP-4), the second at (EBP-8), so on. This conventional utilise of the base pointer allows us to quickly identify the apply of local variables and parameters within a function body.
The function epilogue is basically a mirror image of the function prologue. The caller's register values are recovered from the stack, the local variables are deallocated by resetting the stack arrow, the caller'south base of operations arrow value is recovered, and the ret instruction is used to return to the appropriate lawmaking 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.
It was revised for 216 Spring 2006 past David Evans.
Information technology was finally modified by Quentin Carbonneaux to use the AT&T syntax for Yale's CS421.
How To Get One Byte Of Register,
Source: https://flint.cs.yale.edu/cs421/papers/x86-asm/asm.html
Posted by: wilsonsawran56.blogspot.com
0 Response to "How To Get One Byte Of Register"
Post a Comment