Guide to x86 Assembly (2023)

Contents: Registers | Memory andAddressing | Instructions | Calling Convention

This guide describes the basics of 32-bit x86 assembly languageprogramming, covering a small but useful subset of the availableinstructions and assembler directives. There are several differentassembly languages for generating x86 machine code. The one we will usein CS216 is the Microsoft Macro Assembler (MASM) assembler. MASM usesthe standard Intel syntax for writing x86 assembly code.

The full x86 instruction set is large and complex (Intel's x86instruction set manuals comprise over 2900 pages), and we do not coverit all in this guide. For example, there is a 16-bit subset of the x86instruction set. Using the 16-bit programming model can be quitecomplex. It has a segmented memory model, more restrictions on registerusage, and so on. In this guide, we will limit our attention to moremodern aspects of x86 programming, and delve into the instruction setonly in enough detail to get a basic feel for x86 programming.

Resources

Registers

Modern (i.e 386 and beyond) x86 processors have eight 32-bit generalpurpose registers, as depicted in Figure 1. The register names aremostly historical. For example, EAX used to be called theaccumulator since it was used by a number of arithmetic operations, andECX was known as the counter since it was used to hold a loopindex. Whereas most of the registers have lost their special purposes inthe modern instruction set, by convention, two are reserved for specialpurposes — the stack pointer (ESP) and the base pointer(EBP).

For the EAX, EBX, ECX, andEDX registers, subsections may be used. For example, the leastsignificant 2 bytes of EAX can be treated as a 16-bit registercalled AX. The least significant byte of AX can beused as a single 8-bit register called AL, while the mostsignificant byte of AX can be used as a single 8-bit registercalled AH. These names refer to the same physicalregister. When a two-byte quantity is placed into DX, theupdate affects the value of DH, DL, andEDX. These sub-registers are mainly hold-overs from older,16-bit versions of the instruction set. However, they are sometimesconvenient when dealing with data that are smaller than 32-bits(e.g. 1-byte ASCII characters).

When referring to registers in assemblylanguage, the names are not case-sensitive. For example, the namesEAX and eax refer to the same register.


Figure 1. x86 Registers

Memory and Addressing Modes

Declaring Static Data Regions

You can declare static data regions (analogous to global variables) inx86 assembly using special assembler directives for this purpose. Datadeclarations should be preceded by the .DATAdirective. Following this directive, the directives DB, DW, and DD can be used to declare one, two, and four bytedata locations, respectively. Declared locations can be labeled withnames for later reference — this is similar to declaring variables byname, but abides by some lower level rules. For example, locationsdeclared in sequence will be located in memory next to one another.

Example declarations:

.DATA
varDB64; Declare a byte, referred to as location var, containing the value 64.
var2DB?; Declare an uninitialized byte, referred to as location var2.
DB10; Declare a byte with no label, containing the value 10.Its location is var2 + 1.
XDW?; Declarea 2-byte uninitialized value, referred to as location X.
YDD30000; Declare a 4-byte value, referred to aslocation Y, initialized to 30000.

Unlike in high level languages where arrays can have many dimensions andare accessed by indices, arrays in x86 assembly language are simply anumber of cells located contiguously in memory. An array can be declaredby just listing the values, as in the first example below. Two othercommon methods used for declaring arrays of data are the DUP directive and the use of string literals. TheDUP directive tells the assembler to duplicate anexpression a given number of times. For example, 4 DUP(2) is equivalent to 2, 2, 2,2.

Some examples:

ZDD 1, 2, 3; Declare three 4-byte values, initialized to 1,2, and 3. The value of location Z + 8 will be 3.
bytesDB 10 DUP(?); Declare 10 uninitialized bytes starting atlocation bytes.
arrDD 100 DUP(0); Declare 100 4-byte words starting at locationarr,all initialized to 0
strDB 'hello',0; Declare 6 bytes starting at the address str,initialized to the ASCII character valuesfor hello and the null (0)byte.

Addressing Memory

Modern x86-compatible processors are capable of addressing up to232 bytes of memory: memory addresses are 32-bits wide. Inthe examples above, where we used labels to refer to memory regions,these labels are actually replaced by the assembler with 32-bitquantities that specify addresses in memory. In addition to supportingreferring to memory regions by labels (i.e. constant values), the x86provides a flexible scheme for computing and referring to memoryaddresses: up to two of the 32-bit registers and a 32-bit signedconstant can be added together to compute a memory address. One of theregisters can be optionally pre-multiplied by 2, 4, or 8.

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

Some examples of mov instructionsusing address computations are:

mov eax, [ebx];Move the 4 bytes in memory at the address contained in EBX intoEAX
mov [var], ebx; Move the contents of EBX into the 4 bytes atmemory address var. (Note, var is a 32-bitconstant).
mov eax, [esi-4]; Move 4 bytes at memory addressESI + (-4) into EAX
mov [esi+eax], cl; Move the contents of CL into thebyte at address ESI+EAX
mov edx, [esi+4*ebx]; Move the 4 bytes of data at address ESI+4*EBX into EDX

Some examples of invalid address calculations include:

mov eax, [ebx-ecx]; Can only add registervalues
mov [eax+esi+edi], ebx; At most 2 registers in addresscomputation

Size Directives

In general, the intended size of the data item at a given memoryaddress can be inferred from the assembly code instruction in which itis referenced. For example, in all of the above instructions, the sizeof the memory regions could be inferred from the size of the registeroperand. When we were loading a 32-bit register, the assembler couldinfer that the region of memory we were referring to was 4 byteswide. 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 asingle byte in memory.

However, in some cases the size of a referred-to memory region isambiguous. Consider the instruction mov [ebx],2. Should this instruction move the value 2 into thesingle byte at address EBX? Perhapsit should move the 32-bit integer representation of 2 into the 4-bytesstarting at address EBX. Since eitheris a valid possible interpretation, the assembler must be explicitlydirected as to which is correct. The size directives BYTE PTR, WORDPTR, and DWORD PTR serve this purpose,indicating sizes of 1, 2, and 4 bytes respectively.

For example:

mov BYTE PTR [ebx], 2; Move 2 into the single byte at the addressstored in EBX.
mov WORD PTR [ebx], 2; Move the 16-bit integer representationof 2 into the 2 bytes starting at the address in EBX.
mov DWORD PTR [ebx], 2; Move the 32-bit integer representation of 2 into the4 bytes starting at the address in EBX.

Instructions

Machine instructions generally fall into three categories: datamovement, arithmetic/logic, and control-flow. In this section, we willlook at important examples of x86 instructions from each category. Thissection should not be considered an exhaustive list of x86 instructions,but rather a useful subset. For a complete list, see Intel'sinstruction set reference.

We use the following notation:

(Video) Intro to x86 Assembly Language (Part 1)

<reg32>Any32-bit register (EAX, EBX,ECX,EDX,ESI,EDI,ESP, orEBP)
<reg16>Any16-bit register (AX, BX,CX, orDX)
<reg8>Any8-bit register (AH, BH,CH,DH,AL,BL,CL, orDL)
<reg>Any register
<mem>A memory address (e.g., [eax], [var + 4], ordword ptr [eax+ebx])
<con32>Any 32-bit constant
<con16>Any 16-bit constant
<con8>Any 8-bit constant
<con>Any 8-, 16-, or 32-bit constant

Data Movement Instructions

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

The mov instruction copies the data item referred to byits second operand (i.e. register contents, memory contents, or a constantvalue) into the location referred to by its first operand (i.e. a register ormemory). While register-to-register moves are possible, direct memory-to-memorymoves are not. In cases where memory transfers are desired, the source memorycontents must first be loaded into a register, then can be stored to thedestination memory address.

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

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

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

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

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

pop — Pop stack

The pop instruction removes the 4-byte dataelement from the top of the hardware-supported stack into the specifiedoperand (i.e. register or memory location). It first moves the 4 byteslocated at memory location [SP] into thespecified register or memory location, and then increments SP by 4.

Syntax
pop <reg32>
pop <mem>

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

lea — Load effective address

The lea instruction places the address specified by its second operandinto the register specified by its first operand. Note, the contents of the memory location are notloaded, only the effective address is computed and placed into the register.This is useful for obtaining a pointer into a memory region.

Syntax
lea <reg32>,<mem>

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

Arithmetic and Logic Instructions

add — Integer Addition

The add instruction addstogether its two operands, storing the result in its firstoperand. Note, whereas both operands may be registers, at most oneoperand may be a memory location.Syntax
add <reg>,<reg>
add <reg>,<mem>
add <mem>,<reg>
add <reg>,<con>
add <mem>,<con>
Examples
add eax, 10 — EAX ← EAX + 10
add BYTE PTR [var], 10 — add 10 to thesingle byte stored at memory address var

sub — Integer Subtraction

The sub instruction stores in the value ofits first operand the result of subtracting the value of its secondoperand from the value of its first operand. As with addSyntax
sub <reg>,<reg>
sub <reg>,<mem>
sub <mem>,<reg>
sub <reg>,<con>
sub <mem>,<con>
Examples
sub al, ah — AL ← AL - AH
sub eax, 216 — subtract 216 from thevalue stored in EAX

inc, dec — Increment, Decrement

The inc instruction incrementsthe contents of its operand by one. The decinstruction 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.
inc DWORD PTR [var] — add one to the32-bit integer stored at location var

imul — Integer Multiplication

The imul instruction has two basic formats:two-operand (first two syntax listings above) and three-operand (lasttwo syntax listings above).The two-operand form multiplies its two operands together and stores the resultin the first operand. The result (i.e. first) operand must be aregister.The three operand form multiplies its second and third operands togetherand stores the result in its first operand. Again, the result operandmust be a register. Furthermore, the third operand is restricted tobeing a constant value.Syntax
imul <reg32>,<reg32>
imul <reg32>,<mem>
imul <reg32>,<reg32>,<con>
imul <reg32>,<mem>,<con>

Examples

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

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

(Video) Assembly Language in 100 Seconds

idiv — Integer Division

The idiv instruction divides thecontents of the 64 bit integer EDX:EAX (constructed by viewing EDX asthe most significant four bytes and EAX as the least significant fourbytes) by the specified operand value. The quotient result of thedivision is stored into EAX, while the remainder is placed in EDX.

Syntax
idiv <reg32>
idiv <mem>

Examples

idiv ebx — divide the contents ofEDX:EAX by the contents of EBX. Place the quotient in EAX and theremainder in EDX.

idiv DWORD PTR [var] — divide thecontents of EDX:EAX by the 32-bit value stored at memory locationvar. Place the quotient in EAX and the remainder in EDX.

and, or, xor — Bitwise logicaland, or and exclusive or

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

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

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

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

Examples
and eax, 0fH — clear all but the last 4bits of EAX.
xor edx, edx — set the contents of EDXto zero.

not — Bitwise Logical Not

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

Syntax
not <reg>
not <mem>

Example
not BYTE PTR [var] — negate all bits in the byteat the memory location var.

neg — Negate

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

Syntax
neg <reg>
neg <mem>

Example
neg eax — EAX → - EAX

shl, shr — Shift Left, ShiftRight

These instructions shift the bits in their first operand's contentsleft and right, padding the resulting empty bitpositions with zeros. The shifted operand can be shifted up to 31 places. Thenumber of bits to shift is specified by the second operand, which can beeither an 8-bit constant or the register CL. In either case, shifts counts ofgreater then 31 are performed modulo 32.

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

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

(Video) x86 Assembly: Hello World!

Examples

shl eax, 1 — Multiply the value of EAXby 2 (if the most significant bit is 0)

shr ebx, cl — Store in EBX the floor of result of dividing the value of EBXby 2n wheren is the value in CL.

Control Flow Instructions

The x86 processor maintains an instruction pointer (IP) register that isa 32-bit value indicating the location in memory where the currentinstruction starts. Normally, it increments to point to the nextinstruction in memory begins after execution an instruction. The IPregister cannot be manipulated directly, but is updated implicitly byprovided control flow instructions.

We use the notation <label> to refer tolabeled locations in the program text. Labels can be inserted anywherein x86 assembly code text by entering a label name followed by a colon. For example,

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

The second instruction in this code fragment is labeled begin. Elsewhere in the code, we can refer to thememory location that this instruction is located at in memory using themore convenient symbolic name begin. Thislabel is just a convenient way of expressing the location instead of its32-bit value.

jmp — Jump

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

Syntax
jmp <label>

Example
jmp begin — Jump to the instructionlabeled begin.

jcondition —Conditional Jump

These instructions are conditional jumps that are based on the status ofa set of condition codes that are stored in a special register calledthe machine status word. The contents of the machine statusword include information about the last arithmetic operationperformed. For example, one bit of this word indicates if the lastresult was zero. Another indicates if the last result wasnegative. Based on these condition codes, a number of conditional jumpscan be performed. For example, the jzinstruction performs a jump to the specified operand label if the resultof the last arithmetic operation was zero. Otherwise, control proceedsto the next instruction in sequence.

A number of the conditional branches are given names that areintuitively based on the last operation performed being a specialcompare instruction, cmp (see below). For example, conditional branchessuch as jle and jne are based on first performing a cmp operationon the desired operands.

Syntax
je <label> (jump when equal)
jne <label> (jump when not equal)
jz <label> (jump when last result was zero)
jg <label> (jump 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 eax, ebx
jle done

If the contents of EAX are less than or equal to the contents of EBX,jump to the label done. Otherwise, continue to the nextinstruction.

cmp — Compare

Compare the values of the two specified operands, setting the conditioncodes in the machine status word appropriately. This instruction is equivalent to the sub instruction, except theresult of the subtraction is discarded instead of replacing the firstoperand.

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

Example
cmp DWORD PTR [var], 10
jeq loop

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

call, ret — Subroutinecall and return

(Video) x86 Assembly Crash Course

These instructions implement a subroutine call and return.The call instruction first pushes the currentcode location onto the hardware supported stack in memory (see the push instruction for details), and then performsan unconditional jump to the code location indicated by the labeloperand. Unlike the simple jump instructions, the call instruction saves the location to return towhen the subroutine completes.

The ret instruction implements a subroutinereturn mechanism. This instruction first pops a code location off thehardware supported in-memory stack (see the pop instruction for details). It then performs anunconditional jump to the retrieved code location.

Syntax
call <label>
ret

Calling Convention

To allow separate programmers to share code and develop libraries foruse by many programs, and to simplify the use of subroutines in general,programmers typically adopt a common calling convention. Thecalling convention is a protocol about how to call and return fromroutines. For example, given a set of calling convention rules, aprogrammer need not examine the definition of a subroutine to determinehow parameters should be passed to that subroutine. Furthermore, given aset of calling convention rules, high-level language compilers can bemade to follow the rules, thus allowing hand-coded assembly languageroutines and high-level language routines to call one another.

In practice, many calling conventions are possible. We will use thewidely used C language calling convention. Following this conventionwill allow you to write assembly language subroutines that are safelycallable from C (and C++) code, and will also enable you to call Clibrary functions from your assembly language code.

The C calling convention is based heavily on the use of thehardware-supported stack. It is based on the push, pop, call, and retinstructions. Subroutine parameters are passed on the stack. Registersare saved on the stack, and local variables used by subroutines areplaced in memory on the stack. The vast majority of high-levelprocedural languages implemented on most processors have used similarcalling conventions.

The calling convention is broken into two sets of rules. The first setof rules is employed by the caller of the subroutine, and the second setof rules is observed by the writer of the subroutine (the callee). Itshould be emphasized that mistakes in the observance of these rulesquickly result in fatal program errors since the stack will be left inan inconsistent state; thus meticulous care should be used whenimplementing the call convention in your own subroutines.

>
Stack during Subroutine Call
[Thanks to Maxence Faldor for providing a correct figure and to James Peterson for finding and fixing the bug inthe original version of this figure!]

A good way to visualize the operation of the calling convention is todraw the contents of the nearby region of the stack during subroutineexecution. The image above depicts the contents of the stack during theexecution of a subroutine with three parameters and three localvariables. The cells depicted in the stackare 32-bit wide memory locations, thus the memory addresses of the cellsare 4 bytes apart. The firstparameter resides at an offset of 8 bytes from the base pointer. Abovethe parameters on the stack (and below the base pointer), the call instruction placed the return address, thusleading to an extra 4 bytes of offset from the base pointer to the firstparameter. When the ret instruction is usedto return from the subroutine, it will jump to the return address storedon the stack.

Caller Rules

To make a subrouting call, the caller should:

  1. Before calling a subroutine, the caller shouldsave the contents of certain registers that are designatedcaller-saved. The caller-saved registers are EAX, ECX, EDX.Since the called subroutine is allowed to modify these registers, if thecaller relies on their values after the subroutine returns, the callermust push the values in these registers onto the stack (so they can berestore after the subroutine returns.
  2. To pass parameters to the subroutine, push them onto the stackbefore the call. The parameters should be pushed in inverted order(i.e. last parameter first). Since the stack grows down, the first parameter will be stored at the lowest address (this inversion ofparameters was historically used to allow functions to be passed avariable number of parameters).
  3. To call the subroutine, use the callinstruction. This instruction places the return address on top of theparameters on the stack, and branches to the subroutine code. Thisinvokes the subroutine, which should follow the callee rules below.

After the subroutine returns (immediately following the call instruction), the caller can expect to findthe return value of the subroutine in the register EAX. To restore themachine state, the caller should:

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

Example
The code below shows a function call that follows the caller rules. Thecaller is calling a function _myFunc that takes three integerparameters. First parameter is in EAX, the second parameter is theconstant 216; the third parameter is in memory location var.

push [var] ; Push last parameter firstpush 216 ; Push the second parameterpush eax ; Push first parameter lastcall _myFunc ; Call the function (assume C naming)add esp, 12

Note that after the call returns, the caller cleans up the stack usingthe add instruction. We have 12 bytes (3parameters * 4 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 now available for use in theregister EAX. The values of the caller-saved registers (ECX and EDX),may have been changed. If the caller uses them after the call, it wouldhave needed to save them on the stack before the call and restore themafter it.

Callee Rules

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

  1. Push the value of EBP onto the stack, and then copy the value of ESPinto EBP using the following instructions:
     push ebp mov ebp, esp
    This initial action maintains the base pointer, EBP. The basepointer is used by convention as a point of reference for findingparameters and local variables on the stack. When a subroutine isexecuting, the base pointer holds a copy of the stack pointer value fromwhen the subroutine started executing. Parameters and local variableswill always be located at known, constant offsets away from the basepointer value. We push the old base pointer value at the beginning ofthe subroutine so that we can later restore the appropriate base pointervalue for the caller when the subroutine returns. Remember, the calleris not expecting the subroutine to change the value of the basepointer. We then move the stack pointer into EBP to obtain our point ofreference for accessing parameters and local variables.
  2. Next, allocate local variables by making space on thestack. Recall, the stack grows down, so to make space on the top of the stack, the stack pointer should be decremented. The amount by which the stackpointer is decremented depends on the number and size of local variablesneeded. For example, if 3 local integers (4 bytes each) were required,the stack pointer would need to be decremented by 12 to make space forthese local variables (i.e., subesp,12).As with parameters, local variables will be located at known offsetsfrom the base pointer.
  3. Next, save the values of the callee-saved registers thatwill be used by the function. To save registers, push them onto thestack. The callee-saved registers are EBX, EDI, and ESI (ESP and EBPwill also be preserved by the calling convention, but need not be pushedon the stack during this step).

After these three actions are performed, the body of thesubroutine may proceed. When the subroutine is returns, it must followthese 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 by popping themfrom the stack. The registers should be popped in the inverseorder that they were pushed.
  3. Deallocate local variables. The obvious way to do this might be toadd the appropriate value to the stack pointer (since the space wasallocated by subtracting the needed amount from the stack pointer). Inpractice, a less error-prone way to deallocate the variables is to move the value in the base pointer into the stack pointer: movesp,ebp. This works because thebase pointer always contains the value that the stack pointer contained immediatelyprior to the allocation of the local variables.
  4. Immediately before returning, restore the caller's base pointervalue by popping EBP off the stack. Recall that the first thing we did onentry to the subroutine was to push the base pointer to save its oldvalue.
  5. Finally, return to the caller by executing a ret instruction. This instruction will find andremove the appropriate return address from the stack.

Note that the callee's rules fall cleanly into two halves that arebasically mirror images of one another. The first half of the rulesapply to the beginning of the function, and are commonly saidto define the prologue to the function. The latter half of therules apply to the end of the function, and are thus commonly said todefine the epilogue of the function.Example
Here is an example function definition that follows the callee rules:

.486.MODEL FLAT.CODEPUBLIC _myFunc_myFunc PROC ; Subroutine Prologue push ebp ; Save the old base pointer value. mov ebp, esp ; Set the new base pointer value. sub esp, 4 ; Make room for one 4-byte local variable. push edi ; Save the values of registers that the function push esi ; will modify. This function uses EDI and ESI. ; (no need to save EBX, EBP, or ESP) ; Subroutine Body mov eax, [ebp+8] ; Move value of parameter 1 into EAX mov esi, [ebp+12] ; Move value of parameter 2 into ESI mov edi, [ebp+16] ; Move value of parameter 3 into EDI mov [ebp-4], edi ; Move EDI into the local variable add [ebp-4], esi ; Add ESI into the local variable add eax, [ebp-4] ; Add the contents of the local variable ; into EAX (final result) ; Subroutine Epilogue pop esi ; Recover register values pop edi mov esp, ebp ; Deallocate local variables pop ebp ; Restore the caller's base pointer value ret_myFunc ENDPEND

The subroutine prologue performs the standard actions of saving asnapshot of the stack pointer in EBP (the base pointer), allocatinglocal variables by decrementing the stack pointer, and saving registervalues on the stack.

In the body of the subroutine we can see the use of the basepointer. Both parameters and local variables are located at constantoffsets from the base pointer for the duration of the subroutinesexecution. In particular, we notice that since parameters were placedonto the stack before the subroutine was called, they are always locatedbelow the base pointer (i.e. at higher addresses) on the stack. Thefirst parameter to the subroutine can always be found at memory locationEBP + 8, the second at EBP + 12, the third at EBP + 16. Similarly,since local variables are allocated after the base pointer is set, theyalways reside above the base pointer (i.e. at lower addresses) on thestack. In particular, the first local variable is always located atEBP - 4, the second at EBP - 8, and so on. This conventional use of thebase pointer allows us to quickly identify the use of local variablesand parameters within a function body.

The function epilogue is basically a mirror image of the functionprologue. The caller's register values are recovered from the stack,the local variables are deallocated by resetting the stack pointer, thecaller's base pointer value is recovered, and the ret instruction isused to return to the appropriate code location in the caller.

Using these Materials

These materials are released under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License. We are delighted when people want to use or adapt the course materials we developed, and you are welcome to reuse and adapt these materials for any non-commercial purposes (if you would like to use them for a commercial purpose, please contact David Evans for more information).If you do adapt or use these materials, please include a credit like"Adapted from materials developed for University of Virginia cs216 byDavid Evans. This guide was revised for cs216 by David Evans, based onmaterials originally created by Adam Ferrari many years ago, and sinceupdated by Alan Batson, Mike Lack, and Anita Jones." and a link back tothis page.

(Video) Assembly x86 GUIDE for beginners: Asm and Disasm

CS216: Program and Data Representation
University of Virginia
David Evans
evans@cs.virginia.edu
Using these Materials

FAQs

How long does it take to learn x86 assembly? ›

How long does it take to master assembly (x86) programming language? Thanks for the A2A. For bright capable programmers who do not know any assembly language, it has been my experience (I have trained x86 asm programmers) that 2 years are needed of pure x86 assembly programming in order to master it.

What are the 32-bit instructions? ›

The 32-bit instruction has six fields: cond, op, funct, Rn, Rd, and Src2. The operation the instruction performs is encoded in the fields highlighted in blue: op (also called the opcode or operation code) and funct or function code; the cond field encodes conditional execution based on flags described in Section 6.3.

How many instructions does x86 assembly have? ›

al. states that the current x86-64 design “contains 981 unique mnemonics and a total of 3,684 instruction variants” [2].

How hard is assembly code? ›

Programming in assembly language is hard work; it's slow, tedious and needs a lot of concentration. You have no variables, just registers and memory locations.

What is the hardest programming language to learn? ›

Malbolge. This language is so hard that it has to be set aside in its own paragraph. Malbolge is by far the hardest programming language to learn, which can be seen from the fact that it took no less than two years to finish writing the first Malbolge code.

Is ARM harder than X86? ›

X86 processors use more registers and place a greater emphasis on performance and high throughputs. As a result, there is some excess heat production and electricity consumption. ARM devices are substantially more energy-efficient by design. They have a simpler design because they are RISC processors.

What is 32-bit vs 64-bit for dummies? ›

Simply put, a 64-bit processor is more capable than a 32-bit processor because it can handle more data at once. A 64-bit processor can store more computational values, including memory addresses, which means it can access over 4 billion times the physical memory of a 32-bit processor. That's just as big as it sounds.

How many 32-bit patterns are there? ›

How many integers can be represented in 32 bits? Using 32 bits up to 4,294,967,296 pieces of unique data can be stored. As signed integers, the range is -2,147,483,648 to 2,147,483,647.

Is 32-bit used anymore? ›

Yes. There are many 32-bit PCs still in use in schools, homes, and businesses. They serve their purpose and don't really need to be upgraded to 64-bit hardware. In addition, there are billions of embedded microcontrollers that are 32-bit, 16-bit, or 8-bit.

What is the longest x86 instruction? ›

General Overview. An x86-64 instruction may be at most 15 bytes in length. It consists of the following components in the given order, where the prefixes are at the least-significant (lowest) address in memory: Legacy prefixes (1-4 bytes, optional)

What is the longest instruction name in x86? ›

The x86 instruction set (16, 32 or 64 bit, all variants/modes) guarantees / requires that instructions are at most 15 bytes. Anything beyond that will give an "invalid opcode". You can't achieve that without using redundant prefixes (e.g. multiple 0x66 or 0x67 prefixes, for example).

What are the most important x86 instructions? ›

PUSH and POP are the two most popular instructions when working with the stack. PUSH instruction is used to push a value onto the stack and the POP instruction is used to pop a value off the stack and store it into a register.

Do people still code in assembly? ›

How Are Assembly Languages Used Today? Though considered lower level languages compared to more advanced languages, assembly languages are still used. Assembly language is used to directly manipulate hardware, access specialized processor instructions, or evaluate critical performance issues.

How much do assembly coders make? ›

Assembly Language Programmer Salary
Annual SalaryMonthly Pay
Top Earners$141,500$11,791
75th Percentile$108,500$9,041
Average$85,889$7,157
25th Percentile$57,500$4,791

Does Bill Gates know assembly language? ›

Bill Gates was proficient at BASIC and assembly(most popular languages those days). However, Microsoft developed C# as a replacement for Java, after they had a falling out with Sun over Java.

What is the #1 hardest language? ›

Across multiple sources, Mandarin Chinese is the number one language listed as the most challenging to learn. The Defense Language Institute Foreign Language Center puts Mandarin in Category IV, which is the list of the most difficult languages to learn for English speakers.

What is the hottest programming language right now? ›

The best in-demand programming languages to learn in 2023 are:
  • Python.
  • JavaScript.
  • PHP.
  • C++
  • TypeScript.
  • Java.
  • Swift.
  • Kotlin.
Apr 26, 2023

Which programming language has highest salary? ›

  • Clojure. Salary: $106,644. Clojure, according to StackOverflow, is the highest-paying programming language. ...
  • Erlang. Salary: $103,000. At number two we have Erlang. ...
  • F# Salary: $95,526. ...
  • LISP. Salary: $95,000. ...
  • Ruby. Salary: $93,000. ...
  • Elixir. Salary: $92,959. ...
  • Scala. Salary: $92,780.
Jan 25, 2023

Why does Intel still use x86? ›

The x86 processors allow you to perform several activities at the same time from a single instruction. Also, they can perform numerous simultaneous tasks without any of them being affected. This makes them very sophisticated and advanced processors, allowing many complex calculations in a short time.

Why is ARM replacing x86? ›

ARM chips, by design, are much more power-efficient than x86 CPUs. They're RISC processors, so they're simpler in design. Also, things like ARM's big. LITTLE configuration help battery life and overall efficiency greatly.

Will ARM eventually replace x86? ›

no, not likely, anytime soon. Apple switch to ARM for computers as well as phones makes sense for them — unifying architecture and software. Windows machines are still x86 and will like remain so — due to legacy software.

Why use 32-bit over 64? ›

When it comes to computers, the difference between 32-bit and a 64-bit is all about processing power. Computers with 32-bit processors are older, slower, and less secure, while a 64-bit processor is newer, faster, and more secure.

Does it matter if I use 32-bit or 64-bit? ›

In such cases, because a 64-bit operating system can handle large amounts of memory more efficiently than a 32-bit operating system, a 64-bit system can be more responsive when running several programs at the same time and switching between them frequently.

What is the main advantage of 64-bit over 32-bit? ›

Using 64 bit operating system with 64 bit processer, the system can perform an increased number of calculations per second. As a result, it increases the processing power and makes a computer run faster. This is limited in case of 32 bit operating system. You can multi-task, switch between various application etc.

Why is 11 three in binary code? ›

3 in binary is 11. Unlike the decimal number system where we use the digits 0 to 9 to represent a number, in a binary system, we use only 2 digits that are 0 and 1 (bits). We have used 2 bits to represent 3 in binary.

What is the largest 32-bit value? ›

A 32-bit signed integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

What is the biggest number with 32 bits? ›

The number 2,147,483,647 (or hexadecimal 7FFFFFFF16) is the maximum positive value for a 32-bit signed binary integer in computing.

How much RAM can 64bit use? ›

Memory in 32 and 64-Bit Architectures

In terms of Random Access Memory, 32-bit architectures can address 4GB of memory, maximum. A 64-bit architecture, in turn, has a theoretical limit of addressing 16 million TB of memory.

Can Windows 10 run on 32-bit processor? ›

In general, yes, you can . the fact that they are 32-bit is irrelevant. Both 64-bit Windows 10 and 32-bit Windows 10 can run 32-bit programs.

Is there 128-bit processor? ›

While there are currently no mainstream general-purpose processors built to operate on 128-bit integers or addresses, a number of processors do have specialized ways to operate on 128-bit chunks of data.

What is the most power efficient x86? ›

AMD EPYC™ processors power the most energy-efficient x86 servers in the game, delivering exceptional performance and helping lower energy consumption.

Is x86 obsolete? ›

ARM will be the dominant CPU architecture going forward. In a few years, x86 will be relegated to specialty use cases. All new consumer devices and most cloud services will be based on ARM.

What is the smallest x86 board computer? ›

LattePanda V1 - The smallest x86 Windows Single Board Computer
  • LattePanda V1 features Intel Atom® x5-Z8350 processor which is based on x86 architecture. ...
  • The LattePanda V1 is available in various RAM and storage configurations, allowing you to choose the one that best suits your individual needs.

How many registers does x86 have? ›

The x86 architecture contains eight 32-bit General Purpose Registers (GPRs). These registers are mainly used to perform address calculations, arithmetic and logical calculations. Four of the GPRs can be treated as a 32-bit quantity, a 16-bit quantity or as two 8-bit quantities.

Is x86 old? ›

The x86 architectures were based on the Intel 8086 microprocessor chip, initially released in 1978.

How long is a word in x86? ›

x86 Architecture

In the x86 PC (Intel, AMD, etc.), although the architecture has long supported 32-bit and 64-bit registers, its native word size stems back to its 16-bit origins, and a "single" word is 16 bits. A "double" word is 32 bits.

Is x86 always 32-bit? ›

The x86 architecture is based on Intel's 8086 (hence the name) microprocessor and its 8088 variant. At first, it was a 16-bit instruction set for 16-bit processors, and later it grew to 32-bit instruction sets. The number of bits signifies how much information the CPU can process per cycle.

Should I use x86 or ARM? ›

This is why ARM processors dominate small electronics and mobile devices like smartphones, tablets, and even Raspberry Pi systems. x86 architectures are more common in servers, PCs, and even laptops where there is a preference for speed and flexibility in real time, and fewer constraints on cooling and size.

What does 86 mean in x86? ›

The term x86 was coined as a result of the original Intel 8086 chip ending with the number 86. The x86 processor had additional segment registers for accessing multiple data segments at the same interval.

Why do hackers use assembly language? ›

Assembly language helps a hacker manipulate systems straight up at the architectural level. It is also the most appropriate coding language to build malware like viruses and trojans. Assembly is also the go-to choice if you want to reverse engineer a piece of software that has already been compiled.

Is assembly code easier than machine code? ›

The machine languages consist of 1s and 0s as binary digits. The assembly languages have a similar syntax to that of the English language- thus making it easy for general users to understand (other than the programmers).

Why do programmers not use assembly language? ›

However, writing code in assembly language can be time-consuming and requires a deep understanding of hardware architecture. Therefore, Programmers often use assembly language only for specific tasks where its unique strengths are needed, while they use higher-level languages for other programming tasks.

How much do x86 developers make a year? ›

The median salary approximately calculated from salary profiles measured so far is $469k per year.

Is assembler a good career? ›

No, assembly is not a good career.

The average mid-tier salary range for workers in the United States is $45-70,000. Unfortunately, assemblers usually don't make around that range and often make around the $30-40,000 range.

Is coding a lucrative job? ›

The national average salary for a computer programmer or coder is $73,473 per year . However, once you specialize in a certain area of coding , you have the potential to earn a higher wage. Salary expectations differ based on your job location and years of experience.

Does Mark Zuckerberg know coding? ›

Without Zuckerberg, our idea of social media would be vastly different than how we see it today. It's safe to say that Mark owes most of his success to his innate ability to code which he acquired early in life.

How did Mark Zuckerberg learn to code? ›

Zuckerberg's passion for coding appeared at a young age. His father was a dentist though he undertook programming basics on Atari as a hobby; thanks to it, young Zuckerberg got involved into coding and received his first PC at as early as 9 years old. Since then, Mark had had private coding lessons.

Does Jeff Bezos know how do you code? ›

Jeff Bezos is not a programmer. Larry Ellison is not really a programmer, he did write some mainframe code when he was in his twenties. He and Bezos are though awesome kickass business people.

How long is an x86-64 instruction set? ›

An x86-64 instruction may be at most 15 bytes in length.

Is x86 assembly a low level language? ›

Regarded as a programming language, assembly is machine-specific and low-level. Like all assembly languages, x86 assembly uses mnemonics to represent fundamental CPU instructions, or machine code.

Should I learn ARM or x86 assembly? ›

ARM assembly has all the features of a good assembly language. x86 has all the features of a horrible assembly language. ARM is much better for beginners. Once you have learned ARM, it is relatively easy to learn x86, and doing that will REALLY make you appreciate the beauty of ARM.

Is it worth learning assembly code? ›

If you want to know what is really going on at every step of execution, learning assembly language is the best way to achieve that goal. Assembly knowledge also allows you to explore what your compiler does to convert high-level conditional statements and loops in C to machine code.

What is the longest x64 instruction? ›

The maximum length of an Intel 64 and IA-32 instruction remains 15 bytes. You can construct instructions that would encode to more than 15 bytes, but such instructions would be illegal and would probably not execute.

Why is x86 slower than ARM? ›

ARM chips, by design, are much more power-efficient than x86 CPUs. They're RISC processors, so they're simpler in design. Also, things like ARM's big. LITTLE configuration help battery life and overall efficiency greatly.

How many bits are needed to code 64 operations? ›

Since there are 64 registers → 6 bits are needed (ceil(log264) = 6 bits) for each register. It implies, DR, SR1 and SR2 all require 18 bits in all. No of bits available for OPCODES = (32 – 18) = 14 bits.

Is assembly still used today? ›

How Are Assembly Languages Used Today? Though considered lower level languages compared to more advanced languages, assembly languages are still used. Assembly language is used to directly manipulate hardware, access specialized processor instructions, or evaluate critical performance issues.

Why do programmers still use low-level languages? ›

The advantages of low-level languages are: They allow a programmer to create optimised programs. When a computer system has limited resources (processing power and memory) low-level languages allow a programmer to more directly control how the resources are used.

Is assembly language harder than machine language? ›

Assembly language falls between a high-level programming language and Machine language. it has syntaxes similar to English, but more difficult than high-level programming languages. To program in assembly language, one should have understood at hardware level like computer architecture, registers, etc.

Is assembler obsolete? ›

The bottom line is that assembly language skills are far from obsolete, but many highly skilled and very productive embedded software developers may be limited to competent assembly code reading.

Is Raspberry Pi ARM or x86? ›

This is why ARM processors dominate small electronics and mobile devices like smartphones, tablets, and even Raspberry Pi systems. x86 architectures are more common in servers, PCs, and even laptops where there is a preference for speed and flexibility in real time, and fewer constraints on cooling and size.

Why use assembly over C? ›

Assembler is a lower level programming language than C,so this makes it a good for programming directly to hardware. Hardware programming can be done directly in either language. The only things you can't do in C are accessing stack pointers and condition registers etc, of the CPU core itself.

Is assembly language important for hackers? ›

Assembly is the best programming language for ethical hacking and building malware like viruses and trojans. With the help of this, you can reverse engineer a piece of software that has already been created and compiled.

Videos

1. x86 Assembly Beginner Guide Using the Forth Programming Language (SwiftForth)
(code4th)
2. You Can Learn Assembly in 10 Minutes (it’s easy)
(Low Level Learning)
3. x86-64 Assembly Programming Part 1: Registers, Data Movement, and Addressing Modes
(Gedare Bloom)
4. Assembly I: Register operands | x86 mov instruction | Intel vs AT&T syntax | Assembly crash Course
(Tech Instance)
5. Top 10 Craziest Assembly Language Instructions
(Creel)
6. x86-64 Assembly Crash Course
(Elevate Cyber)

References

Top Articles
Latest Posts
Article information

Author: Laurine Ryan

Last Updated: 09/12/2023

Views: 5553

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.