This C program doesn’t use any C standard library functions. An ordinary “hello world” program might use printf, ultimately making the write sys

Hello world in C inline assembly

submited by
Style Pass
2024-06-16 06:30:04

This C program doesn’t use any C standard library functions. An ordinary “hello world” program might use printf, ultimately making the write system call. The above program bypasses this and makes the system call more directly using “inline assembly”. This program works on Linux x86-64, but because assembly is so non-portable, probably doesn’t work on most other systems.

Inline assembly is written using the syntax form asm(...). The above program uses this in a couple of ways. First, the statement asm("syscall"); injects a syscall assembly instruction at that point in the program. The syscall instruction expects a system call number in register rax. The program arranges for rax to hold the value 1, the system call number for write. It arranges this by declaring the local variable syscall_no as register, and specifically marking this register variable to be stored in register rax using asm("rax"). The arguments for the write system call are put in rdi, rsi and rdx using the same feature.

In the statement asm("syscall"), the string "syscall" is assembly in “gas” (GNU ASsembler) syntax. We can write longer partions of assembly here. For example, we can prepare the registers rax, rdi and rdx using mov instructions instead of C variables:

Leave a Comment