Thanks to visit codestin.com
Credit goes to github.com

Skip to content

IRodriguez13/IR0

Repository files navigation

IR0 Kernel

IR0 is a modern monolithic operating system kernel designed for x86-64 architecture, focusing on modularity, multi-language support (C, C++, Rust), POSIX compliance, and extensibility. With over 33,000 lines of code across 224 files, IR0 provides a complete operating system foundation featuring advanced memory management, comprehensive process control, virtual file system, hardware drivers, and integrated networking capabilities.

Recent Major Updates

Bluetooth Experimental (In Progress)

  • HCI (Host Controller Interface) UART transport layer implemented
  • H4 protocol support for Bluetooth communication
  • Phase 1 Complete: Basic HCI transport over UART (COM1)
  • Coming Next: HCI Core commands, device discovery, filesystem integration
  • Experimental feature: Requires physical Bluetooth-UART adapter (HC-05, HC-06, or USB-UART dongle)

Multi-Language Driver System

  • Native support for drivers written in C, C++, and Rust
  • Unified driver registry with automatic initialization
  • Cross-compilation support for all languages to Windows targets
  • Runtime integration with kernel memory management and interrupts

Enhanced Security & Validation

  • Comprehensive path validation preventing traversal attacks
  • Buffer overflow protection in network and filesystem code
  • Secure disk management with host system protection
  • Memory safety improvements in allocator and paging systems

Advanced Virtual File System

  • Multiple filesystem support: MINIX, RAMFS, TMPFS, ProcFS, DevFS, SysFS
  • Dynamic mount system with cross-filesystem path resolution
  • POSIX-compliant operations with full permission model
  • Real-time process information via /proc filesystem

Production-Ready Networking

  • Complete TCP/IP stack with Ethernet, ARP, IPv4, ICMP, UDP
  • Hardware driver support: RTL8139 and Intel e1000 NICs
  • Network configuration tools: ifconfig, ping, netinfo
  • TAP networking support for development and testing

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 TB
    subgraph UserSpace["User Space (Ring 3)"]
        Apps["User Applications"]
        Shell["Interactive Shell"]
        Init["Init Process (PID 1)"]
    end

    subgraph SyscallLayer["System Call Interface"]
        Syscall["Syscall Dispatcher<br/>(INT 0x80)"]
    end

    subgraph KernelCore["Kernel Core (Ring 0)"]
        subgraph ProcessMgmt["Process Management"]
            Proc["Process Lifecycle<br/>(Fork/Exec/Wait)"]
            Sched["Round Robin Scheduler"]
        end
        
        subgraph MemMgmt["Memory Management"]
            Paging["Paging"]
            Kalloc["Heap Allocator<br/>(kmalloc/kfree)"]
            PMM["Physical Memory Manager"]
        end
        
        subgraph VFSSystem["Virtual File System"]
            VFS["VFS Layer"]
            MinixFS["Minix FS"]
            RAMFS["RAMFS"]
            ProcFS["/proc Filesystem"]
            DevFS["/dev Filesystem"]
        end
        
        subgraph Network["Network Stack"]
            NetCore["Network Core"]
            ARP["ARP Protocol"]
            IPv4["IPv4 Protocol"]
            RTL8139["RTL8139 Driver"]
        end
        
        subgraph Drivers["Device Drivers"]
            DriverReg["Driver Registry<br/>(C/C++/Rust)"]
            Storage["ATA/IDE Storage"]
            Input["PS/2 Keyboard/Mouse"]
            Audio["Audio Drivers"]
            Serial["Serial Port"]
            Timer["Timers (PIT/HPET/LAPIC)"]
        end
        
        subgraph Interrupts["Interrupt System"]
            IDT["IDT Setup"]
            PIC["PIC Controller"]
            ISR["Interrupt Handlers"]
        end
    end

    Apps -->|syscalls| Syscall
    Shell -->|syscalls| Syscall
    Init -->|spawns| Shell
    
    Syscall --> ProcessMgmt
    Syscall --> MemMgmt
    Syscall --> VFSSystem
    
    ProcessMgmt --> Sched
    Sched --> Interrupts
    
    VFSSystem --> MinixFS
    VFSSystem --> RAMFS
    VFSSystem --> ProcFS
    VFSSystem --> Storage
    
    Network --> NetCore
    NetCore --> ARP
    NetCore --> IPv4
    IPv4 --> RTL8139
    
    Drivers --> DriverReg
    Storage --> DriverReg
    Input --> DriverReg
    Audio --> DriverReg
    
    Interrupts --> Drivers
    Interrupts --> Timer
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>

Multi-Language Development

IR0 supports kernel development in C, C++, and Rust. Each language has a specific role and build requirements. The kernel provides a unified driver registry system that allows drivers written in any of these languages to be registered and initialized at boot time.

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 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.
  • Freestanding Environment: C++ drivers run in a freestanding environment without standard library dependencies.

Rust (Device Drivers)

  • Role: Device drivers focusing on memory safety and modern language features.
  • Setup: Requires Rust Nightly toolchain for build-std support.
    rustup toolchain install nightly
    rustup component add rust-src --toolchain nightly
    The kernel uses a custom bare-metal target (x86_64-ir0-kernel) defined in rust/x86_64-ir0-kernel.json. The build system handles target configuration automatically.
  • Compilation: make unibuild-rust <file.rs>
    • Uses cargo with -Z build-std=core to compile the standard library for the bare-metal target.
    • Requires no_std environment with FFI bindings to kernel functions.
  • Integration: Rust drivers link statically into the kernel binary and register through the driver registry system.

Driver Registry System

All drivers (C, C++, and Rust) are registered through the unified driver registry (ir0_driver_registry). The registry provides:

  • Driver registration and initialization at boot time
  • Language-agnostic driver interface
  • Driver lifecycle management (registered, initialized, running)
  • Driver information querying (name, version, language, author)

Drivers register themselves during kernel initialization by providing driver information and operation callbacks.

Extern Drivers

The kernel includes optional extern drivers to demonstrate multi-language integration. These drivers are disabled by default and are intended for testing and development purposes only.

Enabling extern drivers:

make en-ext-drv  # Enable for next build
make ir0         # Build kernel with extern drivers

Disabling extern drivers:

make dis-ext-drv  # Disable extern drivers
make ir0          # Build kernel without extern drivers

When enabled, the extern drivers (Rust and C++) will be compiled, linked into the kernel, and automatically registered during boot initialization.

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

Virtual Disk Management

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

  • Advanced heap allocator with boundary tags and O(1) coalescing
  • Complete paging system with identity mapping and demand paging
  • Physical memory manager with bitmap-based allocation
  • Ring 0/Ring 3 separation with proper privilege isolation
  • Memory protection with page-level access controls

Process Management

  • Complete process lifecycle: create, run, terminate, wait with POSIX semantics
  • Process states: READY, RUNNING, BLOCKED, ZOMBIE with proper transitions
  • Round-Robin scheduler with configurable time quantum and preemption
  • Context switching: Assembly-optimized x86-64 implementation with full register preservation
  • Process tree hierarchy: Parent-child relationships with automatic reparenting
  • ELF loader: Complete ELF64 binary loading with proper memory mapping
  • Init system: PID 1 process with service management capabilities

System Calls

  • POSIX-compatible system call interface via INT 0x80 with full ABI compliance
  • Process management: fork, exec, exit, waitpid, getpid, getppid, spawn
  • File operations: open, close, read, write, lseek, dup2, creat with proper error handling
  • Directory operations: mkdir, rmdir, chdir, getcwd, unlink, link
  • File system: stat, fstat, mount, chmod, touch, append with permission validation
  • Memory management: brk, sbrk, mmap, munmap, mprotect with security checks
  • System information: ps, df, lsblk, whoami, ls with real-time data
  • Networking: ping, ifconfig with IPv4 configuration and diagnostics

Virtual File System

  • VFS abstraction layer with mount point resolution across multiple filesystems
  • Multiple filesystem support: MINIX (primary), RAMFS (memory), TMPFS (temporary)
  • Virtual filesystems: /proc (process info), /dev (devices), /sys (kernel info)
  • Dynamic mount management with proper unmounting and cleanup
  • Path resolution engine that traverses mounted filesystems seamlessly
  • Security validation preventing path traversal and buffer overflow attacks
  • See VIRTUAL_FILESYSTEMS.md for detailed documentation

Hardware Drivers

  • Input/Output: PS/2 keyboard and mouse drivers with interrupt handling, PC Speaker driver
  • Storage: ATA/IDE disk driver with DMA support and partition management
  • Network: RTL8139 and Intel e1000 Ethernet NIC drivers with full TCP/IP integration
  • Audio: Sound Blaster 16 driver with PCM support, Adlib OPL2 driver for FM synthesis
  • Video: VGA text mode driver with color support, VBE graphics driver (basic)
  • Timers: PIT (Programmable Interval Timer), HPET (High Precision Event Timer), LAPIC (Local APIC Timer), RTC (Real Time Clock)
  • Serial: COM1/COM2 serial port driver for debugging and communication
  • Bluetooth: Complete HCI implementation with device discovery and management
  • DMA: 8-channel DMA controller support for high-speed data transfer
  • Driver Registry: Unified driver registration system supporting C, C++, and Rust drivers

Networking

  • Complete TCP/IP stack with layered architecture (Ethernet → IP → Transport)
  • Protocol support: Ethernet frame handling, ARP (Address Resolution Protocol), IPv4 with routing
  • Transport protocols: ICMP (ping, diagnostics), UDP (basic implementation)
  • Network drivers: RTL8139 and Intel e1000 with interrupt-driven I/O
  • Configuration tools: ifconfig for interface management, ping for connectivity testing
  • Development support: TAP networking for advanced testing scenarios

Interrupt System

  • Complete IDT setup with proper exception and interrupt handling
  • PIC configuration with IRQ masking and priority management
  • Exception handling for CPU faults with signal delivery to processes
  • TSS configuration for proper privilege level transitions

Interactive Shell

  • Full-featured command-line interface with 33+ built-in commands
  • File operations: ls, cat, cp, mv, mkdir, rmdir, rm, cd, pwd, touch, chmod, chown, ln
  • System information: ps (process list), df (disk usage), lsblk (block devices), whoami, netinfo, arpcache
  • Process management: exec for program execution
  • Networking: ping for connectivity testing, ifconfig for network configuration
  • Text processing: echo with variable expansion, sed for stream editing
  • Driver management: lsdrv (list drivers), dmesg (kernel messages)
  • Hardware testing: audio_test, mouse_test for driver validation
  • System utilities: clear, help, exit, type, mount for filesystem management

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 moderno diseñado para arquitectura x86-64, con un enfoque en la modularidad, soporte multilenguaje (C, C++, Rust) y cumplimiento de estándares POSIX. Con más de 33,000 líneas de código distribuidas en 224 archivos, IR0 proporciona una base completa de sistema operativo con gestión avanzada de memoria, control integral de procesos, sistema de archivos virtual, controladores de hardware y capacidades de red integradas.

Actualizaciones Principales Recientes

Integración Bluetooth Experimental

  • Implementación HCI (Host Controller Interface) con transporte UART
  • Fase 1 completada: Capa de transporte HCI básica sobre UART (COM1)
  • Protocolo H4: Soporte para framing de paquetes Bluetooth
  • En desarrollo: Comandos HCI Core, descubrimiento de dispositivos, integración con filesystem
  • Característica experimental: Requiere adaptador Bluetooth-UART físico (HC-05, HC-06, o dongle USB-UART)

Sistema de Drivers Multilenguaje

  • Soporte nativo para drivers escritos en C, C++ y Rust
  • Registro unificado de drivers con inicialización automática
  • Soporte de cross-compilación para todos los lenguajes a targets Windows
  • Integración en tiempo de ejecución con gestión de memoria del kernel e interrupciones

Seguridad y Validación Mejoradas

  • Validación integral de paths previniendo ataques de traversal
  • Protección contra buffer overflow en código de red y filesystem
  • Gestión segura de discos con protección del sistema host
  • Mejoras de seguridad de memoria en allocator y sistemas de paginación

Sistema de Archivos Virtual Avanzado

  • Soporte para múltiples filesystems: MINIX, RAMFS, TMPFS, ProcFS, DevFS, SysFS
  • Sistema de montaje dinámico con resolución de paths cross-filesystem
  • Operaciones compatibles con POSIX con modelo completo de permisos
  • Información de procesos en tiempo real vía filesystem /proc

Networking Listo para Producción

  • Stack TCP/IP completo con Ethernet, ARP, IPv4, ICMP, UDP
  • Soporte de drivers de hardware: NICs RTL8139 e Intel e1000
  • Herramientas de configuración de red: ifconfig, ping, netinfo
  • Soporte de networking TAP para desarrollo y testing

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 UserSpace["Espacio de Usuario (Ring 3)"]
        Apps["Aplicaciones de Usuario"]
        Shell["Shell Interactivo"]
        Init["Proceso Init (PID 1)"]
    end

    subgraph SyscallLayer["Interfaz de Llamadas al Sistema"]
        Syscall["Despachador de Syscalls<br/>(INT 0x80)"]
    end

    subgraph KernelCore["Núcleo del Kernel (Ring 0)"]
        subgraph ProcessMgmt["Gestión de Procesos"]
            Proc["Ciclo de Vida<br/>(Fork/Exec/Wait)"]
            Sched["Planificador Round Robin"]
        end
        
        subgraph MemMgmt["Gestión de Memoria"]
            Paging["Paginación"]
            Kalloc["Asignador de Heap<br/>(kmalloc/kfree)"]
            PMM["Administrador de Memoria Física"]
        end
        
        subgraph VFSSystem["Sistema de Archivos Virtual"]
            VFS["Capa VFS"]
            MinixFS["Minix FS"]
            RAMFS["RAMFS"]
            ProcFS["Sistema de Archivos /proc"]
            DevFS["Sistema de Archivos /dev"]
        end
        
        subgraph Network["Pila de Red"]
            NetCore["Núcleo de Red"]
            ARP["Protocolo ARP"]
            IPv4["Protocolo IPv4"]
            RTL8139["Driver RTL8139"]
        end
        
        subgraph Drivers["Controladores de Dispositivos"]
            DriverReg["Registro de Drivers<br/>(C/C++/Rust)"]
            Storage["Almacenamiento ATA/IDE"]
            Input["Teclado/Ratón PS/2"]
            Audio["Controladores de Audio"]
            Serial["Puerto Serial"]
            Timer["Temporizadores (PIT/HPET/LAPIC)"]
        end
        
        subgraph Interrupts["Sistema de Interrupciones"]
            IDT["Configuración IDT"]
            PIC["Controlador PIC"]
            ISR["Manejadores de Interrupciones"]
        end
    end

    Apps -->|syscalls| Syscall
    Shell -->|syscalls| Syscall
    Init -->|inicia| Shell
    
    Syscall --> ProcessMgmt
    Syscall --> MemMgmt
    Syscall --> VFSSystem
    
    ProcessMgmt --> Sched
    Sched --> Interrupts
    
    VFSSystem --> MinixFS
    VFSSystem --> RAMFS
    VFSSystem --> ProcFS
    VFSSystem --> Storage
    
    Network --> NetCore
    NetCore --> ARP
    NetCore --> IPv4
    IPv4 --> RTL8139
    
    Drivers --> DriverReg
    Storage --> DriverReg
    Input --> DriverReg
    Audio --> DriverReg
    
    Interrupts --> Drivers
    Interrupts --> Timer
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 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 drivers/IO/ps2.c

Gestión de Discos Virtuales

El disco virtual se crea automáticamente durante la compilación. El sistema de gestión de discos soporta múltiples sistemas de archivos e incluye validaciones de seguridad para proteger el sistema host.

Crear Discos Virtuales:

make create-disk                    # Crear disco MINIX de 200MB (por defecto)
make create-disk fat32              # Crear disco FAT32 (500MB por defecto)
make create-disk fat32 500          # Crear disco FAT32 de 500MB
make create-disk ext4 1000          # Crear disco ext4 de 1GB
make create-disk hints              # Mostrar ayuda y opciones disponibles

El comando create-disk soporta argumentos posicionales:

  • Primer argumento: Tipo de sistema de archivos (minix, fat32, ext4, etc.)
  • Segundo argumento (opcional): Tamaño del disco en MB

Tamaños por defecto según sistema de archivos:

  • MINIX: 200MB
  • FAT32: 500MB
  • ext4: 1000MB

Eliminar Discos Virtuales:

make delete-disk                    # Eliminar disk.img (disco MINIX por defecto)
make delete-disk fat32              # Eliminar fat32.img
make delete-disk minix disk.img     # Eliminar disk.img explícitamente

El comando delete-disk acepta:

  • Sin argumentos: Elimina el archivo por defecto disk.img
  • Nombre del sistema de archivos: Elimina el archivo por defecto específico (ej: fat32.img)
  • Sistema de archivos y nombre de archivo: Elimina el archivo especificado explícitamente

Para obtener ayuda adicional sobre los comandos de gestión de discos:

make create-disk hints              # Mostrar ayuda de create-disk
make delete-disk                    # delete-disk no tiene hints, pero acepta los mismos argumentos

Gestión del Proceso Init:

El kernel IR0 soporta la carga del proceso Init (PID 1) desde el sistema de archivos del disco virtual. El binario de Init debe compilarse en un repositorio separado y colocarse en setup/pid1/init antes de cargarlo en el disco.

Cargar Init en el disco:

sudo make load-init                    # Auto-detectar filesystem, usar disk.img
sudo make load-init fat32              # Cargar Init en fat32.img
sudo make load-init fat32 fat32.img    # Especificar filesystem y disco explícitamente
sudo make load-init fat32 fat32.img /path/to/init  # Especificar todos los parámetros
make load-init hints                   # Mostrar ayuda y opciones disponibles

El comando load-init:

  • Monta el sistema de archivos del disco virtual (requiere privilegios root)
  • Crea el directorio /sbin si no existe
  • Copia el binario desde setup/pid1/init a /sbin/init en el disco
  • Soporta auto-detección del tipo de filesystem desde el nombre del archivo
  • Soporta minix, fat32 y ext4

Remover Init del disco:

sudo make remove-init                  # Auto-detectar filesystem, usar disk.img
sudo make remove-init fat32            # Remover Init de fat32.img
sudo make remove-init fat32 fat32.img  # Especificar filesystem y disco explícitamente
make remove-init hints                 # Mostrar ayuda y opciones disponibles

El comando remove-init:

  • Monta el sistema de archivos del disco virtual (requiere privilegios root)
  • Elimina /sbin/init del disco
  • Preserva el directorio /sbin para futuros usos
  • Soporta auto-detección del tipo de filesystem

Nota importante: Si el disco no está formateado, el script formateará automáticamente el filesystem antes de cargar Init. Esto elimina la necesidad de arrancar el kernel una vez antes de usar load-init.

Características de Seguridad: Tanto el script de creación como el de eliminación incluyen validación exhaustiva ejecutada antes de cualquier operación en disco. La validación previene:

  • Operaciones en dispositivos de bloque (/dev/*)
  • Operaciones en directorios del sistema (/etc, /boot, /usr, etc.)
  • Ataques de path traversal (secuencias ..)

Estas protecciones garantizan que el sistema host permanezca seguro durante las operaciones de gestión de imágenes de disco.

The virtual disk is automatically created during the build process. The disk management system supports multiple filesystems and includes security validations to protect the host system.

Creating Virtual Disks

Create a virtual disk manually:

make create-disk                    # Create 200MB MINIX disk (default)
make create-disk fat32              # Create FAT32 disk (500MB default)
make create-disk fat32 500          # Create 500MB FAT32 disk
make create-disk ext4 1000          # Create 1GB ext4 disk
make create-disk hints              # Show help and available options

The create-disk command supports positional arguments:

  • First argument: Filesystem type (minix, fat32, ext4, etc.)
  • Second argument (optional): Disk size in MB

Default filesystem sizes:

  • MINIX: 200MB
  • FAT32: 500MB
  • ext4: 1000MB

Security Features: The disk creation script includes comprehensive validation to prevent accidental operations on system devices or critical directories. All validations execute before any disk write operations.

Deleting Virtual Disks

Delete virtual disks using the same filesystem-based syntax:

make delete-disk                    # Delete disk.img (default MINIX disk)
make delete-disk fat32              # Delete fat32.img
make delete-disk minix disk.img     # Delete disk.img explicitly

The delete-disk command accepts:

  • No arguments: Deletes the default disk.img file
  • Filesystem name: Deletes the filesystem-specific default file (e.g., fat32.img)
  • Filesystem and filename: Deletes the specified file explicitly

For additional help on disk management commands:

make create-disk hints              # Show create-disk help
make delete-disk                    # delete-disk uses the same syntax as create-disk

Init Process Management

The IR0 kernel supports loading the Init process (PID 1) from the virtual disk filesystem. The Init binary must be compiled in a separate repository and placed at setup/pid1/init before loading it into the disk.

Loading Init into the disk:

sudo make load-init                    # Auto-detect filesystem, use disk.img
sudo make load-init fat32              # Load Init into fat32.img
sudo make load-init fat32 fat32.img    # Explicitly specify filesystem and disk
sudo make load-init fat32 fat32.img /path/to/init  # Specify all parameters
make load-init hints                   # Show help and available options

The load-init command:

  • Mounts the virtual disk filesystem (requires root privileges)
  • Creates the /sbin directory if it doesn't exist
  • Copies the binary from setup/pid1/init to /sbin/init on the disk
  • Supports auto-detection of filesystem type from filename
  • Supports minix, fat32, and ext4 filesystems

Removing Init from the disk:

sudo make remove-init                  # Auto-detect filesystem, use disk.img
sudo make remove-init fat32            # Remove Init from fat32.img
sudo make remove-init fat32 fat32.img  # Explicitly specify filesystem and disk
make remove-init hints                 # Show help and available options

The remove-init command:

  • Mounts the virtual disk filesystem (requires root privileges)
  • Removes /sbin/init from the disk
  • Preserves the /sbin directory for future use
  • Supports auto-detection of filesystem type

Important note: If the disk is not formatted, the script will automatically format the filesystem before loading Init. This eliminates the need to boot the kernel once before using load-init.

Both commands use the same security validations as disk creation to prevent dangerous operations.

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

  • Ciclo de vida completo de procesos: crear, ejecutar, terminar, esperar
  • Estados de proceso: READY, RUNNING, BLOCKED, ZOMBIE
  • Planificador: Round-Robin con quantum configurable
  • Cambio de contexto: Implementación optimizada en assembly x86-64
  • Jerarquía de árbol de procesos: Relaciones padre-hijo con soporte waitpid
  • Aislamiento de memoria: Separación Ring 0 (kernel) y Ring 3 (usuario)
  • Cargador ELF: Carga básica de binarios ELF para programas de usuario
  • Sistema init: Proceso PID 1 con gestión de servicios

Llamadas al Sistema

  • Interfaz de llamadas al sistema compatible con POSIX vía INT 0x80
  • Gestión de procesos: fork, exec, exit, waitpid, getpid, getppid, spawn
  • Operaciones de archivo: open, close, read, write, lseek, dup2, creat
  • Operaciones de directorio: mkdir, rmdir, chdir, getcwd, unlink, link
  • Sistema de archivos: stat, fstat, mount, chmod, touch, append
  • Gestión de memoria: brk, sbrk, mmap, munmap, mprotect
  • Información del sistema: ps, df, lsblk, whoami, ls
  • Redes: ping, ifconfig (configuración IPv4)

Sistema de Archivos Virtual

  • Capa de abstracción VFS
  • Soporte para sistemas de archivos MINIX, RAMFS, TMPFS
  • Gestión de puntos de montaje
  • Filesystems virtuales: /proc, /dev, RAMFS, TMPFS
  • Ver VIRTUAL_FILESYSTEMS.md para documentación detallada

Controladores de Hardware

  • Entrada/Salida: Controladores de teclado y ratón PS/2, controlador de altavoz PC
  • Almacenamiento: Controlador de disco ATA/IDE con soporte DMA, gestión de particiones
  • Red: Controladores Ethernet RTL8139 e Intel e1000
  • Audio: Controlador Sound Blaster 16, controlador Adlib OPL2
  • Video: Controlador de modo texto VGA, controlador gráfico VBE
  • Temporizadores: PIT (Programmable Interval Timer), HPET (High Precision Event Timer), LAPIC (Local APIC Timer), RTC (Real Time Clock)
  • Serial: Controlador de puerto serie COM1/COM2 para depuración
  • DMA: Soporte para controlador DMA de 8 canales
  • Registro de Controladores: Sistema unificado de registro de controladores con soporte para C, C++ y Rust

Redes

  • Stack TCP/IP completo: Ethernet, ARP, IPv4, ICMP, UDP
  • Controladores hardware: RTL8139 e Intel e1000
  • Herramientas: ping, ifconfig, netinfo
  • Soporte TAP: Networking avanzado para desarrollo

Bluetooth Experimental

  • HCI Transport: Capa de transporte HCI sobre UART (COM1)
  • Protocolo H4: Framing de paquetes Bluetooth
  • Estado: Fase 1 completada (transporte básico)
  • Requisitos: Adaptador Bluetooth-UART (HC-05, HC-06, o USB-UART)
  • Próximas fases: HCI Core, descubrimiento de dispositivos, integración con /dev y /proc

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 completa (33+ comandos)
  • Operaciones de archivo: ls, cat, cp, mv, mkdir, rmdir, rm, cd, pwd, touch, chmod, chown, ln
  • Información del sistema: ps, df, lsblk, whoami, netinfo, arpcache
  • Gestión de procesos: exec
  • Redes: ping, ifconfig
  • Procesamiento de texto: echo, sed
  • Gestión de controladores: lsdrv, dmesg
  • Pruebas de hardware: audio_test, mouse_test
  • Utilidades del sistema: clear, help, exit, type, mount

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.