MACHINE CODE AND ASSEMBLY LANGUAGE**
We’ve covered the physical parts of a computer: the CPU, main memory, and I/O devices. Understanding the hardware of a computer is important, but hardware is only half the story. The magic of computers is in software. It’s software that moves a computer from being a fixed-purpose device to a highly flexible device that can easily take on new abilities! In this chapter we cover low-level software—machine code and assembly language. I’ve found that these topics are best understood using an interactive approach, so the bulk of this chapter’s content is in the projects.
Software Terms Defined
To discuss software, I need to first introduce several terms. Instructions that tell a computer what to do are known as software ; this contrasts with hardware, the physical elements of a computer. An ordered set of software instructions that accomplishes a task is called a program , and programming is the act of writing such programs.
The term application is sometimes used synonymously with program, although application tends to refer to a program that interacts directly with humans, rather than programs that interact with software or hardware. An application may also consist of multiple programs working together. The word app came into popular use around 2008, and tends to carry other connotations that I will cover in Chapter 13 .
Another name for a set of software instructions is computer code , or just code . CPUs execute machine code , whereas software developers typically write their source code in a higher-level programming language. The term source code refers to the text of a program as originally written by developers. Such code usually isn’t written in a form that CPUs understand directly, so additional steps must be taken before it can run on a computer. I will cover more details on source code and high-level programming languages in Chapter 9 , but now let’s look at the foundation of software: machine code.
Machine code is software in the form of binary machine language instructions. As described in Chapter 7 , a CPU’s architecture determines which instructions that particular CPU understands. In the same way that a human language is formed from a vocabulary, a machine language is formed from a list of instructions known to a CPU family. Vocabulary words arranged into sentences convey meaning, and CPU instructions arranged into programs do the same.
No matter how a program was originally written (and there are lots of ways to write programs), it eventually needs to execute on a CPU as a series of machine language instructions. As you might expect, CPU instructions boil down to a series of 0s and 1s, just like everything else a computer deals with. This is worth repeating: no matter how a program was originally written, no matter what programming language was used, no matter what technologies were involved, in the end, that program becomes a series of 0s and 1s, representing instructions that a CPU can execute.
Some years ago, I had a job that involved diagnosing software failures. Often, the problems I analyzed occurred in software written by other companies. I didn’t have the source code for this software, nor did I have much information about how the software was supposed to work, and yet my job was to determine why the software was failing! I had a coworker who took this in stride, and he regularly reminded me that “it’s just code.” In other words, the failing software was just a bunch of 1s and 0s that a CPU interpreted as instructions. If a CPU can make sense of the code, so can you.
An Example Machine Instruction
I think the simplest way to jump into the topic of machine code is to look at an example. Let’s take a look at a specific machine instruction understood by the ARM family of processors. As you may recall, ARM processors are found in most smartphones, so this instruction is probably something your phone would understand.
Our example instruction tells the processor to move the number 4 into the r7 register, one of several general-purpose registers on ARM processors. Recall from our previous discussion of computer hardware that a register is a small storage location within the CPU. The ARM instruction for doing that looks like this in binary:
11100011101000000111000000000100
Let’s examine how an ARM CPU would go about making sense of this instruction, as shown in Figure 8-1 . Note that we’re skipping some of the bits that aren’t relevant to our discussion.
Figure 8-1: Decoding an ARM instruction
The condition section specifies the conditions under which the instruction should be executed. 1110 means the instruction is not conditional, so the CPU should always execute it. Although this is not the case in this example, some instructions only need to run under specific conditions. The next two bits, 00 in this example, aren’t relevant to our discussion, so we’ll skip them. The immediate bit tells us whether we’re accessing a value in a register or accessing a value specified in the instruction itself (known as an immediate value ). In this case, the immediate bit is 1 , so we’re using a number specified within the instruction. If the immediate bit were 0 , the register that should be accessed would be specified elsewhere in the instruction’s bits. The opcode represents the operation that the CPU is to perform. In this case, it’s mov , meaning the CPU has to move some data. The destination register of 0111 tells us we’re moving a value into register r7 ( 0111 is binary for seven). Finally, the immediate value of 00000100 is 4 in decimal, which is the number we want to move into register r7 . To recap, this binary sequence tells an ARM CPU to move the number 4 into the r7 register.
A CPU always deals with everything in binary, but most people have a hard time with all those 0s and 1s. Let’s represent the same instruction in hexadecimal to make it somewhat easier to read:
e3a07004
Now isn’t that better? Well, maybe not. It’s more compact and easier to distinguish than binary, but its meaning still isn’t obvious. Fortunately for us, there’s yet another way to represent this instruction: assembly language. Assembly language (or assembler language ) is a programming language in which each statement directly represents a machine language instruction. Each type of machine language has a corresponding assembly language—x86 assembly, ARM assembly, and so forth. An assembly language statement consists of a mnemonic that represents a CPU opcode, plus any required operands (such as a register or numeric value). A mnemonic is a human-readable form of an opcode, allowing assembly language programmers to use mov instead of 1101 in their code. The same ARM instruction discussed earlier can also be represented using the following assembly language statement:
mov r7, #4
Compared to the corresponding binary and hexadecimal representations, this statement is certainly a better way to say, “move 4 into the r7 register”! At least it’s easier to read for humans. That said, remember that the assembly language statement is just a convenience for people. A CPU never executes instructions in a text format, it only deals with the binary form of an instruction. If a programmer writes a program in assembly language, the assembly instructions must still be turned into machine code before a computer runs the program. This is accomplished using an assembler , a program that translates assembly language statements to machine code. An assembly language text file is fed into an assembler, and the output is a binary object file containing machine code, as illustrated in Figure 8-2 .
Figure 8-2: An assembler turns assembly language into machine code.
Calculating a Factorial in Machine Code
Now that we’ve examined a single ARM instruction, let’s see how multiple instructions can be combined to perform a useful task. Let’s look at some ARM machine code that calculates the factorial of an integer. As you may remember from math class, the factorial of n (written as n !) is the product of the positive integers less than or equal to n . So as an example, the factorial of 4 is
4! = 4 × 3 × 2 × 1 = 24
Now that we have a definition for factorial, let’s look at an implementation of a factorial calculation in ARM machine code. To keep things simple, we won’t examine the full program code, just the part that does the factorial algorithm. We assume that initially the value of n is stored in the r0 register, and that when the code completes, the result of the calculation is also stored in r0.
Machine code, like any other data a computer deals with, must be loaded into memory before the CPU can access it. The following is a view of our machine code as 32-bit (4-byte) hexadecimal values, along with the memory address of each value.
Address Data
0001007c e2503001
00010080 da000002
00010084 e0000093
00010088 e2533001
0001008c 1afffffc
When our code loads into memory, the factorial logic starts at address 0001007c . Let’s examine the contents of memory starting at that address. Note that 0001007c isn’t a magic address; it just happens to be where the code loaded in this example. Note, also, that the memory address values increase by 4 because each data value requires 4 bytes of storage. Each ARM instruction is 4 bytes in length, so this data represents five ARM instructions.
Looking at these instructions as hexadecimal values doesn’t give us much insight to their meaning, so let’s decode the instructions so we can make sense of this program. In the following listing, I’ve converted the hexadecimal data values to their corresponding assembly language mnemonics. In case you’re wondering, manually translating machine language to assembly language isn’t something you need to know how to do! We have software for that called a disassembler . For now, this book acts as your disassembler. Here’s each instruction paired with its assembly statement:
Address Data Assembly
0001007c e2503001 subs r3, r0, #1
00010080 da000002 ble 0x10090
00010084 e0000093 mul r0, r3, r0
00010088 e2533001 subs r3, r3, #1
0001008c 1afffffc bne 0x10084
00010090 ---
The CPU executes these instructions sequentially until it hits a branching instruction (such as ble or bne ), which may cause it to jump to another part of the program. Address 00010090 marks the end of the factorial logic. Once that address is reached, the factorial result has been stored in r0 . At that point, the CPU executes whatever instruction happens to be at address 00010090 .
You may be wondering how these instructions represent a calculation of a factorial. For most people, a cursory look at such instructions isn’t sufficient to understand the underlying intent. Taking a step-by-step approach and tracking the values of the registers as each instruction is executed can help you understand the program. I’ll provide you with some needed background information, and then you can try evaluating how this program works.
To make sense of this program, you first need a description of each instruction used. In Table 8-1 , I’ve given you an explanation of each instruction in this program. In this table, I’ve used placeholder names for registers such as Rd and Rn . When you review assembly code, you’ll see actual register names used instead, such as r0 or r3 . The order of the operands listed in the code corresponds to the order of the operands in Table 8-1 . For example, subs r3, r0, #1 means subtract 1 from the value stored in r0 and store the result in r3 .
Table 8-1: Explanation of a Few ARM Instructions
| Instruction | Details |
|---|---|
| subs Rd , Rn , #Const | SubtractSubtracts constant value Const from the value stored in register Rn and stores the result in register Rd .In other words, Rd = Rn – Const |
| mul Rd , Rn , Rm | MultiplyMultiplies the value stored in register Rn and the value stored in register Rm and stores the result in register Rd .In other words, Rd = Rn × Rm |
| ble Addr | Branch if less than or equalIf the previous operation’s result was less than or equal to 0, then jump to the instruction at address Addr . Otherwise, continue to the next instruction. |
| bne Addr | Branch if not equalIf the previous operation’s result was not 0, then jump to the instruction at address Addr . Otherwise, continue to the next instruction. |
BRANCHING AND THE STATUS REGISTER
The branch instructions don’t actually look at the numeric result of the previous instruction. ARM processors, like most CPUs, have a register dedicated to tracking status. This status register has 32 bits, and each bit corresponds to a certain status flag. For example, bit 31 is the N flag, and it is set to 1 when an instruction results in a negative number. Only certain instructions affect the state of these flags. For example, the subs instruction alters the state of the flags. If a certain subtraction operation results in a negative result, the N flag is set; otherwise, it is cleared. Other instructions, including branching instructions, then look at the status flags to determine what to do. This may seem like a roundabout approach, but really, it simplifies things for instructions like bne —the processor can branch (or not) based on the value of a single bit.
We’ve reached the end of the explanatory content on this topic; the rest of the chapter is made up of an exercise and two projects. In Exercise 8-1 , you’ll walk through the example factorial program using the details found in Table 8-1 to understand how each instruction works.
EXERCISE 8-1: USE YOUR BRAIN AS A CPU
Try running the following ARM assembly program in your mind, or use pencil and paper:
Address Assembly
0001007c subs r3, r0, #1
00010080 ble 0x10090
00010084 mul r0, r3, r0
00010088 subs r3, r3, #1
0001008c bne 0x10084
00010090 ---
Assume an input value of n = 4 is initially stored in r0 . When the program gets to the instruction at 00010090 , you’ve reached the end of the code, and r0 should be the expected output value of 24. I recommend that for each instruction, you keep track of the values of r0 and r3 before and after the instruction completes. Work through the instructions until you reach the instruction at 00010090 and see if you got the expected result. If things worked correctly, you should have looped through the same instructions several times; that’s intentional. The answer is in Appendix A .
Walking through assembly language on paper is a great start, but trying out assembly language on a computer is even better.
NOTE
Please see Project #12 on page 145 , where you can assemble the factorial code and examine it while it runs. Also, see Project #13 on page 155 , where you can learn some additional approaches for examining machine code .
Summary
In this chapter we covered machine code, a series of CPU-specific instructions represented as bytes in memory. You learned how an example ARM processor instruction is encoded, and you saw how that instruction can be represented in assembly language. You learned that assembly language is a kind of source code, specifically a human-readable form of machine code. We saw how multiple assembly language statements can be combined to perform useful operations.
In the next chapter, we’ll cover high-level programming languages. Such languages provide an abstraction from a CPU’s instruction set, allowing developers to write source code that’s easier to understand and portable across different computer hardware platforms.
PROJECT #12: FACTORIAL IN ASSEMBLY
Prerequisite: A Raspberry Pi, running Raspberry Pi OS. I recommend that you flip to Appendix B and read the entire “Raspberry Pi” section on page 341 . That gets you set up and walks you through using Raspberry Pi OS, including how to work with files, which you do extensively in this chapter’s projects.
In this project, you’ll build a factorial program in assembly language, like the one we covered earlier in this chapter. You’ll then examine the generated machine code. The factorial program includes some additional code beyond what was included in the chapter. Specifically, the program also reads the initial value of n from memory, writes the result back to memory, and hands control back to the operating system at the end.
ASSEMBLY INSTRUCTIONS AND DIRECTIVES
Since you’re including this additional code, I’ve provided Table 8-2 to explain the various instructions used in the code. You saw some of these instructions already in Table 8-1 , but I’m including everything here for easy reference.
Table 8-2: ARM Instructions Used in Project #12
| Instruction | Details |
|---|---|
| ldr Rd , Addr | Load register from memoryReads the value at address Addr and puts it in register Rd . |
| str Rd , Addr | Store register to memoryWrites the value in register Rd to address Addr . |
| mov Rd , # Const | Move constant to registerMoves constant value Const to register Rd . |
| svc | Make system callMakes a request of the operating system. |
| subs Rd , Rn , # Const | SubtractSubtracts constant value Const from the value stored in register Rn and stores the result in register Rd .In other words, Rd = Rn – Const |
| mul Rd , Rn , Rm | MultiplyMultiplies the value stored in register Rn and the value stored in register Rm and stores the result in register Rd .In other words, Rd = Rn × Rm |
| ble Addr | Branch if less than or equalIf the previous operation’s result was less than or equal to 0, then jump to the instruction at address Addr . Otherwise, continue to the next instruction. |
| bne Addr | Branch if not equalIf the previous operation’s result was not 0, then jump to the instruction at address Addr . Otherwise, continue to the next instruction. |
When writing code in assembly language, developers also use assembler directives . These aren’t ARM instructions, but commands to the assembler. These directives start with a period, so they’re easy to distinguish from instructions. In the following code, you also see text followed by a colon—these are labels , names given to a memory address. Since we don’t know where instructions will be located in memory when we write the code, we refer to memory locations by labels instead of by memory addresses. One more thing to note: the @ sign indicates that the text following it (on the same line) is a comment. I’ve included comments to explain the program, but you can skip entering them if you prefer.
ENTER AND REVIEW THE CODE
That’s enough background information; this is a project after all! Time to enter the code. Use the text editor of your choice to create a new file called fac.s in the root of your home folder. Detailed steps for using text editors on Raspberry Pi OS are included in the “Working with Files and Folders” section of the Raspberry Pi documentation on page 346 . Enter the following ARM assembly code into your text editor (you don’t have to preserve indentation and empty lines, but be sure to maintain line breaks, although extra line breaks won’t hurt). Don’t worry if you don’t yet understand all of this code; I explain what you need to know following the code.
.global _start ❶
.text ❷
_start: ❸
ldr r1, =n @ set r1 = address of n ❹
ldr r0, [r1] @ set r0 = the value of n
subs r3, r0, #1 @ set r3 = r0 - 1
ble end @ jump to end if r3 <= 0
loop:
mul r0, r3, r0 @ set r0 = r3 x r0
subs r3, r3, #1 @ decrement r3
bne loop @ jump to loop if r3 > 0
end:
ldr r1, =result @ set r1 = address of result ❺
str r0, [r1] @ store r0 at result
@ Exit the program
mov r0, #0 ❻
mov r7, #1
svc 0
.data ❼
n: .word 5 ❽
result: .word 0
After entering in your code, save it in the text editor as fac.s in the root of your home folder. Let’s walk through this code, starting with the directives and labels.
As mentioned earlier, text followed by a colon, like _start: , is a label for a memory location ❸ . The _start label marks the point at which the program begins execution. The .global directive makes the _start label visible to the linker ❶ (we’ll get to the linker in a minute) so that it can be set as the entry point for the program. The .text directive tells the assembler that the lines following it are instructions ❷ .
At the end of the code, the .data directive tells the assembler that the lines following it are data ❼ . In the data section, the program is storing two 32-bit values, each indicated by the .word directive ❽ . The first is the value of n , initially set to a value of 5. The second is result , initially set to a value of 0. In this context, “word” means 4 bytes, or 32 bits.
Now let’s look at the functional additions to the code beyond what was in the chapter. We now have code that loads n from memory, saves the factorial result to memory, and exits the program. The first two instructions in _start load the value of n from a location in memory ❹ . The ldr instruction loads a register with a value. We reference the address of n with \=n . On the next line, [r1] is in brackets because the program is accessing the value stored at the address in r1 .
The two instructions following end save the result to a location in memory ❺ . The first instruction moves the address of the memory location named result into the r1 register. After that, the code stores the value in the r0 register (which happens to be the calculated factorial) to the result memory address, referenced by r1 .
The last three instructions in the .text section are used to cleanly exit the program ❻ . This requires the help of the operating system, so I’ll skip over the details of these instructions until we cover operating systems in Chapter 10 .
ASSEMBLE, LINK, AND RUN
You now have a text file with assembly language instructions, but this isn’t a format that a computer can run. You need to turn the assembly language instructions into bytes of machine code through a two-step process. First, you need to convert (assemble) the instructions to machine code bytes using an assembler . The result of this process is an object file , a file that contains the bytes of your program but still isn’t in the final format needed to run the program. Next, you need to use a program called a linker to turn your object file into an executable file that the operating system can run. This process is illustrated in Figure 8-3 .
Figure 8-3: Assembling and linking produces an executable file
You may wonder why this two-step process is needed. If you’re assembling multiple source files that all work together as one program, each source file assembles into an object file. The linker then combines the various object files into one executable file. This allows for object files that were created previously to be linked as needed. In this case, you have just one object file, and the linker simply turns it into a format that’s ready to execute.
Now, assemble your code:
$ as -o fac.o fac.s
The as tool is the GNU Assembler, which turns your assembly language statements into machine code. This command writes the generated machine code to a file called fac.o , an object file. The assembler may give you a warning if your fac.s file doesn’t end with a line break—you can safely ignore this warning.
Once your source code has been assembled into an object file, you need to use the GNU linker ( ld ) to convert your object file to an executable file:
$ ld -o fac fac.o
This command takes fac.o as an input, and outputs an executable file named fac . At this point, you can run your program with the following command:
$ ./fac
This command should immediately return to the next line with no output. This is because your program doesn’t actually display any text to the screen. It simply calculates a factorial, saves the result in memory, then exits. To interact with the user, the program would need to request some help from the operating system. However, since we’re trying to keep this program as minimal as possible, you don’t need to do that.
LOAD THE PROGRAM WITH A DEBUGGER
Since your program doesn’t output anything, how can you tell what it’s doing? You can use a debugger , a program that can examine a process as it runs. A debugger can attach to a running program and then halt its execution. While the program is halted, the debugger can examine the registers and memory of the target process. Here, you use the GNU Debugger, gdb , as your debugger, and your target is the fac program.
To start, just execute the following command:
$ gdb fac
When you run this command, gdb loads the fac file but no instructions execute yet. From the ( gdb ) prompt, enter the following to view the start address of the program:
(gdb) info files
You should see a line like this, although the specific address may differ:
Entry point: 0x10074
This tells you that the program’s entry point is address 0x10074 . Remember, when you wrote the program, you didn’t know what memory addresses would be used, so you used labels instead. Now that the program has been built and loaded into memory, you have real memory addresses to examine. This entry point address corresponds to the _start label, since that’s where the program begins. You can now use gdb to disassemble the machine code starting at the program entry point. Disassembly is the process of viewing machine code bytes as assembly language instructions. The following command uses 0x10074 as the start address; if your entry point is different, use that address instead.
(gdb) disas 0x10074
Dump of assembler code for function _start:
0x00010074 <+0>: ldr r1, [pc, #40] ; 0x100a4 <end+20>
0x00010078 <+4>: ldr r0, [r1]
0x0001007c <+8>: subs r3, r0, #1
0x00010080 <+12>: ble 0x10090 <end>
After running this command, you should see the first four instructions disassembled, as shown here. By default, gdb only disassembles a handful of instructions. That’s a good start, but it is better to see the entire program. To do that you need to tell gdb the ending address of the code you want to see. If you look back at the earlier code you entered into fac.s , you can see that there are 12 instructions total in your program. Each instruction is 4 bytes, so the program should be 48 bytes in length. This means your program should end 48 bytes after the start address, so the ending address should be 0x00010074 + 48. You can do this addition by hand or in a calculator program, but since you’re in gdb , you can ask it to do that math for you and find the ending address of your program (again, replace 0x10074 with your entry point address if you need to):
(gdb) print/x 0x00010074 + 48
$1 = 0x100a4
The print command output can be a bit confusing at first. The /x in the command means “print the result in hexadecimal.” If you look at the output, the left-hand value ( $1 ) is a convenience variable , a temporary storage location in gdb . Saving a value in a convenience variable is gdb ’s way of making it easy for you to get back to this result later. The value after the equals sign is the printed value, the result of the calculation, 0x100a4 in this case.
So now you know the ending address ( 0x100a4 ), and you can ask gdb to disassemble the entire program. Note that if your starting address is different than mine, you need to replace the two addresses in the following command.
(gdb) disas 0x10074,0x100a4
Dump of assembler code from 0x10074 to 0x100a4:
0x00010074 <_start+0>: ldr r1, [pc, #40] ; 0x100a4 <end+20> ❶
0x00010078 <_start+4>: ldr r0, [r1]
0x0001007c <_start+8>: subs r3, r0, #1
0x00010080 <_start+12>: ble 0x10090 <end>
0x00010084 <loop+0>: mul r0, r3, r0
0x00010088 <loop+4>: subs r3, r3, #1
0x0001008c <loop+8>: bne 0x10084 <loop>
0x00010090 <end+0>: ldr r1, [pc, #16] ; 0x100a8 <end+24> ❷
0x00010094 <end+4>: str r0, [r1]
0x00010098 <end+8>: mov r0, #0
0x0001009c <end+12>: mov r7, #1
0x000100a0 <end+16>: svc 0x00000000
This looks very much like what you originally entered into fac.s and assembled, except now each instruction has been assigned an address, and the references to n and result have been replaced with memory offsets relative to the program counter register (for example, [pc, #40] ❶ ). The program counter register, or instruction pointer , holds the memory address of the current instruction. For the sake of keeping things simple, I’m not going into the details of why program counter offsets are used here, but just know that the instructions at 0x10074 ❶ and 0x10090 ❷ are loading the memory addresses of n and result , respectively, into r1 .
RUN AND EXAMINE THE PROGRAM USING DEBUGGER BREAKPOINTS
Now that you can see the program loaded into memory, let’s see if the program works as expected. To do this, you’re going to set breakpoints on certain instructions, which allows you to examine the state of your program at that point. A breakpoint tells the debugger to halt execution when a certain address is reached. Setting a breakpoint on a certain address halts execution immediately before the corresponding instruction is executed. In the following example commands, I use the addresses shown on my system, but if your memory addresses are different, be sure to use those addresses instead.
You’re going to set the following breakpoints:
0x10074 The start of the program.
0x1007c The beginning of the factorial logic, 8 bytes after the first instruction. When the program reaches this instruction, register r0 should be the input value n , which was hard-coded to 5 in the program.
0x10090 The end of the factorial logic, 0x1C bytes after the first instruction. When the program reaches this instruction, register r0 should hold the factorial value that was calculated.
0x100a0 The final instruction of the program. When the program reaches this instruction, the memory location labeled result should hold the factorial result.
Set the breakpoints as follows (again, adjust the addresses if your start address isn’t 0x10074 ):
(gdb) break *0x10074
(gdb) break *0x1007c
(gdb) break *0x10090
(gdb) break *0x100a0
Now begin running the program:
(gdb) run
Starting program: /home/pi/fac
Breakpoint 1, 0x00010074 in _start ()
You should see output like this, indicating that execution stopped at the first breakpoint. At this point the program is ready to execute the first instruction, and you can take a look around at the state of things. First, examine the registers, and really, the only one we care about at this point is the program counter ( pc ), because we want to confirm that the current instruction is the start address of 0x10074. Now ask the debugger to show the value of the pc register:
(gdb) info register pc
pc 0x10074 0x10074 <_start>
This tells you that the program counter is pointing to the start address and first breakpoint, as expected. Another way to confirm the current instruction is to simply disassemble the current code like so:
(gdb) disas
Dump of assembler code for function _start:
\=> 0x00010074 <+0>: ldr r1, [pc, #40] ; 0x100a4 <end+20>
0x00010078 <+4>: ldr r0, [r1]
0x0001007c <+8>: subs r3, r0, #1
0x00010080 <+12>: ble 0x10090 <end>
Note the \=> symbol indicating the current instruction.
Now that you’ve confirmed that the program is ready to run its first instruction, you can examine the current values of the two labeled memory addresses: n and result . These should be 5 and 0, respectively, since that’s what you defined their initial values as in the fac.s source code. You can again use the print command to see these values. When you do so, you need to specify a data type of int (a 32-bit integer) so the print command knows how to display these values.
(gdb) print (int)n
$2 = 5
(gdb) p (int)result
$3 = 0
Note how p is substituted for print in the second command. Shortened versions of commands are supported by gdb ; this can save you some typing. As you can see, the print command makes it easy to print the values of labeled memory locations!
Although printing the value of a labeled memory location is convenient, it does raise a question: How does the print command in gdb know about the labels you gave these memory locations in your original fac.s file? The CPU doesn’t use these labels; it just uses memory addresses. The machine code doesn’t refer to these memory locations by name either. The debugger is able to do this because the file that holds the machine code, fac , also holds symbolic information. These debug symbols tell the debugger about certain named memory locations, such as n and result . Usually symbolic information is removed from executable files before they are distributed to end users, but the symbolic info is still present in your fac executable file.
Keeping in mind that n and result are just labels for memory locations, how do you find the actual memory addresses of these variables? One way is to print the address by using the & operator, which means “address of” in gdb . So &n means “the address of n.” Now print the address of n and the address of result .
(gdb) p &n
$4 = (<data variable, no debug info> *) 0x200ac
(gdb) p &result
$5 = (<data variable, no debug info> *) 0x200b0
This tells you that the value of n is stored at address 0x200ac , and the value of result is stored at address 0x200b0 . Note that these are consecutive values in memory, since both n and result are 4 bytes in length. You can examine this memory using the x command:
(gdb) x/2xw 0x200ac
0x200ac: 0x00000005 0x00000000
The x/2xw command means examine two consecutive values, displayed in hex, each “word” sized (4 bytes), starting at address 0x200ac . So here again you can see that n is 5, and result is 0. This is just a different way of looking at memory, this time without using named labels.
So back to the program—you’ve now established that the initial memory values are set as expected. Continue execution to your next breakpoint, where you can verify that r0 has been set to the initial value of n .
(gdb) continue
Continuing.
Breakpoint 2, 0x0001007c in _start ()
(gdb) disas
Dump of assembler code for function _start:
0x00010074 <+0>: ldr r1, [pc, #40] ; 0x100a4 <end+20>
0x00010078 <+4>: ldr r0, [r1]
\=> 0x0001007c <+8>: subs r3, r0, #1
0x00010080 <+12>: ble 0x10090 <end>
End of assembler dump.
(gdb) info registers r0
r0 0x5 5
From the preceding output you can see that the program has moved forward to instruction 0x1007c as expected, and r0 has the expected value of 5 (the value of n ). So far, so good. Now, move ahead to your next breakpoint, where r0 should now be the calculated value of 5 factorial, which is 120. You can shorten the continue command to just c , and the info registers command to just i r .
(gdb) c
Continuing.
Breakpoint 3, 0x00010090 in end ()
(gdb) disas
Dump of assembler code for function end:
\=> 0x00010090 <+0>: ldr r1, [pc, #16] ; 0x100a8 <end+24>
0x00010094 <+4>: str r0, [r1]
0x00010098 <+8>: mov r0, #0
0x0001009c <+12>: mov r7, #1
0x000100a0 <+16>: svc 0x00000000
0x000100a4 <+20>: andeq r0, r2, r12, lsr #1
0x000100a8 <+24>: strheq r0, [r2], -r0 ; <UNPREDICTABLE>
End of assembler dump.
(gdb) i r r0
r0 0x78 120
That all looks good. Recall that at this point the factorial output hasn’t been saved to the result memory address. Now verify that result is unchanged:
(gdb) p (int)result
$6 = 0
Although you have the factorial output temporarily stored in r0 , it hasn’t been written to memory yet. Continue to the end of program (the final breakpoint) and see if the result memory location has been updated.
(gdb) c
Continuing.
Breakpoint 4, 0x000100a0 in end ()
(gdb) p (int)result
$7 = 120
You should see a value of 120 for result . If so, nice work, your program worked as expected!
HACK THE PROGRAM TO CALCULATE A DIFFERENT FACTORIAL
This program is hard-coded to calculate the factorial of 5. What if you want it to calculate the factorial of some other number? Well, you could change the hard-coded value in the fac.s source code, rebuild the code, and run it again. Or you could write some code that allows the user to input a desired value of n at runtime. But imagine that you don’t have access to the source code anymore, and you just want a quick way to alter this program’s behavior while it runs, replacing the hard-coded value of n with some value other than 5.
First, restart the program using the run command, and answer y to the question:
(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/pi/fac
Breakpoint 1, 0x00010074 in _start ()
Now you’re back at the beginning of the program, at breakpoint 1. You can edit the in-memory value of n , setting it to 7 rather than 5. First, get the memory address of n , then set the value at that address to 7. Then you can print out n to make sure the change worked.
(gdb) p &n
$8 = (<data variable, no debug info> *) 0x200ac
(gdb) set {int}0x200ac = 7
(gdb) p (int)n
$9 = 7
Now go to the end of the program and see if result gets updated to the expected value of 7 factorial, which is 5,040. You can get rid of your two middle breakpoints (numbers 2 and 3), since you want to go straight to the end:
(gdb) disable 2
(gdb) disable 3
(gdb) c
Continuing.
Breakpoint 4, 0x000100a0 in end ()
(gdb) p (int)result
$10 = 5040
You should see a value of 5,040 for result . If so, you’ve just successfully hacked a program to make it do your bidding—all without touching the source code!
At this point you may want to try setting n to other values and see if you get the expected results. To do this, restart the program using the run command, edit the in-memory value of n , continue to the final breakpoint, and check the value of result . However, if you use a value of n larger than 12, you get an incorrect result. See the answer to Exercise 8-1 in Appendix A for the reason why this is so.
If you allow the program to continue to the end, the process exits, and you should get a message like Inferior 1 (process 946) exited normally . This isn’t an insult of your code, rather “inferior” is just how gdb refers to the target being debugged! You can exit the debugger at any time by entering quit in gdb .
PROJECT #13: EXAMINING MACHINE CODE
Prerequisite: Project #12 .
Let’s say that you were given the fac executable file, but not the original assembly language source file. You want to know what the program does, but you don’t have the source code. As you saw in Project #12 , you can use the gdb debugger to examine the fac executable file. In this project, I’ll show you a different set of tools for examining machine code.
Open a terminal on your Raspberry Pi. By default, the terminal should open to the home folder, indicated by the ~ character. In this folder you should have three factorial-related files from the last project. Check this with the following command:
$ ls fac*
You should see
fac The executable file
fac.o The object file generated during assembly
fac.s The assembly language source code
In our fictional scenario, you only have the executable fac file, and you want to know what you can learn about the program from the contents of this file. First, look at the bytes contained in the file as hexadecimal values by using the hexdump tool:
$ hexdump -C fac
The beginning of the hexdump output should look something like Figure 8-4 (without the annotations), displaying the bytes in the fac executable file.
Figure 8-4: Hex dump of Linux executable file
What you see is simply a sequential listing of the bytes in the file, each displayed as a two-character hexadecimal value. If the output of this command is too large to fit in your terminal window, scroll up to see the beginning bytes. The eight-character hex numbers along the left-hand column represent the offset into the file of the first byte in the corresponding row. There are 16 bytes on each row, meaning the offset number of each row (along the left) increases by 0x10. On the right-hand side of the output are the same bytes interpreted as ASCII. Bytes that do not correspond to a printable ASCII character code are indicated with a period.
At offset 00000000 , the very beginning of the file, you should see a 7F , followed by 45 4c 46 , or in ASCII, ELF . This is an indicator that this is a file that is in executable and linkable format (ELF) . ELF files are the standard Linux format for executable programs. These 4 bytes mark the beginning of the ELF header , a set of properties that describe the contents of the file. Following the ELF header is a program header , which provides details needed by the operating system to run the program.
Now move past the headers and find the text section that contains the program’s machine instructions. On my system, offset 00000074 is the beginning of the text section, and it starts with bytes 28 10 9f e5 . If you rearrange these bytes last-to-first, you get e59f1028 , which is the machine code instruction for ldr r1, [pc, #40] . Each set of 4 bytes in this section is a machine instruction. Looking at the program in this way is a good reminder that the code of the fac program is simply represented as a sequence of bytes. Refer to Figure 8-1 for a reminder of how machine code is represented in binary.
Later in the output, at offset 000000ac on my system, you should see the data section of the file, containing the two initial 4-byte values defined by the program. You don’t see the n and result labels here, but you should see 05 00 00 00 and 00 00 00 00 . The offset of these bytes on your system may differ from mine.
As a side note, the order in which computers store bytes of data for larger numerical values is known as endianness . When a computer stores the least significant byte first (at the lowest address) this is called little-endian . Storing the most significant byte first is called big-endian . In the hexdump output, you see little-endian storage, since the 32-bit machine instruction of e59f1028 was stored as bytes in this order: 28 10 9f e5 . The least significant byte was stored first. The same can be said of the values of n and result . The value of n is stored as 05 00 00 00 , meaning 00000005 when you consider it as a 32-bit integer.
If you want to view parts of this hexadecimal data, but grouped into sections, you can use the objdump tool:
$ objdump -s fac
This dumps out some of the same bytes as before, but grouped into sections, like so:
Contents of section .text:
10074 28109fe5 000091e5 013050e2 020000da (........0P.....
10084 930000e0 013053e2 fcffff1a 10109fe5 .....0S.........
10094 000081e5 0000a0e3 0170a0e3 000000ef .........p......
100a4 ac000200 b0000200 ........
Contents of section .data:
200ac 05000000 00000000 ........
Contents of section .ARM.attributes:
0000 41130000 00616561 62690001 09000000 A....aeabi......
0010 06010801 ....
Note how the numbers along the left-hand side have changed. Instead of starting at 0074 , the .text section (that is, code) starts at 10074 . Instead of starting at 00ac , the .data section containing the values of n and result starts at 200ac . The hexdump tool simply shows the byte offset within the file, whereas objdump output refers to the address where the bytes are loaded in memory when the program runs. Another way to view the addresses of the various sections in an ELF executable file is with readelf -e fac . This displays the headers in the file.
You can now try another feature of objdump , disassembly of machine code, so you can see the assembly language instructions alongside the machine code byte values.
$ objdump -d fac
fac: file format elf32-littlearm
Disassembly of section .text:
00010074 <_start>:
10074: e59f1028 ldr r1, [pc, #40] ; 100a4 <end+0x14> ❶
10078: e5910000 ldr r0, [r1]
1007c: e2503001 subs r3, r0, #1
10080: da000002 ble 10090 <end>
00010084 <loop>:
10084: e0000093 mul r0, r3, r0
10088: e2533001 subs r3, r3, #1
1008c: 1afffffc bne 10084 <loop>
00010090 <end>:
10090: e59f1010 ldr r1, [pc, #16] ; 100a8 <end+0x18>
10094: e5810000 str r0, [r1]
10098: e3a00000 mov r0, #0
1009c: e3a07001 mov r7, #1
100a0: ef000000 svc 0x00000000
100a4: 000200ac .word 0x000200ac
100a8: 000200b0 .word 0x000200b0
You should expect to see output similar to what is shown here. Note that the instruction at address 10074 ❶ is the same sequence of bytes highlighted in Figure 8-4 , the first 4 bytes of machine code. This output is very similar to the output from gdb in the previous project. Consider what this means: using tools like gdb or objdump , you can easily view the machine code and corresponding assembly language for any executable!
Using the techniques I’ve described in the preceding pages, you can get a view of the contents of an ELF executable file. This applies to any standard ELF file on a Linux system, not just code you wrote. Feel free to explore the machine code of any ELF file on your computer. For example, say you want to see the machine code for ls —the tool you used earlier to list the contents of a directory. First, you need to find the filesystem location of the ls ELF file, like so:
$ whereis ls
ls: /bin/ls /usr/share/man/man1/ls.1.gz
This tells us the binary executable file for ls is located at /bin/ls (you can ignore any additional results returned). Now you can run objdump (or any of the other tools already covered) to see the machine code for ls :
$ objdump -d /bin/ls > ls.txt
The output of this command is rather long, so it is redirected to a file named ls.txt . You don’t see the disassembled code in the terminal window; instead it is written to the ls.txt file, which you can view using the text editor of your choice. Of course, since Linux is open source, you can just look at the source code for the ls tool online. However, not everything is open source, and this project should give you an idea of how you can view the disassembled code for any Linux executable program.