6. Under the C: Diving into Assembly

Under the C, under the C

Don’t you know it’s better

Dealing with registers

And assembly?

-Sebastian, probably

Prior to the invention of the compiler in the early days of computing, many programmers coded in assembly language, which directly specifies the set of instructions that a computer follows during execution. Assembly language is the closest a programmer gets to coding at the machine level without writing code directly in 1s and 0s and is a readable form of machine code. To write efficient assembly code, programmers must intimately understand the operation of the underlying machine architecture.

The invention of the compiler fundamentally changed the way programmers write code. A compiler translates a human readable programming language (usually written using English words) into a language that a computer understands (i.e. machine code). Compilers translate the human readable code into machine code using the rules of the programming language, specification of the operating system, and the instruction set of the machine and provides some error detection and type checking in the process. Most modern compilers produce assembly code that is as efficient as the hand-written assembly code of yesteryear.

The Benefits of Learning Assembly

Given all the benefits of compilers, it may not be obvious why learning assembly is useful. However, there are several compelling reasons to learn and understand assembly code. Here are a few examples:

1. Higher level abstraction hides valuable program details

The abstraction provided by high-level programming languages is a boon for reducing the complexity of programming. At the same time, this simplification makes it easy for programmers to make design decisions without fully understanding the ramifications of their choices at the machine level. Lacking a knowledge of assembly often prevents a programmer from understanding valuable information on how a program runs and limits their ability to understand what their code is actually doing.

As an example, take a look at the following program:

#include <stdio.h>

int adder() {
    int a;
    return a + 2;
}

int assign() {
    int y = 40;
    return y;
}

int main() {
    int x;
    assign();
    x = adder();
    printf("x is: %d\n", x);
    return 0;
}

What is the program’s output? At first glance, the assign() function appears to have no effect, as its return value is not stored by any variable in main(). The adder() function returns the value of a + 2, although the variable a is uninitialized (though on some machines the compiler will initialize a to 0). Printing out x should result in an undefined value. However, compiling and running it on most 64-bit machines consistently produces an answer of 42:

$ gcc -o example example.c
$ ./example
x is: 42

The output of this program seems nonsensical at first glance, as the adder() and assign() functions appear to be disconnected. Understanding stack frames and how functions execute under the hood will help you understand why the answer is 42. We revisit this example later in the upcoming chapters.

2. Some computing systems are too resource-constrained for compilers

The most common types of "computers" are the ones we cannot readily identify as computers. These devices exist everywhere from cars and coffee makers to washing machines and smart watches. Sensors, microcontrollers, and other embedded processors play an increasingly dominant role in our lives and all require software to operate. However, the processors contained in such devices are often so small that they cannot execute the compiled code written by higher-level programming languages. In many cases, these devices require standalone assembly programs that are not dependent on the run-time libraries required by common programming languages.

3. Vulnerability analysis

A subset of security professionals spend their days trying to identify vulnerabilities in various types of computer systems. Many avenues for attacking a program involve the way the program stores its run-time information. Learning assembly enables security professionals to understand how vulnerabilities arise and how they can be exploited.

Other security professionals spend time "reverse engineering" malicious code in malware and other malicious software. A working knowledge of assembly is essential to enable these software engineers to quickly develop counter-measures to protect systems against attack. Lastly, developers who lack an understanding of how the code they write translates to assembly may end up unwittingly writing vulnerable code.

4. Critical Code Sequences in System-level software

Lastly, there are just some components of a computer system that cannot be optimized sufficiently by compilers and require hand-written assembly. Some system levels have hand-written assembly code in areas where detailed machine-specific optimizations are critical for performance. For example, the boot sequence on all computers is written in assembly code. Operating systems often contain hand-written assembly for thread or process context-switching. Humans are often able to produce better optimized assembly code than compilers for these short and performance-critical sequences.

What You Will Learn in the Coming Chapters

The next three chapters cover three different flavors of assembly. Chapter 7 and Chapter 8 cover x86_64 and its earlier form, IA32. Chapter 9 covers ARMv8-A assembly, which is ISA found on most modern ARM devices, including single board computers like the Raspberry Pi. Chapter 10 contains a summary and some key takeaways for learning assembly.

Each of these different flavors of assembly implement different Instruction Set Architectures (ISA). Recall that an ISA defines: the set of instructions and their binary encoding; the set of CPU registers; and the effects of executing instructions on the state of the CPU and memory.

In the following three chapters that cover different ISA assembly languages, you will see general similarities across all ISAs, including that CPU registers are used as operands of many instructions, and that each ISA provides similar types of instructions, namely:

  1. Instructions for computing arithmetic and logic operations, such as addition or bit-wise AND.

  2. Instructions for control flow that are used to implement branching such as if-else, loops, and function call and return.

  3. Instructions for data movement that load and store values between CPU registers and memory.

  4. Instructions for pushing and popping values from the stack. These instructions are used to implement the execution call stack, where a new frame of stack memory that stores a function activation’s local variables and parameters is added to the top of the stack on a function call, and a frame is removed from the top of the stack on a function return.

A C compiler translates C source code to a specific ISA instruction set. The compiler uses the set of instructions defined by a specific ISA to translate C statements, including loops and if-else, function calls, and variable access, to a specific set of instructions defined by the ISA and implemented by a CPU that is designed to execute instructions from the specific ISA. For example, a compiler translates C to x86 instructions for execution on an Intel x86 processor, or translates C to ARM instructions for execution on an ARM processor.

As you read the chapters in the assembly part of the book, you may note that some key terms are redefined and that some figures reproduced. To best aid other CS educators, we designed each chapter to be used "in whole" at particular colleges and universities. While most of the material in each chapter is unique, we hope the commonalities between the chapters help reinforce the similarities between the different flavors of assembly in the mind of readers.

Ready to learn assembly? Let’s dive right in! Follow the links below to visit particular chapters of interest: