Libasm
42 Abu Dhabi

Libasm

x86-64 Assembly Library

2 weeks
Individual Project
AssemblyNASMCMakefileLinux

Implementation of common C standard library functions in pure x86-64 assembly language, providing deep understanding of CPU-level operations, register usage, and low-level programming concepts.

Key Features

ft_strlen

Assembly implementation of string length calculation, iterating through memory to count characters until null terminator.

ft_strcpy

Low-level string copy function copying bytes from source to destination until null terminator is reached.

ft_strcmp

String comparison at the assembly level, comparing byte by byte and returning difference values.

ft_write

System call wrapper for write operations using syscall instruction with proper register setup.

ft_read

System call wrapper for read operations implementing the read syscall with error handling.

ft_strdup

String duplication using malloc for memory allocation and assembly-level string copying.

Development Journey

Phase 1

Environment Setup

Setting up NASM assembler, understanding x86-64 architecture, System V AMD64 ABI calling conventions, and register usage.

Phase 2

String Functions

Implementation of ft_strlen, ft_strcpy, and ft_strcmp using memory addressing and loop constructs.

Phase 3

System Calls

Implementing ft_write and ft_read using syscall instruction with proper error handling and errno setting.

Phase 4

Memory Allocation

Implementing ft_strdup combining malloc calls with string operations for dynamic string duplication.

Challenges & Solutions

Calling Convention Mastery

Problem:

Understanding and correctly implementing System V AMD64 ABI calling conventions for function arguments and returns.

Solution:

Studied register usage patterns (rdi, rsi, rdx for args; rax for return) and implemented proper stack frame management.

System Call Implementation

Problem:

Correctly setting up registers for Linux syscalls and handling error conditions with errno.

Solution:

Used syscall instruction with proper register setup and implemented error checking by examining return values.

Memory Safety

Problem:

Ensuring memory operations don't cause segmentation faults or buffer overflows at the assembly level.

Solution:

Implemented careful boundary checking and null terminator handling in all string operations.

ft_strlen.s
asm
section .text
    global ft_strlen

; size_t ft_strlen(const char *s)
; rdi = pointer to string
; rax = return value (length)

ft_strlen:
    xor     rax, rax            ; Initialize counter to 0

.loop:
    cmp     byte [rdi + rax], 0 ; Compare current byte with null
    je      .done               ; If null, we're done
    inc     rax                 ; Increment counter
    jmp     .loop               ; Continue loop

.done:
    ret                         ; Return length in rax