Okay, so I’ve been messing around with “as” lately, you know, the GNU assembler. I figured I’d try to put together a super basic assembly program, just to get the hang of it. I’m calling this little experiment “as 101”.
Getting Started
First things first, I needed a text editor. I just used a plain old text editor, nothing fancy. I created a new file and saved it with a “.s” extension. That tells the assembler that it’s an assembly language file, filename is “myfirst.s”.
Writing Some Code (The Fun Part)
I started with a super simple goal: make the program exit with a specific exit code. I want to get an exit code 1.
Here’s the code I wrote:
.global _start
_start:
mov $1, %eax # Stuff 1 into the eax register (this is for the exit syscall number)
mov $42, %ebx # Stuff 42 into ebx (this will be our exit code)
int $0x80 # Boom! Make the system call (exit in this case)
I then saved the file.
Assembling the Thing
Next, I opened up my terminal. I used the “as” command to assemble my code. It went something like this:
as myfirst.s -o myfirst.o
Basically, I’m telling “as” to take “myfirst.s” and turn it into an object file named “myfirst.o”. An object file is like a… half-compiled thing. It’s not quite a runnable program yet.
Linking It Up
To make it runnable, I needed to link it. I used the “ld” command for this:
ld myfirst.o -o myfirst
This tells “ld” to take “myfirst.o” and create an executable file named “myfirst”. Now that’s something I can run.
Running the Beast
Back in the terminal, I typed:
./myfirst
Nothing showed up on the screen, which is what I expected. This program doesn’t print anything. But, I wanted to see that exit code. So, I used this little trick:
echo $?
And guess what? It printed “42”! Success! The program exited with the code I set in the ebx register.
But I want to get 1, remember the code? oh I get it, I make some change
.global _start
_start:
mov $1, %eax # Stuff 1 into the eax register (this is for the exit syscall number)
mov $1, %ebx # Stuff 1 into ebx (this will be our exit code)
int $0x80 # Boom! Make the system call (exit in this case)
I tried again, from assembled to linked to run, and use echo $?, yes! I get the exit code 1!
Wrapping Up
It was a pretty simple program, but it helped me understand the basic workflow: write the assembly code, assemble it with “as”, link it with “ld”, and then run it. Then I use some little trick to check the program’s exit code. Feels good to get the basics down!