Learn Assembly Language

This project was put together to teach myself NASM 64bit assembly language on linux.

Github Project »

Lesson 1

The obligatory 'Hello, world!'

Introduction to the Linux System Call Table. In this lesson we use software interrupts to request system functions from the kernel in order to print out 'Hello World!' to the console.

View lesson »

Lesson 2

Proper program exit

A very brief lesson about memory addresses, sequential code execution and how to properly terminate a program without errors.

View details »

Lesson 3

Calculate string length

What if we wanted to output something that we don't know the length of? Like user input? Learn about loops, labels and pointer arithmic.

View details »

Lesson 4

Subroutines

Introduction to the stack and how to write clean, reusable code in assembly.

View lesson »

Lesson 5

External include files

To further simplify our code we can move our subroutines into an external include file.

View details »

Lesson 6

NULL terminating bytes

A quick lesson on how memory is handled. This lesson also fixes the duplication bug we added in lesson 5.

View details »

Lesson 7

Linefeeds

How you can use the stack to print linefeeds after strings and an introduction to the Extended Stack Pointer ESP.

View lesson »

Lesson 8

Passing arguments

Passing arguments to your program from the command line.

View lesson »

Lesson 9

User input

Introduction to the BSS section and how to trigger a call to sys_read to process user input.

View lesson »

Lesson 10

Count to 10

Introduction to numbers and counting in assembly.

View lesson »

Lesson 11

Count to 10 (itoa)

Introduction to ASCII and how to convert integers to their string representations in assembly.

View lesson »

Lesson 12

Calculator - addition

Introduction to calulating numbers in assembly. This tutorial describes a simple program to add two numbers together.

View lesson »

Lesson 13

Calculator - subtraction

Introduction to calulating numbers in assembly. This tutorial describes a simple program to subtract one number from another.

View lesson »

Lesson 14

Calculator - multiplication

Introduction to calulating numbers in assembly. This tutorial describes a simple program to multiply two numbers together.

View lesson »

Lesson 15

Calculator - division

Introduction to calulating numbers in assembly. This tutorial describes a simple program to divide one number by another.

View lesson »

Lesson 16

Calculator (atoi)

This program takes a series of passed string arguments, converts them to integers and adds them all together.

View lesson »

Lesson 17

Namespace

Introduction to how NASM handles namespace when it comes to global and local labels.

View lesson »

Lesson 18

Fizz Buzz

The Fizz Buzz programming challenge recreated in NASM.

View lesson »

Lesson 19

Execute Command

In this lesson we replace the currently running process with a new process that executes a command.

View lesson »

Lesson 20

Process Forking

In this lesson we create a new process that duplicates our current process.

View lesson »

Lesson 21

Telling the time

In this lesson we ask the kernel for the current unix timestamp.

View lesson »


Lesson 1

Hello, world!

First, some background

Assembly language is bare-bones. The only interface a programmer has above the actual hardware is the kernel itself. In order to build useful programs in assembly we need to use the linux system calls provided by the kernel. These system calls are a library built into the operating system to provide functions such as reading input from a keyboard and writing output to the screen.

When you invoke a system call the kernel will immediately suspend execution of your program. It will then contact the necessary drivers needed to perform the task you requested on the hardware and then return control back to your program.

Note: Drivers are called drivers because the kernel literally uses them to drive the hardware.

We can accomplish this all in assembly by loading EAX with the function number (operation code OPCODE) we want to execute and filling the remaining registers with the arguments we want to pass to the system call. A software interrupt is requested with the INT instruction and the kernel takes over and calls the function from the library with our arguments. Simple.

For example requesting an interrupt when EAX=1 will call sys_exit and requesting an interrupt when EAX=4 will call sys_write instead. EBX, ECX & EDX will be passed as arguments if the function requires them. Click here to view an example of a Linux System Call Table and its corresponding OPCODES.

Writing our program

Firstly we create a variable 'msg' in our .data section and assign it the string we want to output in this case 'Hello, world!'. In our .text section we tell the kernel where to begin execution by providing it with a global label _start: to denote the programs entry point.

We will be using the system call sys_write to output our message to the console window. This function is assigned OPCODE 4 in the Linux System Call Table. The function also takes 3 arguments which are sequentially loaded into EDX, ECX and EBX before requesting a software interrupt which will perform the task.

The arguments passed are as follows:

  • EDX will be loaded with the length (in bytes) of the our string.
  • ECX will be loaded with the address of our variable created in the .data section.
  • EBX will be loaded with the file we want to write to – in this case STDOUT.
The datatype and meaning of the arguments passed can be found in the function's definition.

We compile, link and run the program using the commands below.

helloworld.asm
                            ; Hello World Program - asmtutor.com
                            ; Compile with: nasm -f elf helloworld.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld.o -o helloworld
                            ; Run with: ./helloworld

                            SECTION .data
                            msg     db      'Hello World!', 0Ah     ; assign msg variable with your message string

                            SECTION .text
                            global  _start

                            _start:

                                mov     edx, 13     ; number of bytes to write - one for each letter plus 0Ah (line feed character)
                                mov     ecx, msg    ; move the memory address of our message string into ecx
                                mov     ebx, 1      ; write to the STDOUT file
                                mov     eax, 4      ; invoke SYS_WRITE (kernel opcode 4)
                                int     80h
                            
~$ nasm -f elf helloworld.asm ~$ ld -m elf_i386 helloworld.o -o helloworld ~$ ./helloworld Hello World! Segmentation fault

Error: Segmentation fault


Lesson 2

Proper program exit

Some more background

After successfully learning now to execute a system call in Lesson 1 we now need to learn about one of the most important system calls in the kernel, sys_exit.

Notice how after our 'Hello, world!' program ran we got a Segmentation fault? Well, computer programs can be thought of as a long strip of instructions that are loaded into memory and divided up into sections (or segments). This general pool of memory is shared between all programs and can be used to store variables, instructions, other programs or anything really. Each segment is given an address so that information stored in that section can be found later.

To execute a program that is loaded in memory, we use the global label _start: to tell the operating system where in memory our program can be found and executed. Memory is then accessed sequentially following the program logic which determines the next address to be accessed. The kernel jumps to that address in memory and executes it.

It's important to tell the operating system exactly where it should begin execution and where it should stop. In Lesson 1 we didn't tell the kernel where to stop execution. So, after we called sys_write the program continued sequentially executing the next address in memory, which could have been anything. We don't know what the kernel tried to execute but it caused it to choke and terminate the process for us instead - leaving us the error message of 'Segmentation fault'. Calling sys_exit at the end of all our programs will mean the kernel knows exactly when to terminate the process and return memory back to the general pool thus avoiding an error.

Writing our program

Sys_exit has a simple function definition. In the Linux System Call Table it is allocated OPCODE 1 and is passed a single argument through EBX.

In order to execute this function all we need to do is:

  • Load EBX with 0 to pass zero to the function meaning 'zero errors'.
  • Load EAX with 1 to call sys_exit.
  • Then request an interrupt on libc using INT 80h.

We then compile, link and run it again.

Note: Only new code added in each lesson will be commented.

helloworld.asm
                            ; Hello World Program - asmtutor.com
                            ; Compile with: nasm -f elf helloworld.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld.o -o helloworld
                            ; Run with: ./helloworld

                            SECTION .data
                            msg     db      'Hello World!', 0Ah

                            SECTION .text
                            global  _start

                            _start:

                                mov     edx, 13
                                mov     ecx, msg
                                mov     ebx, 1
                                mov     eax, 4
                                int     80h

                                mov     ebx, 0      ; return 0 status on exit - 'No Errors'
                                mov     eax, 1      ; invoke SYS_EXIT (kernel opcode 1)
                                int     80h
                            
~$ nasm -f elf helloworld.asm ~$ ld -m elf_i386 helloworld.o -o helloworld ~$ ./helloworld Hello World!

Lesson 3

Calculate string length

Firstly, some background

Why do we need to calculate the length of a string?

Well sys_write requires that we pass it a pointer to the string we want to output in memory and the length in bytes we want to print out. If we were to modify our message string we would have to update the length in bytes that we pass to sys_write as well, otherwise it will not print correctly.

You can see what I mean using the program in Lesson 2. Modify the message string to say 'Hello, brave new world!' then compile, link and run the new program. The output will be 'Hello, brave ' (the first 13 characters) because we are still only passing 13 bytes to sys_write as its length. It will be particularly necessary when we want to print out user input. As we won't know the length of the data when we compile our program, we will need a way to calculate the length at runtime in order to successfully print it out.

Writing our program

To calculate the length of the string we will use a technique called pointer arithmetic. Two registers are initialised pointing to the same address in memory. One register (in this case EAX) will be incremented forward one byte for each character in the output string until we reach the end of the string. The original pointer will then be subtracted from EAX. This is effectively like subtraction between two arrays and the result yields the number of elements between the two addresses. This result is then passed to sys_write replacing our hard coded count.

The CMP instruction compares the left hand side against the right hand side and sets a number of flags that are used for program flow. The flag we're checking is the ZF or Zero Flag. When the byte that EAX points to is equal to zero the ZF flag is set. We then use the JZ instruction to jump, if the ZF flag is set, to the point in our program labeled 'finished'. This is to break out of the nextchar loop and continue executing the rest of the program.

helloworld-len.asm
                            ; Hello World Program (Calculating string length)
                            ; Compile with: nasm -f elf helloworld-len.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld-len.o -o helloworld-len
                            ; Run with: ./helloworld-len

                            SECTION .data
                            msg     db      'Hello, brave new world!', 0Ah ; we can modify this now without having to update anywhere else in the program

                            SECTION .text
                            global  _start

                            _start:

                                mov     ebx, msg        ; move the address of our message string into EBX
                                mov     eax, ebx        ; move the address in EBX into EAX as well (Both now point to the same segment in memory)

                            nextchar:
                                cmp     byte [eax], 0   ; compare the byte pointed to by EAX at this address against zero (Zero is an end of string delimiter)
                                jz      finished        ; jump (if the zero flagged has been set) to the point in the code labeled 'finished'
                                inc     eax             ; increment the address in EAX by one byte (if the zero flagged has NOT been set)
                                jmp     nextchar        ; jump to the point in the code labeled 'nextchar'

                            finished:
                                sub     eax, ebx        ; subtract the address in EBX from the address in EAX
                                                        ; remember both registers started pointing to the same address (see line 15)
                                                        ; but EAX has been incremented one byte for each character in the message string
                                                        ; when you subtract one memory address from another of the same type
                                                        ; the result is number of segments between them - in this case the number of bytes

                                mov     edx, eax        ; EAX now equals the number of bytes in our string
                                mov     ecx, msg        ; the rest of the code should be familiar now
                                mov     ebx, 1
                                mov     eax, 4
                                int     80h

                                mov     ebx, 0
                                mov     eax, 1
                                int     80h
                            
~$ nasm -f elf helloworld-len.asm ~$ ld -m elf_i386 helloworld-len.o -o helloworld-len ~$ ./helloworld-len Hello, brave new world!

Lesson 4

Subroutines

Introduction to subroutines

Subroutines are functions. They are reusable pieces of code that can be called by your program to perform various repeatable tasks. Subroutines are declared using labels just like we've used before (eg. _start:) however we don't use the JMP instruction to get to them - instead we use a new instruction CALL. We also don't use the JMP instruction to return to our program after we have run the function. To return to our program from a subroutine we use the instruction RET instead.

Why don't we JMP to subroutines?

The great thing about writing a subroutine is that we can reuse it. If we want to be able to use the subroutine from anywhere in the code we would have to write some logic to determine where in the code we had jumped from and where we should jump back to. This would litter our code with unwanted labels. If we use CALL and RET however, assembly handles this problem for us using something called the stack.

Introduction to the stack

The stack is a special type of memory. It's the same type of memory that we've used before however it's special in how it is used by our program. The stack is what is call Last In First Out memory (LIFO). You can think of the stack like a stack of plates in your kitchen. The last plate you put on the stack is also the first plate you will take off the stack next time you use a plate.

The stack in assembly is not storing plates though, its storing values. You can store a lot of things on the stack such as variables, addresses or other programs. We need to use the stack when we call subroutines to temporarily store values that will be restored later.

Any register that your function needs to use should have it's current value put on the stack for safe keeping using the PUSH instruction. Then after the function has finished it's logic, these registers can have their original values restored using the POP instruction. This means that any values in the registers will be the same before and after you've called your function. If we take care of this in our subroutine we can call functions without worrying about what changes they're making to our registers.

The CALL and RET instructions also use the stack. When you CALL a subroutine, the address you called it from in your program is pushed onto the stack. This address is then popped off the stack by RET and the program jumps back to that place in your code. This is why you should always JMP to labels but you should CALL functions.

helloworld-len.asm
                            ; Hello World Program (Subroutines)
                            ; Compile with: nasm -f elf helloworld-len.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld-len.o -o helloworld-len
                            ; Run with: ./helloworld-len

                            SECTION .data
                            msg     db      'Hello, brave new world!', 0Ah

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, msg        ; move the address of our message string into EAX
                                call    strlen          ; call our function to calculate the length of the string

                                mov     edx, eax        ; our function leaves the result in EAX
                                mov     ecx, msg        ; this is all the same as before
                                mov     ebx, 1
                                mov     eax, 4
                                int     80h

                                mov     ebx, 0
                                mov     eax, 1
                                int     80h

                            strlen:                     ; this is our first function declaration
                                push    ebx             ; push the value in EBX onto the stack to preserve it while we use EBX in this function
                                mov     ebx, eax        ; move the address in EAX into EBX (Both point to the same segment in memory)

                            nextchar:                   ; this is the same as lesson3
                                cmp     byte [eax], 0
                                jz      finished
                                inc     eax
                                jmp     nextchar

                            finished:
                                sub     eax, ebx
                                pop     ebx             ; pop the value on the stack back into EBX
                                ret                     ; return to where the function was called
                            
~$ nasm -f elf helloworld-len.asm ~$ ld -m elf_i386 helloworld-len.o -o helloworld-len ~$ ./helloworld-len Hello, brave new world!

Lesson 5

External include files

External include files allow us to move code from our program and put it into separate files. This technique is useful for writing clean, easy to maintain programs. Reusable bits of code can be written as subroutines and stored in separate files called libraries. When you need a piece of logic you can include the file in your program and use it as if they are part of the same file.

In this lesson we will move our string length calculating subroutine into an external file. We fill also make our string printing logic and program exit logic a subroutine and we will move them into this external file. Once it's completed our actual program will be clean and easier to read.

We can then declare another message variable and call our print function twice in order to demonstrate how we can reuse code.

Note: I won't be showing the code in functions.asm after this lesson unless it changes. It will just be included if needed.

functions.asm
                            ;------------------------------------------
                            ; int slen(String message)
                            ; String length calculation function
                            slen:
                                push    ebx
                                mov     ebx, eax

                            nextchar:
                                cmp     byte [eax], 0
                                jz      finished
                                inc     eax
                                jmp     nextchar

                            finished:
                                sub     eax, ebx
                                pop     ebx
                                ret


                            ;------------------------------------------
                            ; void sprint(String message)
                            ; String printing function
                            sprint:
                                push    edx
                                push    ecx
                                push    ebx
                                push    eax
                                call    slen

                                mov     edx, eax
                                pop     eax

                                mov     ecx, eax
                                mov     ebx, 1
                                mov     eax, 4
                                int     80h

                                pop     ebx
                                pop     ecx
                                pop     edx
                                ret


                            ;------------------------------------------
                            ; void exit()
                            ; Exit program and restore resources
                            quit:
                                mov     ebx, 0
                                mov     eax, 1
                                int     80h
                                ret


                            
helloworld-inc.asm
                            ; Hello World Program (External file include)
                            ; Compile with: nasm -f elf helloworld-inc.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld-inc.o -o helloworld-inc
                            ; Run with: ./helloworld-inc

                            %include        'functions.asm'                             ; include our external file

                            SECTION .data
                            msg1    db      'Hello, brave new world!', 0Ah              ; our first message string
                            msg2    db      'This is how we recycle in NASM.', 0Ah      ; our second message string

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, msg1       ; move the address of our first message string into EAX
                                call    sprint          ; call our string printing function

                                mov     eax, msg2       ; move the address of our second message string into EAX
                                call    sprint          ; call our string printing function

                                call    quit            ; call our quit function
                            
~$ nasm -f elf helloworld-inc.asm ~$ ld -m elf_i386 helloworld-inc.o -o helloworld-inc ~$ ./helloworld-inc Hello, brave new world! This is how we recycle in NASM. This is how we recycle in NASM.

Error: Our second message is outputted twice. This is fixed in the next lesson.


Lesson 6

NULL terminating bytes

Ok so why did our second message print twice when we only called our sprint function on msg2 once? Well actually it did only print once. You can see what I mean if you comment out our second call to sprint. The output will be both of our message strings.

But how is this possible?

What is happening is we weren't properly terminating our strings. In assembly, variables are stored one after another in memory so the last byte of our msg1 variable is right next to the first byte of our msg2 variable. We know our string length calculation is looking for a zero byte so unless our msg2 variable starts with a zero byte it keeps counting as if it's the same string (and as far as assembly is concerned it is the same string). So we need to put a zero byte or 0h after our strings to let assembly know where to stop counting.

Note: In programming 0h denotes a null byte and a null byte after a string tells assembly where it ends in memory.

helloworld-inc.asm
                            ; Hello World Program (NULL terminating bytes)
                            ; Compile with: nasm -f elf helloworld-inc.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld-inc.o -o helloworld-inc
                            ; Run with: ./helloworld-inc

                            %include        'functions.asm'

                            SECTION .data
                            msg1    db      'Hello, brave new world!', 0Ah, 0h          ; NOTE the null terminating byte
                            msg2    db      'This is how we recycle in NASM.', 0Ah, 0h  ; NOTE the null terminating byte

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, msg1
                                call    sprint

                                mov     eax, msg2
                                call    sprint

                                call    quit
                            
~$ nasm -f elf helloworld-inc.asm ~$ ld -m elf_i386 helloworld-inc.o -o helloworld-inc ~$ ./helloworld-inc Hello, brave new world! This is how we recycle in NASM.

Lesson 7

Linefeeds

Linefeeds are essential to console programs like our 'hello world' program. They become even more important once we start building programs that require user input. But linefeeds can be a pain to maintain. Sometimes you will want to include them in your strings and sometimes you will want to remove them. If we continue to hard code them in our variables by adding 0Ah after our declared message text, it will become a problem. If there's a place in the code that we don't want to print out the linefeed for that variable we will need to write some extra logic remove it from the string at runtime.

It would be better for the maintainability of our program if we write a subroutine that will print out our message and then print a linefeed afterwards. That way we can just call this subroutine when we need the linefeed and call our current sprint subroutine when we don't.

A call to sys_write requires we pass a pointer to an address in memory of the string we want to print so we can't just pass a linefeed character (0Ah) to our print function. We also don't want to create another variable just to hold a linefeed character so we will instead use the stack.

The way it works is by moving a linefeed character into EAX. We then push EAX onto the stack and get the address pointed to by the Extended Stack Pointer. ESP is another register. When you push items onto the stack, ESP is decremented to point to the address in memory of the last item and so it can be used to access that item directly from the stack. Since ESP points to an address in memory of a character, sys_write will be able to use it to print.

Note: I've highlighted the new code in functions.asm below.

functions.asm
                            ;------------------------------------------
                            ; int slen(String message)
                            ; String length calculation function
                            slen:
                                push    ebx
                                mov     ebx, eax

                            nextchar:
                                cmp     byte [eax], 0
                                jz      finished
                                inc     eax
                                jmp     nextchar

                            finished:
                                sub     eax, ebx
                                pop     ebx
                                ret


                            ;------------------------------------------
                            ; void sprint(String message)
                            ; String printing function
                            sprint:
                                push    edx
                                push    ecx
                                push    ebx
                                push    eax
                                call    slen

                                mov     edx, eax
                                pop     eax

                                mov     ecx, eax
                                mov     ebx, 1
                                mov     eax, 4
                                int     80h

                                pop     ebx
                                pop     ecx
                                pop     edx
                                ret


                            ;------------------------------------------
                            ; void sprintLF(String message)
                            ; String printing with line feed function
                            sprintLF:
                                call    sprint

                                push    eax         ; push eax onto the stack to preserve it while we use the eax register in this function
                                mov     eax, 0Ah    ; move 0Ah into eax - 0Ah is the ascii character for a linefeed
                                push    eax         ; push the linefeed onto the stack so we can get the address
                                mov     eax, esp    ; move the address of the current stack pointer into eax for sprint
                                call    sprint      ; call our sprint function
                                pop     eax         ; remove our linefeed character from the stack
                                pop     eax         ; restore the original value of eax before our function was called
                                ret                 ; return to our program


                            ;------------------------------------------
                            ; void exit()
                            ; Exit program and restore resources
                            quit:
                                mov     ebx, 0
                                mov     eax, 1
                                int     80h
                                ret


                            
helloworld-lf.asm
                            ; Hello World Program (Print with line feed)
                            ; Compile with: nasm -f elf helloworld-lf.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld-lf.o -o helloworld-lf
                            ; Run with: ./helloworld-lf

                            %include        'functions.asm'

                            SECTION .data
                            msg1    db      'Hello, brave new world!', 0h          ; NOTE we have removed the line feed character 0Ah
                            msg2    db      'This is how we recycle in NASM.', 0h  ; NOTE we have removed the line feed character 0Ah

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, msg1
                                call    sprintLF    ; NOTE we are calling our new print with linefeed function

                                mov     eax, msg2
                                call    sprintLF    ; NOTE we are calling our new print with linefeed function

                                call    quit
                            
~$ nasm -f elf helloworld-lf.asm ~$ ld -m elf_i386 helloworld-lf.o -o helloworld-lf ~$ ./helloworld-lf Hello, brave new world! This is how we recycle in NASM.

Lesson 8

Passing arguments

Passing arguments to your program from the command line is as easy as popping them off the stack in NASM. When we run our program, any passed arguments are loaded onto the stack in reverse order. The name of the program is then loaded onto the stack and lastly the total number of arguments is loaded onto the stack. The last two stack items for a NASM compiled program are always the name of the program and the number of passed arguments.

So all we have to do to use them is pop the number of arguments off the stack first, then iterate once for each argument and perform our logic. In our program that means calling our print function.

Note: We are using the ECX register as our counter for the loop. Although it's a general-purpose register it's original intention was to be used as a counter.

helloworld-args.asm
                            ; Hello World Program (Passing arguments from the command line)
                            ; Compile with: nasm -f elf helloworld-args.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld-args.o -o helloworld-args
                            ; Run with: ./helloworld-args

                            %include        'functions.asm'

                            SECTION .text
                            global  _start

                            _start:

                                pop     ecx             ; first value on the stack is the number of arguments

                            nextArg:
                                cmp     ecx, 0h         ; check to see if we have any arguments left
                                jz      noMoreArgs      ; if zero flag is set jump to noMoreArgs label (jumping over the end of the loop)
                                pop     eax             ; pop the next argument off the stack
                                call    sprintLF        ; call our print with linefeed function
                                dec     ecx             ; decrease ecx (number of arguments left) by 1
                                jmp     nextArg         ; jump to nextArg label

                            noMoreArgs:
                                call    quit
                            
~$ nasm -f elf helloworld-args.asm ~$ ld -m elf_i386 helloworld-lf.o -o helloworld-args ~$ ./helloworld-args "This is one argument" "This is another" 101 ./helloworld-args This is one argument This is another 101

Lesson 9

User input

Introduction to the .bss section

So far we've used the .text and .data section so now it's time to introduce the .bss section. BSS stands for Block Started by Symbol. It is an area in our program that is used to reserve space in memory for uninitialised variables. We will use it to reserve some space in memory to hold our user input since we don't know how many bytes we'll need to store.

The syntax to declare variables is as follows:

.bss section example
                            SECTION .bss
                            variableName1:      RESB    1       ; reserve space for 1 byte
                            variableName2:      RESW    1       ; reserve space for 1 word
                            variableName3:      RESD    1       ; reserve space for 1 double word
                            variableName4:      RESQ    1       ; reserve space for 1 double precision float (quad word)
                            variableName5:      REST    1       ; reserve space for 1 extended precision float
                            
Writing our program

We will be using the system call sys_read to receive and process input from the user. This function is assigned OPCODE 3 in the Linux System Call Table. Just like sys_write this function also takes 3 arguments which will be loaded into EDX, ECX and EBX before requesting a software interrupt that will call the function.

The arguments passed are as follows:

  • EDX will be loaded with the maximum length (in bytes) of the our space in memory.
  • ECX will be loaded with the address of our variable created in the .bss section.
  • EBX will be loaded with the file we want to write to – in this case STDIN.
As always the datatype and meaning of the arguments passed can be found in the function's definition.

When sys_read detects a linefeed, control returns to the program and the users input is located at the memory address you passed in ECX.

helloworld-input.asm
                            ; Hello World Program (Getting input)
                            ; Compile with: nasm -f elf helloworld-input.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld-input.o -o helloworld-input
                            ; Run with: ./helloworld-input

                            %include        'functions.asm'

                            SECTION .data
                            msg1        db      'Please enter your name: ', 0h      ; message string asking user for input
                            msg2        db      'Hello, ', 0h                       ; message string to use after user has entered their name

                            SECTION .bss
                            sinput:     resb    255                                 ; reserve a 255 byte space in memory for the users input string

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, msg1
                                call    sprint

                                mov     edx, 255        ; number of bytes to read
                                mov     ecx, sinput     ; reserved space to store our input (known as a buffer)
                                mov     ebx, 0          ; write to the STDIN file
                                mov     eax, 3          ; invoke SYS_READ (kernel opcode 3)
                                int     80h

                                mov     eax, msg2
                                call    sprint

                                mov     eax, sinput     ; move our buffer into eax (Note: input contains a linefeed)
                                call    sprint          ; call our print function

                                call    quit
                            
~$ nasm -f elf helloworld-input.asm ~$ ld -m elf_i386 helloworld-input.o -o helloworld-input ~$ ./helloworld-input Please enter your name: Daniel Givney Hello, Daniel Givney

Lesson 10

Count to 10

Firstly, some background

Counting by numbers is not as straight forward as you would think in assembly. Firstly we need to pass sys_write an address in memory so we can't just load our register with a number and call our print function. Secondly, numbers and strings are very different things in assembly. Strings are represented by what are called ASCII values. ASCII stands for American Standard Code for Information Interchange. A good reference for ASCII can be found here. ASCII was created as a way to standardise the representation of strings across all computers.

Remember, we can't print a number - we have to print a string. In order to count to 10 we will need to convert our numbers from standard integers to their ASCII string representations. Have a look at the ASCII values table and notice that the string representation for the number '1' is actually '49' in ASCII. In fact, adding 48 to our numbers is all we have to do to convert them from integers to their ASCII string representations.

Writing our program

What we will do with our program is count from 1 to 10 using the ECX register. We will then add 48 to our counter to convert it from a number to it's ASCII string representation. We will then push this value to the stack and call our print function passing ESP as the memory address to print from. Once we have finished counting to 10 we will exit our counting loop and call our quit function.

helloworld-10.asm
                            ; Hello World Program (Count to 10)
                            ; Compile with: nasm -f elf helloworld-10.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld-10.o -o helloworld-10
                            ; Run with: ./helloworld-10

                            %include        'functions.asm'

                            SECTION .text
                            global  _start

                            _start:

                                mov     ecx, 0          ; ecx is initalised to zero.

                            nextNumber:
                                inc     ecx             ; increment ecx

                                mov     eax, ecx        ; move the address of our integer into eax
                                add     eax, 48         ; add 48 to our number to convert from integer to ascii for printing
                                push    eax             ; push eax to the stack
                                mov     eax, esp        ; get the address of the character on the stack
                                call    sprintLF        ; call our print function

                                pop     eax             ; clean up the stack so we don't have unneeded bytes taking up space
                                cmp     ecx, 10         ; have we reached 10 yet? compare our counter with decimal 10
                                jne     nextNumber      ; jump if not equal and keep counting

                                call    quit
                            
~$ nasm -f elf helloworld-10.asm ~$ ld -m elf_i386 helloworld-10.o -o helloworld-10 ~$ ./helloworld-10 1 2 3 4 5 6 7 8 9 :

Error: Our number 10 prints a colon (:) character instead. What's going on?


Lesson 11

Count to 10 (itoa)

So why did our program in Lesson 10 print out a colon character instead of the number 10?. Well lets have a look at our ASCII table. We can see that the colon character has a ASCII value of 58. We were adding 48 to our integers to convert them to their ASCII string representations so instead of passing sys_write the value '58' to print ten we actually need to pass the ASCII value for the number 1 followed by the ASCII value for the number 0. Passing sys_write '4948' is the correct string representation for the number '10'. So we can't just simply add 48 to our numbers to convert them, we first have to divide them by 10 because each place value needs to be converted individually.

We will write 2 new subroutines in this lesson 'iprint' and 'iprintLF'. These functions will be used when we want to print ASCII string representations of numbers. We achieve this by passing the number in EAX. We then initialise a counter in ECX. We will repeatedly divide the number by 10 and each time convert the remainder to a string by adding 48. We will then push this onto the stack for later use. Once we can no longer divide the number by 10 we will enter our second loop. In this print loop we will print the now converted string representations from the stack and pop them off. Popping them off the stack moves ESP forward to the next item on the stack. Each time we print a value we will decrease our counter ECX. Once all numbers have been converted and printed we will return to our program.

How does the divide instruction work?

The DIV and IDIV instructions work by dividing whatever is in EAX by the value passed to the instruction. The quotient part of the value is left in EAX and the remainder part is put into EDX (Originally called the data register).

For example.

IDIV instruction example
                            mov     eax, 10         ; move 10 into eax
                            mov     esi, 10         ; move 10 into esi
                            idiv    esi             ; divide eax by esi (eax will equal 1 and edx will equal 0)
                            idiv    esi             ; divide eax by esi again (eax will equal 0 and edx will equal 1)
                            
If we are only storing the remainder won't we have problems?

No, because these are integers, when you divide a number by an even bigger number the quotient in EAX is 0 and the remainder is the number itself. This is because the number divides zero times leaving the original value as the remainder in EDX. How good is that?

Note: Only the new functions iprint and iprintLF have comments.

functions.asm
                            ;------------------------------------------
                            ; void iprint(Integer number)
                            ; Integer printing function (itoa)
                            iprint:
                                push    eax             ; preserve eax on the stack to be restored after function runs
                                push    ecx             ; preserve ecx on the stack to be restored after function runs
                                push    edx             ; preserve edx on the stack to be restored after function runs
                                push    esi             ; preserve esi on the stack to be restored after function runs
                                mov     ecx, 0          ; counter of how many bytes we need to print in the end

                            divideLoop:
                                inc     ecx             ; count each byte to print - number of characters
                                mov     edx, 0          ; empty edx
                                mov     esi, 10         ; mov 10 into esi
                                idiv    esi             ; divide eax by esi
                                add     edx, 48         ; convert edx to it's ascii representation - edx holds the remainder after a divide instruction
                                push    edx             ; push edx (string representation of an intger) onto the stack
                                cmp     eax, 0          ; can the integer be divided anymore?
                                jnz     divideLoop      ; jump if not zero to the label divideLoop

                            printLoop:
                                dec     ecx             ; count down each byte that we put on the stack
                                mov     eax, esp        ; mov the stack pointer into eax for printing
                                call    sprint          ; call our string print function
                                pop     eax             ; remove last character from the stack to move esp forward
                                cmp     ecx, 0          ; have we printed all bytes we pushed onto the stack?
                                jnz     printLoop       ; jump is not zero to the label printLoop

                                pop     esi             ; restore esi from the value we pushed onto the stack at the start
                                pop     edx             ; restore edx from the value we pushed onto the stack at the start
                                pop     ecx             ; restore ecx from the value we pushed onto the stack at the start
                                pop     eax             ; restore eax from the value we pushed onto the stack at the start
                                ret


                            ;------------------------------------------
                            ; void iprintLF(Integer number)
                            ; Integer printing function with linefeed (itoa)
                            iprintLF:
                                call    iprint          ; call our integer printing function

                                push    eax             ; push eax onto the stack to preserve it while we use the eax register in this function
                                mov     eax, 0Ah        ; move 0Ah into eax - 0Ah is the ascii character for a linefeed
                                push    eax             ; push the linefeed onto the stack so we can get the address
                                mov     eax, esp        ; move the address of the current stack pointer into eax for sprint
                                call    sprint          ; call our sprint function
                                pop     eax             ; remove our linefeed character from the stack
                                pop     eax             ; restore the original value of eax before our function was called
                                ret


                            ;------------------------------------------
                            ; int slen(String message)
                            ; String length calculation function
                            slen:
                                push    ebx
                                mov     ebx, eax

                            nextchar:
                                cmp     byte [eax], 0
                                jz      finished
                                inc     eax
                                jmp     nextchar

                            finished:
                                sub     eax, ebx
                                pop     ebx
                                ret


                            ;------------------------------------------
                            ; void sprint(String message)
                            ; String printing function
                            sprint:
                                push    edx
                                push    ecx
                                push    ebx
                                push    eax
                                call    slen

                                mov     edx, eax
                                pop     eax

                                mov     ecx, eax
                                mov     ebx, 1
                                mov     eax, 4
                                int     80h

                                pop     ebx
                                pop     ecx
                                pop     edx
                                ret


                            ;------------------------------------------
                            ; void sprintLF(String message)
                            ; String printing with line feed function
                            sprintLF:
                                call    sprint

                                push    eax
                                mov     eax, 0AH
                                push    eax
                                mov     eax, esp
                                call    sprint
                                pop     eax
                                pop     eax
                                ret


                            ;------------------------------------------
                            ; void exit()
                            ; Exit program and restore resources
                            quit:
                                mov     ebx, 0
                                mov     eax, 1
                                int     80h
                                ret


                            
helloworld-itoa.asm
                            ; Hello World Program (Count to 10 itoa)
                            ; Compile with: nasm -f elf helloworld-itoa.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 helloworld-itoa.o -o helloworld-itoa
                            ; Run with: ./helloworld-itoa

                            %include        'functions.asm'

                            SECTION .text
                            global  _start

                            _start:

                                mov     ecx, 0

                            nextNumber:
                                inc     ecx
                                mov     eax, ecx
                                call    iprintLF        ; NOTE call our new integer printing function (itoa)
                                cmp     ecx, 10
                                jne     nextNumber

                                call    quit
                            
~$ nasm -f elf helloworld-itoa.asm ~$ ld -m elf_i386 helloworld-itoa.o -o helloworld-itoa ~$ ./helloworld-itoa 1 2 3 4 5 6 7 8 9 10

Lesson 12

Calculator - addition

In this program we will be adding the registers EAX and EBX together and we'll leave our answer in EAX. Firstly we use the MOV instruction to load EAX with an integer (in this case 90). We then MOV an integer into EBX (in this case 9). Now all we need to do is use the ADD instruction to perform our addition. EBX & EAX will be added together leaving our answer in the left most register in this instruction (in our case EAX). Then all we need to do is call our integer printing function to complete the program.

calculator-addition.asm
                            ; Calculator (Addition)
                            ; Compile with: nasm -f elf calculator-addition.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 calculator-addition.o -o calculator-addition
                            ; Run with: ./calculator-addition

                            %include        'functions.asm'

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, 90     ; move our first number into eax
                                mov     ebx, 9      ; move our second number into ebx
                                add     eax, ebx    ; add ebx to eax
                                call    iprintLF    ; call our integer print with linefeed function

                                call    quit
                            
~$ nasm -f elf calculator-addition.asm ~$ ld -m elf_i386 calculator-addition.o -o calculator-addition ~$ ./calculator-addition 99

Lesson 13

Calculator - subtraction

In this program we will be subtracting the value in the register EBX from the value in the register EAX. Firstly we load EAX and EBX with integers in the same way as Lesson 12. The only difference is we will be using the SUB instruction to perform our subtraction logic, leaving our answer in the left most register of this instruction (in our case EAX). Then all we need to do is call our integer printing function to complete the program.

calculator-subtraction.asm
                            ; Calculator (Subtraction)
                            ; Compile with: nasm -f elf calculator-subtraction.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 calculator-subtraction.o -o calculator-subtraction
                            ; Run with: ./calculator-subtraction

                            %include        'functions.asm'

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, 90     ; move our first number into eax
                                mov     ebx, 9      ; move our second number into ebx
                                sub     eax, ebx    ; subtract ebx from eax
                                call    iprintLF    ; call our integer print with linefeed function

                                call    quit
                            
~$ nasm -f elf calculator-subtraction.asm ~$ ld -m elf_i386 calculator-subtraction.o -o calculator-subtraction ~$ ./calculator-subtraction 81

Lesson 14

Calculator - multiplication

In this program we will be multiplying the value in EBX by the value present in EAX. Firstly we load EAX and EBX with integers in the same way as Lesson 12. This time though we will be calling the MUL instruction to perform our multiplication logic. The MUL instruction is different from many instructions in NASM, in that it only accepts one further argument. The MUL instruction always multiples EAX by whatever value is passed after it. The answer is left in EAX.

calculator-multiplication.asm
                            ; Calculator (Multiplication)
                            ; Compile with: nasm -f elf calculator-multiplication.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 calculator-multiplication.o -o calculator-multiplication
                            ; Run with: ./calculator-multiplication

                            %include        'functions.asm'

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, 90     ; move our first number into eax
                                mov     ebx, 9      ; move our second number into ebx
                                mul     ebx         ; multiply eax by ebx
                                call    iprintLF    ; call our integer print with linefeed function

                                call    quit
                            
~$ nasm -f elf calculator-multiplication.asm ~$ ld -m elf_i386 calculator-multiplication.o -o calculator-multiplication ~$ ./calculator-multiplication 810

Lesson 15

Calculator - division

In this program we will be dividing the value in EBX by the value present in EAX. We've used division before in our integer print subroutine. Our program requires a few extra strings in order to print out the correct answer but otherwise there's nothing complicated going on.

Firstly we load EAX and EBX with integers in the same way as Lesson 12. Division logic is performed using the DIV instruction. The DIV instruction always divides EAX by the value passed after it. It will leave the quotient part of the answer in EAX and put the remainder part in EDX (the original data register). We then MOV and call our strings and integers to print out the correct answer.

calculator-division.asm
                            ; Calculator (Division)
                            ; Compile with: nasm -f elf calculator-division.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 calculator-division.o -o calculator-division
                            ; Run with: ./calculator-division

                            %include        'functions.asm'

                            SECTION .data
                            msg1        db      ' remainder '      ; a message string to correctly output result

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, 90     ; move our first number into eax
                                mov     ebx, 9      ; move our second number into ebx
                                div     ebx         ; divide eax by ebx
                                call    iprint      ; call our integer print function on the quotient
                                mov     eax, msg1   ; move our message string into eax
                                call    sprint      ; call our string print function
                                mov     eax, edx    ; move our remainder into eax
                                call    iprintLF    ; call our integer printing with linefeed function

                                call    quit
                            
~$ nasm -f elf calculator-division.asm ~$ ld -m elf_i386 calculator-division.o -o calculator-division ~$ ./calculator-division 10 remainder 0

Lesson 16

Calculator (atoi)

Our program will take several command line arguments and add them together printing out the result in the terminal.

Writing our program

Our program begins by using the POP instruction to get the number of passed arguments off the stack. This value is stored in ECX (originally known as the counter register). It will then loop through these arguments popping each one off the stack and performing our addition logic. As we know, arguments passed via the command line are received by our program as strings. Before we can add the arguments together we will need to convert them to integers otherwise our result will not be correct. We do this by calling our Ascii to Integer function (atoi). This function will convert the ascii value into an integer and place the result in EAX. We can then add this value to EDX (originally known as the data register) where we will store the result of our additions. If the value passed to atoi is not an ascii representation of an integer our function will return zero instead. When all arguments have been converted and added together we will print out the result and call our quit function.

How does the atoi function work

Converting an ascii string into an integer value is not a trivial task. We know how to convert an integer to an ascii string so the process should essentially work in reverse. Firstly we take the address of the string and move it into ESI (originally known as the source register). We will then move along the string byte by byte (think of each byte as being a single digit or decimal placeholder). For each digit we will check if it's value is between 48-57 (ascii values for the digits 0-9). We will also check if the value is a linefeed or null terminating byte meaning we have reached the end of the string.

Once we have performed all these checks and determined that the byte can be converted to an integer will perform the following logic. We will subtract 48 from the value – converting the ascii value to it's decimal equivalent. We will then add this value to EAX (the general purpose register that will store our result). We will then multiple EAX by 10 as each byte represents a decimal placeholder and continue the loop.

When all bytes have been converted we need to do one last thing before we return the result. The last digit of any number represents a single unit (not a multiple of 10) so we have multiplied our result one too many times. We simple divide it by 10 once to correct this and then return.

What is the BL register

You may have noticed that the atoi function references the BL register. So far in these tutorials we have been exclusively using 32bit registers. These 32bit general purpose registers contain segments of memory that can also be referenced. These segments are available in 16bits and 8bits. We wanted a single byte (8bits) because a byte is the size of memory that is required to store a single ascii character. If we used a larger memory size we would have copied 8bits of data into 32bits of space leaving us with 'rubbish' bits - because only the first 8bits would be meaningful for our calculation.

The EBX register is 32bits. EBX's 16 bit segment is referenced as BX. BX contains the 8bit segments BL and BH (Lower and Higher bits). We wanted the first 8bits (lower bits) of EBX and so we referenced that storage area using BL.

Almost every assembly language tutorial begins with a history of the registers, their names and their sizes. These tutorials however were written to provide a foundation in NASM by first writing code and then understanding the theory. The full story about the size of registers, their history and importance are beyond the scope of this tutorial but we will return to that story in later tutorials.

Note: Only the new function in this file 'atoi' is shown below.

functions.asm
                            ;------------------------------------------
                            ; int atoi(Integer number)
                            ; Ascii to integer function (atoi)
                            atoi:
                                push    ebx             ; preserve ebx on the stack to be restored after function runs
                                push    ecx             ; preserve ecx on the stack to be restored after function runs
                                push    edx             ; preserve edx on the stack to be restored after function runs
                                push    esi             ; preserve esi on the stack to be restored after function runs
                                mov     esi, eax        ; move pointer in eax into esi (our number to convert)
                                mov     eax, 0          ; initialise eax with decimal value 0
                                mov     ecx, 0          ; initialise ecx with decimal value 0

                            .multiplyLoop:
                                xor     ebx, ebx        ; resets both lower and uppper bytes of ebx to be 0
                                mov     bl, [esi+ecx]   ; move a single byte into ebx register's lower half
                                cmp     bl, 48          ; compare ebx register's lower half value against ascii value 48 (char value 0)
                                jl      .finished       ; jump if less than to label finished
                                cmp     bl, 57          ; compare ebx register's lower half value against ascii value 57 (char value 9)
                                jg      .finished       ; jump if greater than to label finished
                                cmp     bl, 10          ; compare ebx register's lower half value against ascii value 10 (linefeed character)
                                je      .finished       ; jump if equal to label finished
                                cmp     bl, 0           ; compare ebx register's lower half value against decimal value 0 (end of string)
                                jz      .finished       ; jump if zero to label finished

                                sub     bl, 48          ; convert ebx register's lower half to decimal representation of ascii value
                                add     eax, ebx        ; add ebx to our interger value in eax
                                mov     ebx, 10         ; move decimal value 10 into ebx
                                mul     ebx             ; multiply eax by ebx to get place value
                                inc     ecx             ; increment ecx (our counter register)
                                jmp     .multiplyLoop   ; continue multiply loop

                            .finished:
                                mov     ebx, 10         ; move decimal value 10 into ebx
                                div     ebx             ; divide eax by value in ebx (in this case 10)
                                pop     esi             ; restore esi from the value we pushed onto the stack at the start
                                pop     edx             ; restore edx from the value we pushed onto the stack at the start
                                pop     ecx             ; restore ecx from the value we pushed onto the stack at the start
                                pop     ebx             ; restore ebx from the value we pushed onto the stack at the start
                                ret
                            
calculator-atoi.asm
                            ; Calculator (ATOI)
                            ; Compile with: nasm -f elf calculator-atoi.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 calculator-atoi.o -o calculator-atoi
                            ; Run with: ./calculator-atoi 20 1000 317

                            %include        'functions.asm'

                            SECTION .text
                            global  _start

                            _start:

                                pop     ecx             ; first value on the stack is the number of arguments
                                mov     edx, 0          ; initialise our data register to store additions

                            nextArg:
                                cmp     ecx, 0h         ; check to see if we have any arguments left
                                jz      noMoreArgs      ; if zero flag is set jump to noMoreArgs label (jumping over the end of the loop)
                                pop     eax             ; pop the next argument off the stack
                                call    atoi            ; convert our ascii string to decimal integer
                                add     edx, eax        ; perform our addition logic
                                dec     ecx             ; decrease ecx (number of arguments left) by 1
                                jmp     nextArg         ; jump to nextArg label

                            noMoreArgs:
                                mov     eax, edx        ; move our data result into eax for printing
                                call    iprintLF        ; call our integer printing with linefeed function
                                call    quit            ; call our quit function
                            
~$ nasm -f elf calculator-atoi.asm ~$ ld -m elf_i386 calculator-atoi.o -o calculator-atoi ~$ ./calculator-atoi 20 1000 317 1337

Lesson 17

Namespace

Namespace is a necessary construct in any software project that involves a codebase that is larger than a few simple functions. Namespace provides scope to your identifiers and allows you to reuse naming conventions to make your code more readable and maintainable. In assembly language where subroutines are identified by global labels, namespace can be achieved by using local labels.

Up until the last few tutorials we have been using global labels exclusively. This means that blocks of logic that essentially perform the same task needed a label with a unique identifier. A good example would be our "finished" labels. These were global in scope meaning when we needed to break out of a loop in one function we could jump to a "finished" label. But if we needed to break out of a loop in a different function we would need to name this same task something else maybe calling it "done" or "continue". Being able to reuse the label "finished" would mean that someone reading the code would know that these blocks of logic perform almost the same task.

Local labels are prepended with a "." at the beginning of their name for example ".finished". You may have noticed them appearing as our code base in functions.asm grew. A local label is given the namespace of the first global label above it. You can jump to a local label by using the JMP instruction and the compiler will calculate which local label you are referencing by determining in what scope (based on the above global labels) the instruction was called.

namespace.asm
                            ; Namespace
                            ; Compile with: nasm -f elf namespace.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 namespace.o -o namespace
                            ; Run with: ./namespace

                            %include        'functions.asm'

                            SECTION .data
                            msg1        db      'Jumping to finished label.', 0h        ; a message string
                            msg2        db      'Inside subroutine number: ', 0h        ; a message string
                            msg3        db      'Inside subroutine "finished".', 0h     ; a message string

                            SECTION .text
                            global  _start

                            _start:

                            subrountineOne:
                                mov     eax, msg1       ; move the address of msg1 into eax
                                call    sprintLF        ; call our string printing with linefeed function
                                jmp     .finished       ; jump to the local label under the subrountineOne scope

                            .finished:
                                mov     eax, msg2       ; move the address of msg2 into eax
                                call    sprint          ; call our string printing function
                                mov     eax, 1          ; move the value one into eax (for subroutine number one)
                                call    iprintLF        ; call our integer printing function with linefeed function

                            subrountineTwo:
                                mov     eax, msg1       ; move the address of msg1 into eax
                                call    sprintLF        ; call our string print with linefeed function
                                jmp     .finished       ; jump to the local label under the subrountineTwo scope

                            .finished:
                                mov     eax, msg2       ; move the address of msg2 into eax
                                call    sprint          ; call our string printing function
                                mov     eax, 2          ; move the value two into eax (for subroutine number two)
                                call    iprintLF        ; call our integer printing function with linefeed function

                                mov     eax, msg1       ; move the address of msg1 into eax
                                call    sprintLF        ; call our string printing with linefeed function
                                jmp     finished        ; jump to the global label finished

                            finished:
                                mov     eax, msg3       ; move the address of msg3 into eax
                                call    sprintLF        ; call our string printing with linefeed function
                                call    quit            ; call our quit function
                            
~$ nasm -f elf namespace.asm ~$ ld -m elf_i386 namespace.o -o namespace ~$ ./namespace Jumping to finished label. Inside subroutine number: 1 Jumping to finished label. Inside subroutine number: 2 Jumping to finished label. Inside subroutine "finished".

Lesson 18

Fizz Buzz

Firstly, some background

FizzBuzz is group word game played in schools to teach children division. Players take turns to count aloud integers from 1 to 100 replacing any number divisible by 3 with the word "fizz" and any number divisible by 5 with the word "buzz". Numbers that are both divisible by 3 and 5 are replaced by the word "fizzbuzz". This children's game has also become a defacto interview screening question for computer programming jobs as it's thought to easily discover candidates that can't construct a simple logic gate.

Writing our program

There are a number of code solutions to this simple game and some languages offer very trivial and elegant solutions. Depending on how you choose to solve it, the solution almost always involves an if statement and possibly an else statement depending whether you choose to exploit the mathematical property that anything divisible by 5 & 3 would also be divisible by 3 * 5. Being that this is an assembly language tutorial we will provide a solution that involves a structure of two cascading if statements to print the words "fizz" and/or "buzz" and an else statement in case these fail, to print the integer as an ascii value. Each iteration of our loop will then print a line feed. Once we reach 100 we call our program exit function.

fizzbuzz.asm
                            ; Fizzbuzz
                            ; Compile with: nasm -f elf fizzbuzz.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 fizzbuzz.o -o fizzbuzz
                            ; Run with: ./fizzbuzz

                            %include        'functions.asm'

                            SECTION .data
                            fizz        db      'Fizz', 0h     ; a message string
                            buzz        db      'Buzz', 0h     ; a message string

                            SECTION .text
                            global  _start

                            _start:

                                mov     esi, 0          ; initialise our checkFizz boolean variable
                                mov     edi, 0          ; initialise our checkBuzz boolean variable
                                mov     ecx, 0          ; initialise our counter variable

                            nextNumber:
                                inc     ecx             ; increment our counter variable

                            .checkFizz
                                mov     edx, 0          ; clear the edx register - this will hold our remainder after division
                                mov     eax, ecx        ; move the value of our counter into eax for division
                                mov     ebx, 3          ; move our number to divide by into ebx (in this case the value is 3)
                                div     ebx             ; divide eax by ebx
                                mov     edi, edx        ; move our remainder into edi (our checkFizz boolean variable)
                                cmp     edi, 0          ; compare if the remainder is zero (meaning the counter divides by 3)
                                jne     .checkBuzz      ; if the remainder is not equal to zero jump to local label checkBuzz
                                mov     eax, fizz       ; else move the address of our fizz string into eax for printing
                                call    sprint          ; call our string printing function

                            .checkBuzz:
                                mov     edx, 0          ; clear the edx register - this will hold our remainder after division
                                mov     eax, ecx        ; move the value of our counter into eax for division
                                mov     ebx, 5          ; move our number to divide by into ebx (in this case the value is 5)
                                div     ebx             ; divide eax by ebx
                                mov     esi, edx        ; move our remainder into edi (our checkBuzz boolean variable)
                                cmp     esi, 0          ; compare if the remainder is zero (meaning the counter divides by 5)
                                jne     .checkInt       ; if the remainder is not equal to zero jump to local label checkInt
                                mov     eax, buzz       ; else move the address of our buzz string into eax for printing
                                call    sprint          ; call our string printing function

                            .checkInt:
                                cmp     edi, 0          ; edi contains the remainder after the division in checkFizz
                                je     .continue        ; if equal (counter divides by 3) skip printing the integer
                                cmp     esi, 0          ; esi contains the remainder after the division in checkBuzz
                                je     .continue        ; if equal (counter divides by 5) skip printing the integer
                                mov     eax, ecx        ; else move the value in ecx (our counter) into eax for printing
                                call    iprint          ; call our integer printing function

                            .continue:
                                mov     eax, 0Ah        ; move an ascii linefeed character into eax
                                push    eax             ; push the address of eax onto the stack for printing
                                mov     eax, esp        ; get the stack pointer (address on the stack of our linefeed char)
                                call    sprint          ; call our string printing function to print a line feed
                                pop     eax             ; pop the stack so we don't waste resources
                                cmp     ecx, 100        ; compare if our counter is equal to 100
                                jne     nextNumber      ; if not equal jump to the start of the loop

                                call    quit            ; else call our quit function
                            
~$ nasm -f elf fizzbuzz.asm ~$ ld -m elf_i386 fizzbuzz.o -o fizzbuzz ~$ ./fizzbuzz 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 ...

Lesson 19

Execute Command

Firstly, some background

The EXEC family of functions replace the currently running process with a new process, that executes the command you specified when calling it. We will be using the SYS_EXECVE function in this lesson to replace our program's running process with a new process that will execute the linux program /bin/echo to print out “Hello World!”.

Naming convention

The naming convention used for this family of functions is exec (execute) followed by one or more of the following letters.

  • e - An array of pointers to environment variables is explicitly passed to the new process image.
  • l - Command-line arguments are passed individually to the function.
  • p - Uses the PATH environment variable to find the file named in the path argument to be executed.
  • v - Command-line arguments are passed to the function as an array of pointers.
Writing our program

The V & E at the end of our function name means we will need to pass our arguments in the following format: The first argument is a string containing the command to execute, then an array of arguments to pass to that command and then another array of environment variables that the new process will use. As we are calling a simple command we won't pass any special environment variables to the new process and instead will pass 0h (null).

Both the command arguments and the environment arguments need to be passed as an array of pointers (addresses to memory). That's why we define our strings first and then define a simple null-terminated struct (array) of the variables names. This is then passed to SYS_EXECVE. We call the function and the process is replaced by our command and output is returned to the terminal.

execute.asm
                            ; Execute
                            ; Compile with: nasm -f elf execute.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 execute.o -o execute
                            ; Run with: ./execute

                            %include        'functions.asm'

                            SECTION .data
                            command         db      '/bin/echo', 0h     ; command to execute
                            arg1            db      'Hello World!', 0h
                            arguments       dd      command
                                            dd      arg1                ; arguments to pass to commandline (in this case just one)
                                            dd      0h                  ; end the struct
                            environment     dd      0h                  ; arguments to pass as environment variables (inthis case none) end the struct

                            SECTION .text
                            global  _start

                            _start:

                                mov     edx, environment    ; address of environment variables
                                mov     ecx, arguments      ; address of the arguments to pass to the commandline
                                mov     ebx, command        ; address of the file to execute
                                mov     eax, 11             ; invoke SYS_EXECVE (kernel opcode 11)
                                int     80h

                                call    quit                ; call our quit function
                            
~$ nasm -f elf execute.asm ~$ ld -m elf_i386 execute.o -o execute ~$ ./execute Hello World!

Note: Here are a couple other commands to try.

execute.asm
                            SECTION .data
                            command         db      '/bin/ls', 0h       ; command to execute
                            arg1            db      '-l', 0h
                            
execute.asm
                            SECTION .data
                            command         db      '/bin/sleep', 0h    ; command to execute
                            arg1            db      '5', 0h
                            

Lesson 20

Process Forking

Firstly, some background

In this lesson we will use SYS_FORK to create a new process that duplicates our current process. SYS_FORK takes no arguments - you just call fork and the new process is created. Both processes run concurrently. We can test the return value (in eax) to test whether we are currently in the parent or child process. The parent process returns a non-negative, non-zero integer. In the child process EAX is zero. This can be used to branch your logic between the parent and child.

In our program we exploit this fact to print out different messages in each process.

Note: Each process is responsible for safely exiting.

fork.asm
                            ; Fork
                            ; Compile with: nasm -f elf fork.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 fork.o -o fork
                            ; Run with: ./fork

                            %include        'functions.asm'

                            SECTION .data
                            childMsg        db      'This is the child process', 0h     ; a message string
                            parentMsg       db      'This is the parent process', 0h    ; a message string

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, 2              ; invoke SYS_FORK (kernel opcode 2)
                                int     80h

                                cmp     eax, 0              ; if eax is zero we are in the child process
                                jz      child               ; jump if eax is zero to child label

                            parent:
                                mov     eax, parentMsg      ; inside our parent process move parentMsg into eax
                                call    sprintLF            ; call our string printing with linefeed function

                                call    quit                ; quit the parent process

                            child:
                                mov     eax, childMsg       ; inside our child process move childMsg into eax
                                call    sprintLF            ; call our string printing with linefeed function

                                call    quit                ; quit the child process
                            
~$ nasm -f elf fork.asm ~$ ld -m elf_i386 fork.o -o fork ~$ ./fork This is the parent process This is the child process

Lesson 21

Telling the time

Generating a unix timestamp in NASM is easy with the SYS_TIME function of the linux kernel. Simply pass OPCODE 13 to the kernel with no arguments and you are returned the Unix Epoch in the EAX register.

That is the number of seconds that have elapsed since January 1st 1970 UTC.

time.asm
                            ; Time
                            ; Compile with: nasm -f elf time.asm
                            ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 time.o -o time
                            ; Run with: ./time

                            %include        'functions.asm'

                            SECTION .data
                            msg        db      'Seconds since Jan 01 1970: ', 0h     ; a message string

                            SECTION .text
                            global  _start

                            _start:

                                mov     eax, msg        ; move our message string into eax for printing
                                call    sprint          ; call our string printing function

                                mov     eax, 13         ; invoke SYS_TIME (kernel opcode 13)
                                int     80h             ; call the kernel

                                call    iprintLF        ; call our integer printing function with linefeed
                                call    quit            ; call our quit function
                            
~$ nasm -f elf time.asm ~$ ld -m elf_i386 time.o -o time ~$ ./time Seconds since Jan 01 1970: 1374995660