Skip to content
systemcoding.dev
Assembly

Assemble and Link a GNU as Program on Linux

Assemble a GNU as source file on Linux x86-64 and link it three ways: with ld as a freestanding program, with gcc and libc, and with gcc driving as itself.

6 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the GNU, Linux and AMD logos.

The GNU assembler, as, is already on every Linux machine that has a C compiler, because GCC compiles C to assembly text and hands it to as. That makes it the easiest assembler to start with: no install, and the same tool that produced the code you will be reading in compiler listings. This post builds a small program with GNU as from binutils 2.42 three ways on x86-64 Linux: as a freestanding binary linked with ld, as a libc program linked with gcc, and by letting gcc run as itself from a .s or .S file. The directive reference is the GNU as manual.

The smallest program

This file uses AT&T syntax, the default, and Linux system calls directly. It writes a line and exits with status 0.

hello.sasm
    .globl  _start

    .section .rodata
msg:
    .ascii  "hello from as\n"
    .set    len, . - msg

    .text
_start:
    movl    $1, %eax            # sys_write
    movl    $1, %edi            # fd 1 is stdout
    leaq    msg(%rip), %rsi     # address of the message
    movl    $len, %edx          # byte count
    syscall

    movl    $60, %eax           # sys_exit
    xorl    %edi, %edi          # status 0
    syscall

    .section .note.GNU-stack,"",@progbits

Each directive does one thing. .globl _start exports the entry symbol to the linker. .section .rodata switches to read-only data, and .text switches back to code. .ascii stores the bytes without a terminator, and .set len, . - msg defines a constant from the difference between the current location and msg, so len is 14. The last line marks the stack as non-executable, which silences the linker warning from binutils 2.39 and later.

Assemble

Shell
as hello.s -o hello.o

as has few options you need on day one. -g adds debug line information, --64 forces 64-bit mode (the default on a 64-bit host), -a or -al prints a listing to standard output, and -o names the output. Run as --version to check you are on a recent binutils; this post assumes 2.42, and every directive used here has been stable for many releases.

A listing is the fastest way to see what happened:

Shell
as -al hello.s -o hello.o
Text
   1                    	.globl  _start
   2
   3                    	.section .rodata
   4                    msg:
   5 0000 68656C6C 	.ascii  "hello from as\n"
   5      6F206672
   5      6F6D2061
   5      730A
   6                    	.set    len, . - msg
   7
   8                    	.text
   9                    _start:
  10 0000 B8010000 	movl    $1, %eax
  10      00
  11 0005 BF010000 	movl    $1, %edi
  11      00
  12 000a 488D3500 	leaq    msg(%rip), %rsi
  12      000000
  13 0011 BA0E0000 	movl    $len, %edx
  13      00
  14 0016 0F05     	syscall

The columns are the line number, the offset within the section, and the bytes. The lea shows 00 00 00 for its displacement because the distance to msg is a relocation filled in at link time. The movl $len, %edx shows 0E, which is 14: the assembler computed the constant itself.

A program with _start and no libc needs only the linker:

Shell
ld hello.o -o hello
./hello
Text
hello from as

ld finds _start by default, places the segments and writes an ELF executable. readelf -h hello shows Type: EXEC and the entry point, and file hello says "statically linked" because no dynamic loader is involved. If ld prints cannot find entry symbol _start, the source forgot .globl _start, or the entry has another name that you can select with ld -e name.

To call library functions, write main and link with gcc. The C runtime then runs first and calls your function. Here is the same message through puts:

greet.sasm
    .globl  main

    .section .rodata
msg:
    .asciz  "hello from main"

    .text
main:
    subq    $8, %rsp            # align the stack for the call
    leaq    msg(%rip), %rdi
    call    puts@PLT
    xorl    %eax, %eax          # return 0
    addq    $8, %rsp
    ret

    .section .note.GNU-stack,"",@progbits
Shell
as greet.s -o greet.o
gcc greet.o -o greet
./greet
Text
hello from main

Two details matter. The System V ABI requires RSP to be a multiple of 16 at the point of a call, and on entry to main it is 8 off, hence the subq $8, %rsp. And call puts@PLT asks for a call through the procedure linkage table, which gcc produces by default for a position-independent executable. Writing call puts also works in current binutils, because the linker converts it when needed, but the explicit form shows the intent.

.asciz appends the terminating zero byte that puts needs, which is the difference from .ascii.

Let gcc run as

gcc accepts assembly files directly. A .s file goes to as unchanged, and a .S file, with a capital S, goes through the C preprocessor first. One command assembles and links:

Shell
gcc greet.s -o greet
gcc -c greet.s -o greet.o

The second form stops after assembling, like as. Using gcc as the driver brings three benefits: the same flags as the rest of a C project (-g, -m64, -fPIE), the preprocessor for .S files so you can #include headers and use #define constants, and automatic selection of the right assembler flags for the target. The cost is that the commands hide what happens, so when something fails you have to add -v to gcc to see the exact as and ld invocations.

For the preprocessor, rename the file greet.S and write something like:

greet.Sasm
#include <asm/unistd.h>

    .globl  _start
    .text
_start:
    movl    $__NR_exit, %eax
    movl    $3, %edi
    syscall

The header defines __NR_exit as 60 on x86-64. A line starting with #include is a preprocessor directive here, not a comment, which is why the comment character # is risky at the beginning of a line in .S files. Build it with gcc -nostdlib -static greet.S -o exit3 && ./exit3; echo $?, and the shell prints:

Text
3

Debug information and listing

With -g, as generates line information for the source file, so GDB steps through your assembly by line:

Shell
as -g hello.s -o hello.o
ld hello.o -o hello
gdb -q hello

In GDB, break _start, run, then layout asm or stepi lets you follow each instruction, and info registers rax rdi rsi rdx shows the system call arguments right before the syscall. Without -g you still get symbols, so break _start works, but source lines are not available.

The -a listing flags combine: -alh includes high-level source for compiler output, and -als includes symbol tables. For hand-written code, -al is enough.

Useful binutils for inspecting the result

CommandShows
objdump -d hello.odisassembly in AT&T syntax
objdump -d -M intel hello.othe same in Intel syntax
objdump -dr hello.odisassembly with relocations
readelf -S hello.osection headers
readelf -s hello.osymbol table
readelf -r hello.orelocation entries
nm hello.osymbols with type letters
size hellotext, data and bss sizes

nm hello.o is a good first check after assembling. In the output, a T marks a global symbol in the text section, a t a local one, R and r the read-only data equivalents, and U an undefined reference that the linker must resolve:

Text
0000000000000000 r msg
0000000000000000 T _start

The r for msg shows it is local and in read-only data, while _start is global text.

Common errors

Text
hello.s: Assembler messages:
hello.s:9: Error: operand type mismatch for `movq'

movq with a 64-bit immediate does not exist as a single instruction; use movabsq or a 32-bit move that zero-extends.

Text
/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000

Add .globl _start or use ld -e main.

Choosing the entry symbol and the dialect

Two habits save time in a GNU as project. First, decide early whether the file defines _start or main, and write that in a comment at the top, because the choice decides the link command: a file that mixes both entry points links without error and then starts at whichever symbol the toolchain prefers. Second, keep one dialect per file. The .intel_syntax noprefix directive is legal at any point, but a file that switches halfway is difficult to read and to diff against compiler output, which is always AT&T. If you want Intel syntax, put the directive on the first line and leave it.

When a link fails and the cause is not obvious, ask gcc to show its work with gcc -v greet.s -o greet 2>&1 | grep -E 'as |collect2|ld '. The output lists the exact commands, including the extra start-up objects, so you can compare them with the manual ld line from earlier and see which piece your own command was missing.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.