An example we can build upon– Creating Our Own Fibers

Note

We will use the Intel dialect in our examples.

Assembly has strong backward compatibility guarantees. That’s why you will see that the same registers are addressed in different ways. Let’s look at the rax register we used as an example as an explanation:
rax    # 64 bit register (8 bytes)
eax    # 32 low bits of the “rax” register
ax     # 16 low bits of the “rax” register
ah     # 8 high bits of the “ax” part of the “rax” register
al     # 8 low bits of the “ax” part of the “rax” register

As you can see, this is basically like watching the history of CPUs evolve in front of us. Since most CPUs today are 64 bits, we will use the 64-bit versions in our code.

The word size in the assembly also has historical reasons. It stems from the time when the CPU had 16-bit data buses, so a word is 16 bits. This is relevant because you will see many instructions suffixed with q (quad word) or l (long word). So, a movq would mean a move of 4 * 16 bits, which is 64 bits.

A plain mov will use the size of the register you target on most modern assemblers. This is the one you will see most used in both AT&T and the Intel dialect when writing inline assembly, and it’s the one we will use in our code.

One more thing to note is that the stack alignment on x86-64 is 16 bytes. Just remember this for later.

An example we can build upon

This is a short example where we will create our own stack and make our CPU return out of its current execution context and over to the stack we just created. We will build on these concepts in the following chapters.

Setting up our project

First, let’s start a new project by creating a folder named a-stack-swap. Enter the new folder and run the following:
cargo init

Tip

You can also navigate to the folder called ch05/a-stack-swap in the accompanying repository and see the whole example there.

In our main.rs, we start by importing the asm! macro:

ch05/a-stack-swap/src/main.rs
use core::arch::asm;

Let’s set a small stack size of only 48 bytes here so that we can print the stack and look at it before we switch contexts after we get the first example to work:
const SSIZE: isize = 48;

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post