Skip to content

IRodriguez13/IR0

Repository files navigation

IR0 Kernel

IR0 is a monolithic operating system kernel designed for x86-64 architecture, focusing on modularity, multi-language support (C, C++, Rust), and POSIX compliance.

System Architecture

The IR0 architecture is built upon a modular monolithic design, where core services reside in Ring 0, providing a robust interface for Ring 3 user applications.

graph TD
    subgraph "User Space (Ring 3)"
        INIT["Init Process"]
        Shell["Baash Shell"]
        Libc["ILibc (Standard IR0 C Library)"]
        Apps["User Applications"]
    end

    subgraph "System Call Interface"
        Syscall["Syscall Dispatcher (int 0x80)"]
    end

    subgraph "Kernel Space (Ring 0)"
        subgraph "Process Management"
            Sched["Round Robin Scheduler"]
            Proc["Process Lifecycle (Fork/Exec)"]
        end

        subgraph "Memory Management"
            Paging["Paging (Identity Map)"]
            Kalloc["Kmalloc (Static/Dynamic Heap)"]
        end

        subgraph "Virtual File System (VFS)"
            Minix["Minix FS Driver"]
            VFS["VFS Abstraction Layer"]
            DevFS["Device Nodes"]
        end

        subgraph "Network Stack (Beta)"
            ARP["ARP Protocol"]
            IPv4["IPv4 Layer"]
            RTL8139["RTL8139 Driver"]
        end

        subgraph "Hardware Abstraction Layer"
            IDT["IDT / PIC / Exceptions"]
            Timer["PIT / HPET / LAPIC"]
            Storage["ATA Disk Driver"]
            IO["PS/2 Keyboard & Mouse"]
        end
    end

    Shell --> Libc
    INIT --> Shell
    Libc --> Syscall
    Syscall --> VFS
    Syscall --> Proc
    Syscall --> Kalloc
    VFS --> Minix
    VFS --> Storage
    Proc --> Sched
    Sched --> IDT
    RTL8139 --> ARP
    ARP --> IPv4
Loading

Dependencies

The following tools are required to build and run IR0:

Essential Build Tools

  • GCC (GNU Compiler Collection) - C compiler
  • NASM (Netwide Assembler) - Assembly compiler
  • LD (GNU Linker) - ELF format linker with x86-64 support
  • Make - Build automation tool

Runtime Tools

  • QEMU (qemu-system-x86_64) - Virtual machine emulator
  • GRUB (grub-mkrescue) - Bootloader tools for ISO creation

Optional Tools

  • Python 3 - Required for kernel configuration system

Platform-Specific Notes

Linux:

  • Install build tools: apt-get install build-essential nasm qemu-system-x86 grub-pc-bin
  • Or on Debian/Ubuntu: apt-get install gcc nasm binutils make qemu-system-x86 grub-pc-bin

Windows:

  • Install MSYS2 or MinGW-w64 with binutils package
  • Ensure ELF linker is available at /usr/bin/ld.exe or /mingw64/bin/ld.exe
  • QEMU can be installed via MSYS2: pacman -S qemu

First-Time Setup

Before building the kernel, verify that all dependencies are installed:

make deptest

This command checks for all required tools and displays installation instructions for any missing dependencies.

Building the Kernel

Full Build

To build the complete kernel with ISO image and userspace programs:

make ir0

This command:

  1. Compiles all kernel source files
  2. Links the kernel binary
  3. Creates a bootable ISO image
  4. Builds userspace programs

The virtual disk image (disk.img) is created automatically on first build.

Windows Build

On Windows, use the Windows-specific Makefile:

make -f Makefile.win ir0

The Makefile automatically detects MSYS2/MinGW environments and uses the appropriate tools.

Running the Kernel

After building, run the kernel in QEMU:

make run

This starts QEMU with the kernel ISO and virtual disk attached.

Additional run options:

  • make run-debug - Run with serial debug output
  • make run-nodisk - Run without virtual disk
  • make run-console - Run in console mode (no GUI)

Development

Compiling Individual Files (Unibuild System)

IR0 provides the unibuild system for isolated compilation of individual files without rebuilding the entire kernel. This system supports C, C++, and Rust with both native and Windows cross-compilation.

Quick Start

Compile a single file:

# C files
make unibuild drivers/IO/ps2.c

# C++ files  
make unibuild-cpp cpp/examples/cpp_example.cpp

# Rust files
make unibuild-rust rust/drivers/rust_example_driver.rs

Multi-File Compilation

Compile multiple files at once:

# Compile 3 C files together
make unibuild fs/vfs.c fs/ramfs.c fs/path.c

# Compile multiple C++ files
make unibuild-cpp kernel/sched1.cpp kernel/sched2.cpp

# Using FILE= syntax (also supported)
make unibuild FILE="drivers/IO/ps2.c drivers/IO/ps2_mouse.c"

Cross-Compilation to Windows

All languages support cross-compilation to Windows using MinGW:

# C to Windows
make unibuild-win drivers/IO/ps2.c

# C++ to Windows
make unibuild-cpp-win cpp/examples/cpp_example.cpp

# Rust to Windows
make unibuild-rust-win rust/drivers/rust_example_driver.rs

# Multiple files
make unibuild-win drivers/serial/serial.c drivers/dma/dma.c

Available Targets

Target Description Example
unibuild Compile C file(s) make unibuild fs/ramfs.c
unibuild-cpp Compile C++ file(s) make unibuild-cpp cpp/example.cpp
unibuild-rust Compile Rust file(s) * make unibuild-rust rust/driver.rs
unibuild-win Cross-compile C to Windows make unibuild-win drivers/io.c
unibuild-cpp-win Cross-compile C++ to Windows make unibuild-cpp-win cpp/example.cpp
unibuild-rust-win Cross-compile Rust to Windows * make unibuild-rust-win rust/driver.rs

* Rust Note: Rust compilation for bare-metal targets requires additional setup. See Multi-Language Development section for details.

Cleaning Compiled Files

make unibuild-clean FILE=<file>

Driver Management

The build system provides specific commands to compile, link, and clean drivers on demand. This allows for modular development and testing of drivers in different languages.

Compilation and Linking:

  • make load-driver rust: Compiles and links all registered Rust drivers.
  • make load-driver cpp: Compiles and links all registered C++ drivers.
  • make load-driver rust cpp: Compiles and links both Rust and C++ drivers simultaneously.

Cleaning Driver Objects:

  • make unload-driver rust: Removes compiled objects for Rust drivers.
  • make unload-driver cpp: Removes compiled objects for C++ drivers.

Multi-Language Development

IR0 supports kernel development in C, C++, and Rust. Each language has a specific role and build requirements.

C (Primary Language)

  • Role: Kernel core, memory management, and critical system drivers.
  • Setup: Standard GCC build environment (included in build-essential).
  • Compilation: make unibuild <file.c>

C++ (Advanced Components)

  • Role: Complex kernel components, schedulers, and abstractions requiring object-oriented features.
  • Setup: Requires g++ compiler.
  • Compilation: make unibuild-cpp <file.cpp>
  • Runtime Support: The kernel includes a minimal C++ runtime (compat.cpp) supporting:
    • Global new and delete operators (mapped to kernel kmalloc/kfree).
    • Pure virtual functions.
    • Static initialization guards.

Rust (Modern Drivers)

  • Role: New device drivers (Network, Storage, USB) focusing on memory safety.
  • Setup: Requires Rust Nightly toolchain for build-std support.
    rustup toolchain install nightly
    rustup component add rust-src --toolchain nightly
    rustup target add x86_64-unknown-none
  • Compilation: make unibuild-rust <file.rs>
    • Uses cargo with -Z build-std=core to compile the standard library for the bare-metal target.

For detailed API documentation and development guidelines, please refer to CONTRIBUTING.md.

Test Drivers

The kernel includes example drivers to verify the multi-language build system.

  • make test-driver-cpp: Compiles the C++ example driver.
  • make test-drivers: Compiles all example drivers.
  • make test-drivers-clean: Removes example driver objects.

Creating Virtual Disk

The virtual disk is created automatically during build. To create it manually:

make create-disk

To remove the virtual disk:

make delete-disk

Cleaning Build Artifacts

To clean all compiled objects and binaries:

make clean

Kernel Configuration Menu (Experimental)

IR0 includes an experimental graphical configuration tool (menuconfig) that provides an interactive interface for kernel subsystem selection and compilation. This tool is designed to simplify kernel development and allow fine-grained control over which components are built.

Features:

  • Visual subsystem selection: Interactive interface showing kernel architecture layers
  • Selective compilation: Build only the subsystems you need using the integrated unibuild system
  • Real-time architecture diagram: Visual representation of kernel components and their dependencies
  • Profile support: Pre-configured profiles for different use cases (x86-64 Generic, ARM32, etc.)
  • Cross-platform: Supports Linux, Windows (MSYS2/MinGW), and macOS

Usage:

make menuconfig

Or run directly:

./menuconfig

Requirements:

  • Python 3 with tkinter support (python3-tk package on Debian/Ubuntu)

Note: This feature is currently experimental. While it provides a convenient way to configure and build the kernel subsystems, the standard make ir0 workflow remains the primary recommended build method. The configuration tool integrates with the kernel's unibuild system to compile selected subsystems incrementally.

Kernel Features

Memory Management

  • Paging with identity mapping
  • Heap allocator (kmalloc/kfree)
  • Physical memory bitmap management
  • Kernel and user space separation

Process Management

  • Process state management (NEW, READY, RUNNING, SLEEPING, STOPPED, ZOMBIE, DEAD)
  • Multiple scheduler algorithms (CFS, Priority-based, Round-Robin)
  • Context switching implementation
  • Process tree hierarchy

System Calls

  • POSIX-compatible system call interface
  • Process control (fork, exec, exit, wait, getpid)
  • File operations (open, close, read, write, lseek)
  • Memory management (brk, mmap, munmap, mprotect)
  • Time operations (time, gettimeofday, sleep, usleep)

Virtual File System

  • VFS abstraction layer
  • MINIX filesystem support
  • RAM filesystem for boot files
  • Mount point management

Hardware Drivers

  • PS/2 keyboard and mouse drivers
  • ATA storage driver with DMA support
  • RTL8139 Network Interface Card (NIC) driver
  • VGA display driver
  • Timer drivers (PIT, HPET, LAPIC)

Networking (Under Development)

  • Ethernet frame handling
  • ARP (Address Resolution Protocol)
  • IPv4 protocol foundation

Interrupt System

  • Complete IDT setup
  • PIC configuration
  • Exception handling
  • TSS configuration

Interactive Shell

  • Command-line interface
  • Built-in commands (help, info, version, ps, meminfo)
  • System integration
  • Basic authentication framework

Architecture

IR0 targets x86-64 architecture. The kernel uses:

  • ELF64 binary format
  • Multiboot boot protocol
  • Protected mode with paging
  • Ring 0 (kernel) and Ring 3 (user) separation

Build System

The build system supports:

  • Native Linux compilation
  • Native Windows compilation (with MSYS2/MinGW)
  • Cross-compilation from Linux to Windows

Build targets:

  • make ir0 - Full kernel build (Linux)
  • make -f Makefile.win ir0 - Full kernel build (Windows)
  • make deptest - Check dependencies
  • make unibuild FILE=<file> - Compile single file
  • make clean - Clean build artifacts

License

This project is licensed under the GNU General Public License v3.0. See the LICENSE file for details.


IR0 Kernel (Español)

IR0 es un kernel de sistema operativo monolítico diseñado para arquitectura x86-64, con un enfoque en la modularidad, soporte multilenguaje (C, C++, Rust) y cumplimiento de estándares POSIX.

Arquitectura del Sistema

La arquitectura de IR0 se basa en un diseño monolítico modular, donde los servicios principales residen en el Ring 0, proporcionando una interfaz robusta para las aplicaciones de usuario en el Ring 3.

graph TD
    subgraph "Espacio de Usuario (Ring 3)"
        INIT["Proceso Init"]
        Shell["Bash/Yell Shell"]
        Libc["IR0 Libc (Biblioteca C Estándar)"]
        Apps["Aplicaciones de Usuario"]
    end

    subgraph "Interfaz de Llamadas al Sistema"
        Syscall["Despachador de Syscalls (int 0x80)"]
    end

    subgraph "Espacio de Kernel (Ring 0)"
        subgraph "Gestión de Procesos"
            Sched["Planificador Round Robin"]
            Proc["Ciclo de Vida de Procesos (Fork/Exec)"]
        end

        subgraph "Gestión de Memoria"
            Paging["Paginación (Mapeo de Identidad)"]
            Kalloc["Kmalloc (Heap Estático/Dinámico)"]
        end

        subgraph "Sistema de Archivos Virtual (VFS)"
            Minix["Driver Minix FS"]
            VFS["Capa de Abstracción VFS"]
            DevFS["Nodos de Dispositivo"]
        end

        subgraph "Pila de Red (Beta)"
            ARP["Protocolo ARP"]
            IPv4["Capa IPv4"]
            RTL8139["Driver RTL8139"]
        end

        subgraph "Capa de Abstracción de Hardware"
            IDT["IDT / PIC / Excepciones"]
            Timer["PIT / HPET / LAPIC"]
            Storage["Driver de Disco ATA"]
            IO["Teclado y Ratón PS/2"]
        end
    end

    Shell --> Libc
    INIT --> Shell
    Libc --> Syscall
    Syscall --> VFS
    Syscall --> Proc
    Syscall --> Kalloc
    VFS --> Minix
    VFS --> Storage
    Proc --> Sched
    Sched --> IDT
    RTL8139 --> ARP
    ARP --> IPv4
Loading

Dependencias

Las siguientes herramientas son necesarias para compilar y ejecutar IR0:

Herramientas de Compilación Esenciales

  • GCC (GNU Compiler Collection) - Compilador C
  • NASM (Netwide Assembler) - Compilador de ensamblador
  • LD (GNU Linker) - Enlazador con soporte para formato ELF x86-64
  • Make - Herramienta de automatización de compilación

Herramientas de Ejecución

  • QEMU (qemu-system-x86_64) - Emulador de máquina virtual
  • GRUB (grub-mkrescue) - Herramientas de bootloader para creación de ISO

Herramientas Opcionales

  • Python 3 - Requerido para el sistema de configuración del kernel

Notas Específicas por Plataforma

Linux:

  • Instalar herramientas de compilación: apt-get install build-essential nasm qemu-system-x86 grub-pc-bin
  • O en Debian/Ubuntu: apt-get install gcc nasm binutils make qemu-system-x86 grub-pc-bin

Windows:

  • Instalar MSYS2 o MinGW-w64 con el paquete binutils
  • Asegurar que el enlazador ELF esté disponible en /usr/bin/ld.exe o /mingw64/bin/ld.exe
  • QEMU se puede instalar vía MSYS2: pacman -S qemu

Configuración Inicial

Antes de compilar el kernel, verificar que todas las dependencias estén instaladas:

make deptest

Este comando verifica todas las herramientas requeridas y muestra instrucciones de instalación para cualquier dependencia faltante.

Compilación del Kernel

Compilación Completa

Para compilar el kernel completo con imagen ISO y programas de espacio de usuario:

make ir0

Este comando:

  1. Compila todos los archivos fuente del kernel
  2. Enlaza el binario del kernel
  3. Crea una imagen ISO booteable
  4. Compila los programas de espacio de usuario

La imagen de disco virtual (disk.img) se crea automáticamente en la primera compilación.

Compilación en Windows

En Windows, usar el Makefile específico de Windows:

make -f Makefile.win ir0

El Makefile detecta automáticamente los entornos MSYS2/MinGW y usa las herramientas apropiadas.

Ejecución del Kernel

Después de compilar, ejecutar el kernel en QEMU:

make run

Esto inicia QEMU con la ISO del kernel y el disco virtual adjunto.

Opciones adicionales de ejecución:

  • make run-debug - Ejecutar con salida de depuración serial
  • make run-nodisk - Ejecutar sin disco virtual
  • make run-console - Ejecutar en modo consola (sin GUI)

Desarrollo

Compilación de Archivos Individuales

Al desarrollar controladores o módulos del kernel, compilar un solo archivo de forma aislada:

make unibuild drivers/IO/ps2.c

O usando la sintaxis tradicional:

make unibuild FILE=drivers/IO/ps2.c

Compilación Cruzada para Múltiples Plataformas:

Compilar para Windows usando el compilador cruzado MinGW:

make unibuild -win drivers/IO/ps2.c

Soporte para otros lenguajes:

make unibuild -cpp kernel/module.cpp    # Soporte C++ (planificado)
make unibuild -rust kernel/module.rs    # Soporte Rust (planificado)

Esto compila el archivo especificado sin compilar todo el kernel. Se pueden compilar múltiples archivos a la vez:

make unibuild fs/vfs.c fs/ramfs.c
make unibuild -win drivers/serial/serial.c drivers/dma/dma.c

Para limpiar un archivo compilado individual:

make unibuild-clean FILE=drivers/IO/ps2.c

Creación de Disco Virtual

El disco virtual se crea automáticamente durante la compilación. Para crearlo manualmente:

make create-disk

Para eliminar el disco virtual:

make delete-disk

Limpieza de Artefactos de Compilación

Para limpiar todos los objetos compilados y binarios:

make clean

Menú de Configuración del Kernel (Experimental)

IR0 incluye una herramienta gráfica de configuración experimental (menuconfig) que proporciona una interfaz interactiva para la selección y compilación de subsistemas del kernel. Esta herramienta está diseñada para simplificar el desarrollo del kernel y permitir un control granular sobre qué componentes se compilan.

Características:

  • Selección visual de subsistemas: Interfaz interactiva mostrando las capas de arquitectura del kernel
  • Compilación selectiva: Compila solo los subsistemas que necesites usando el sistema integrado unibuild
  • Diagrama de arquitectura en tiempo real: Representación visual de los componentes del kernel y sus dependencias
  • Soporte de perfiles: Perfiles preconfigurados para diferentes casos de uso (x86-64 Genérico, ARM32, etc.)
  • Multiplataforma: Soporta Linux, Windows (MSYS2/MinGW) y macOS

Uso:

make menuconfig

O ejecutar directamente:

./menuconfig

Requisitos:

  • Python 3 con soporte para tkinter (paquete python3-tk en Debian/Ubuntu)

Nota: Esta característica es actualmente experimental. Aunque proporciona una manera conveniente de configurar y compilar los subsistemas del kernel, el flujo de trabajo estándar make ir0 sigue siendo el método de compilación principal recomendado. La herramienta de configuración se integra con el sistema unibuild del kernel para compilar subsistemas seleccionados de forma incremental.

Características del Kernel

Gestión de Memoria

  • Paginación con mapeo de identidad
  • Asignador de heap (kmalloc/kfree)
  • Gestión de mapa de bits de memoria física
  • Separación de espacio de kernel y usuario

Gestión de Procesos

  • Gestión de estados de proceso (NEW, READY, RUNNING, SLEEPING, STOPPED, ZOMBIE, DEAD)
  • Múltiples algoritmos de planificación (CFS, basado en prioridad, Round-Robin)
  • Implementación de cambio de contexto
  • Jerarquía de árbol de procesos

Llamadas al Sistema

  • Interfaz de llamadas al sistema compatible con POSIX
  • Control de procesos (fork, exec, exit, wait, getpid)
  • Operaciones de archivo (open, close, read, write, lseek)
  • Gestión de memoria (brk, mmap, munmap, mprotect)
  • Operaciones de tiempo (time, gettimeofday, sleep, usleep)

Sistema de Archivos Virtual

  • Capa de abstracción VFS
  • Soporte para sistema de archivos MINIX
  • Sistema de archivos RAM para archivos de arranque
  • Gestión de puntos de montaje

Controladores de Hardware

  • Controladores de teclado y ratón PS/2
  • Controlador de almacenamiento ATA con soporte DMA
  • Controlador de tarjeta de red RTL8139 (NIC)
  • Controlador de pantalla VGA
  • Controladores de temporizador (PIT, HPET, LAPIC)

Redes (En Desarrollo)

  • Manejo de tramas Ethernet
  • Protocolo ARP (Address Resolution Protocol)
  • Base del protocolo IPv4

Sistema de Interrupciones

  • Configuración completa de IDT
  • Configuración de PIC
  • Manejo de excepciones
  • Configuración de TSS

Shell Interactivo

  • Interfaz de línea de comandos
  • Comandos integrados (help, info, version, ps, meminfo)
  • Integración con el sistema
  • Marco básico de autenticación

Arquitectura

IR0 está dirigido a la arquitectura x86-64. El kernel utiliza:

  • Formato binario ELF64
  • Protocolo de arranque Multiboot
  • Modo protegido con paginación
  • Separación de Ring 0 (kernel) y Ring 3 (usuario)

Sistema de Compilación

El sistema de compilación soporta:

  • Compilación nativa en Linux
  • Compilación nativa en Windows (con MSYS2/MinGW)
  • Compilación cruzada desde Linux a Windows

Objetivos de compilación:

  • make ir0 - Compilación completa del kernel (Linux)
  • make -f Makefile.win ir0 - Compilación completa del kernel (Windows)
  • make deptest - Verificar dependencias
  • make unibuild FILE=<archivo> - Compilar archivo individual
  • make clean - Limpiar artefactos de compilación

Documentación

Documentación adicional disponible en el repositorio:

  • Sistema de Compilación: setup/docs/BUILD_SYSTEM.md
  • Instalación: setup/docs/INSTALL.md
  • Configuración: setup/docs/CONFIGURATION_SYSTEM_README.md
  • Sistema de Inclusión: setup/docs/INCLUDE_SYSTEM_GUIDE.md

Licencia

Este proyecto está licenciado bajo la Licencia Pública General de GNU v3.0. Ver el archivo LICENSE para más detalles.