Learn ARM assembly language with Raspberry Pi

Code a small assembly language program and then compile, execute, and debug it

Stephen Smith

Part 01

If you’ve ever wondered how the ARM CPU at the heart of a Raspberry Pi works, or how to write the most efficient code possible, then assembly language is the place to start. Raspberry Pi OS includes everything you need with the pre- installed GNU Assembler (**gnu.org**) and GNU Debugger. In this tutorial, we will show you how to write simple code in our favourite text editor as we explain assembly language instructions, and you’ll learn about the architecture of the ARM CPU.

A small program

Create a folder called **Simple** to hold your program. Open Geany (menu > Programming > Geany Programmer’s Editor) and enter the listing of **simple.s** (see **magpi.cc/learnassembly1**). Anything after an ‘@’ sign is a comment. Assembly language statements are in the form of: Label: opcode operands @ comment You can use any text editor, and Geany Programmer’s Editor is installed with Raspberry Pi OS. Geany has simple colour coding in the editor and allows you to build and execute your program. Save the file as **simple.s** in the **Simple** folder you created.

Create the makefile

You can enter the build steps manually in a Terminal prompt, but it is easier to have a makefile automate the process. This makefile creates a debug build, which includes information to help us use gdb (GNU Project Debugger) in a later step. Although the makefile is a textfile, the indentations must be made with tab characters and not spaces. Copy, type in, and save the makefile, as **makefile** with no file extension, to the **Simple** folder.

Build the program

In a Terminal window, **cd** into the **Simple** folder, and enter the **make** command:

``` cd Simple make ```

Or, in Geany, choose Build > Make from the menu bar.

Execute the program

In the Terminal window, type:

``` ./simple ```

Or, in Geany, select Build > Execute from the menu. You should see ‘Hello World!’ printed in your Terminal window. Yay, we’ve written our first complete assembly language program.

Examine the machine code

Enter the command:

``` objdump -s -d simple.o > simple.lst ```

Inspect the file with **cat**:

``` cat simple.lst ```

The file **simple.lst** contains lines like:

``` 0: e3a00011 mov r0, #17 ```

The bytes **e3 a0 00 11** are the machine code that our code was assembled into. The numeral **11** is hexadecimal for 17. The register is 0 and the **e3a** part indicates which instruction we are executing and some options for that instruction. Each assembly instruction compiles to a single 32- bit word. A word is the natural size of data for a particular processor, in this case it is 32 bits or 4 bytes in length. This is characteristic of RISC CPUs, allowing them to quickly load and decode each instruction. Even though the R0 register is 32 bits, we can only load a small subset of values, since there are only 16 bits available in this instruction’s encoding.

We haven’t talked about what each statement does, so for the next few steps, we’ll debug through the program and talk about what each statement does. In the Terminal window, enter:

``` gdb simple ```

Debug the program

Set a breakpoint

The first statement in the program is:

``` .global _start: ```

We’ll debug through the program and talk about what each statement does

``` (gdb) b _start Breakpoint 1 at 0x10054: file simple.s, line 12. (gdb) r Starting program: /home/pi/asm/tutorial1/ simple Breakpoint 1, _start () at simple.s:12 12 _start: MOV R0, #17 @ Use 17 for test example ```

This is a label marked as global. When Raspberry Pi OS loads a program, it starts executing at the global label **_start**. We want the debugger to stop at the beginning of our program when we execute it, and a convenient way to do this is to set a breakpoint at this location. All gdb commands have short forms to save typing, in this case **b** is short for breakpoint. Next, we can execute the program by typing the **run** command abbreviated as **r**. gdb will stop at the **_start** location, displaying the assembly language instruction that will execute next:

Examine the registers

In 32-bit mode, Raspberry Pi’s ARM CPU has 16 registers in each CPU core. There are twelve general-purpose registers and four registers with specific purposes. To see all the registers, enter:

``` (gdb) i r ```

This is short for ‘info registers’. This instruction also shows the two program status registers that you test to create conditional logic. To see a specific register, add the register’s name, such as:

``` (gdb) i r r0 r0 0x0 0 ```

Notice the value of R0, as the first instruction we execute will load a value into R0.

Single step through the addition

To execute a single assembly language instruction, enter the **step** command into gdb (**s** for short). The ARM processor uses what is called a load/store architecture. That means you need to load data from memory into the CPU to operate on it, then store the value back to memory when you are done. The **MOV** instruction is one way to load data into a register; in this case, the value is embedded in the instruction. Next, add 2 to R0 using the **ADD** instruction. Enter the **step** and **info** commands below to see this in action.

``` 12 _start: MOV R0, #17 @ Use 17 for test example (gdb) s 13 ADD R0, #2 @ Add 2 to R0 (gdb) i r r0 r0 0x11 17 (gdb) s 14 BL prntHW @ Call subroutine to print hello world (gdb) i r r0 r0 0x13 19 ```

Jump to a subroutine

The program contains a subroutine to print the string ‘Hello World!’ to the Terminal window, to execute this **prntHW** subroutine, we use the Branch and Link (**BL**) instruction. This routine saves the return address in the link register (LR) and sets the program counter (PC) to the start of the routine. To see this, we will check the LR and PC registers, single-step the BL instruction, and then see the effects on these registers.

``` (gdb) i r lr pc lr 0x0 0 pc 0x1005c 0x1005c <_start+8> (gdb) s prntHW () at simple.s:19 19 prntHW: PUSH {R7} @ save R7 (gdb) i r lr pc lr 0x10060 65632 pc 0x1006c 0x1006c <prntHW> ``` The LR has been set to one instruction after the BL instruction and the PC is now the first instruction in the subroutine.

The subroutine starts with a PUSH {R7} instruction to save the register R7 to the stack. Functions and subroutines are responsible for restoring the values of registers R4-R12. Before returning the subroutine calls POP {R7} to restore the saved value from the stack.

Call the Linux write command to output a string to stdout

Call the Linux write command to output a string to stdout. This call takes three parameters that are placed in registers R0, R1, and R2. The function call number to indicate a write call is placed in register R7. If you call a Linux service from any programming language, this is the code that is eventually executed. The Linux function call is initiated with the SVC (Supervisor Call) instruction. This is a software interrupt and a convenient way to switch execution to the Linux kernel via an operating system interrupt handler.

Congratulations, you have written your first assembly language program

The LDR instruction loads the address of the string to print into register R1. Memory addresses are 32-bits, and each instruction is 32-bits long, so how does this work since the instruction also holds the operation code and the register number? If you look at the simple.lst file (from Step 5), you will notice this instruction was changed to:

Which is a program counter relative address. The address is calculated by adding a small constant to the current value of the program counter to get the correct 32-bit address. This is an example of the GNU Assembler helping us deal with one of the tricky aspects of programming RISC processors.

Exit the program

After the subroutine returns, we are done. To exit our program, we call a Linux service to terminate the program. The Linux service number (1) goes in R7, and our program’s return code is placed in R0. When the SVC instruction is executed, Linux terminates the process, which gdb reports.

To exit gdb, press CTRL+D. Congratulations, you have written your first assembly language program. Why don’t you try making changes, for instance change the ADD instruction to SUB or MUL? Perhaps change what is printed or see what happens if you change the program’s return code. The only way to truly learn a new programming technique is to experiment and learn by doing.