]> Projects (at) Tadryanom (dot) Me - AdrOS.git/log
AdrOS.git
7 weeks agofeat: PAE paging + NX bit support
Tulio A M Mendes [Wed, 11 Feb 2026 23:21:00 +0000 (20:21 -0300)]
feat: PAE paging + NX bit support

- src/arch/x86/boot.S: complete rewrite for PAE 3-level page tables
  PDPT (4 entries) + 4 PDs (512 entries each) + 8 PTs covering 16MB
  CR4.PAE enabled before paging, recursive mapping via PD[3][508-511]
- src/arch/x86/vmm.c: complete rewrite for 64-bit PAE entries
  New recursive mapping accessors (PD at 0xFFFFC000, PT at 0xFF800000)
  NX bit support (bit 63), VMM_FLAG_NX added
  All address space ops updated: create, clone, destroy, CoW, fault handler
- src/arch/x86/ap_trampoline.S: enable CR4.PAE before paging for APs
- src/arch/x86/elf.c: updated page table check to PAE 64-bit entries
- src/arch/x86/uaccess.c: updated page present/writable checks for PAE
- include/vmm.h: added VMM_FLAG_NX define
- cppcheck clean, 19/19 smoke tests pass

7 weeks agofeat: per-process errno + set_thread_area syscall stub for future TLS
Tulio A M Mendes [Wed, 11 Feb 2026 22:57:23 +0000 (19:57 -0300)]
feat: per-process errno + set_thread_area syscall stub for future TLS

- user/errno.c: documented per-process errno isolation via fork
- include/syscall.h: added SYSCALL_SET_THREAD_AREA(57) for future TLS
- src/kernel/syscall.c: set_thread_area dispatch stub (-ENOSYS)
- True TLS deferred until clone/threads (task #14) is implemented
- cppcheck clean, 19/19 smoke tests pass

7 weeks agofeat: symbolic links (symlink, readlink) and link stub
Tulio A M Mendes [Wed, 11 Feb 2026 22:53:00 +0000 (19:53 -0300)]
feat: symbolic links (symlink, readlink) and link stub

- include/fs.h: added FS_SYMLINK type and symlink_target[128] field to fs_node_t
- include/stat.h: added S_IFLNK define
- include/syscall.h: added SYSCALL_LINK(54), SYSCALL_SYMLINK(55), SYSCALL_READLINK(56)
- src/kernel/fs.c: vfs_lookup follows symlinks with depth limit (max 8)
- src/kernel/tmpfs.c: tmpfs_create_symlink creates FS_SYMLINK nodes
- src/kernel/syscall.c: symlink_impl, readlink_impl, link_impl (stub -ENOSYS)
  stat_from_node reports S_IFLNK for symlink nodes
- cppcheck clean, 19/19 smoke tests pass

7 weeks agofeat: permissions support (uid/gid/mode, chmod, chown, getuid, getgid)
Tulio A M Mendes [Wed, 11 Feb 2026 22:46:34 +0000 (19:46 -0300)]
feat: permissions support (uid/gid/mode, chmod, chown, getuid, getgid)

- include/fs.h: added uid, gid, mode fields to fs_node_t
- include/process.h: added uid, gid fields to struct process
- include/stat.h: added st_uid, st_gid to struct stat, permission bit defines
- include/syscall.h: added SYSCALL_CHMOD(50), SYSCALL_CHOWN(51), SYSCALL_GETUID(52), SYSCALL_GETGID(53)
- src/kernel/syscall.c: chmod_impl, chown_impl, getuid/getgid dispatch; stat_from_node now populates uid/gid/mode
- user/init.c: updated struct stat to match kernel layout
- cppcheck clean, 19/19 smoke tests pass

7 weeks agofeat: /proc per-process directories (/proc/[pid]/status, maps)
Tulio A M Mendes [Wed, 11 Feb 2026 22:39:04 +0000 (19:39 -0300)]
feat: /proc per-process directories (/proc/[pid]/status, maps)

- /proc/[pid]/status: shows Pid, PPid, Pgrp, Session, State, signals, heap
- /proc/[pid]/maps: shows heap range and mmap regions
- /proc root readdir now lists numeric PID entries alongside self/uptime/meminfo
- /proc root finddir resolves numeric names to per-PID directory nodes
- Uses small static pool of fs_node_t (8 slots) for dynamic PID nodes
- proc_find_pid helper iterates ready queue to find process by PID
- cppcheck clean, 19/19 smoke tests pass

7 weeks agorefactor: generic wait queue abstraction (waitqueue.h)
Tulio A M Mendes [Wed, 11 Feb 2026 22:32:55 +0000 (19:32 -0300)]
refactor: generic wait queue abstraction (waitqueue.h)

- include/waitqueue.h: reusable waitqueue_t with wq_init/push/pop/wake_one/wake_all
- src/kernel/tty.c: refactored to use waitqueue_t instead of ad-hoc arrays
- src/kernel/pty.c: refactored to use waitqueue_t instead of ad-hoc arrays
- Removed duplicate waitq_push/waitq_pop/waitq_empty/waitq_wake_one from both files
- cppcheck clean, 19/19 smoke tests pass

7 weeks agofeat: core utilities (cat, ls, mkdir, rm)
Tulio A M Mendes [Wed, 11 Feb 2026 22:27:23 +0000 (19:27 -0300)]
feat: core utilities (cat, ls, mkdir, rm)

- user/cat.c: reads files or stdin, outputs to stdout
- user/ls.c: lists directory entries via getdents syscall
- user/mkdir.c: creates directories via mkdir syscall
- user/rm.c: removes files (unlink) or directories (-r/-d rmdir)
- Makefile: build rules for all four + initrd packaging as /bin/*
- echo already exists as shell builtin
- cppcheck clean, 19/19 smoke tests pass

7 weeks agofeat: add minimal POSIX sh shell (/bin/sh)
Tulio A M Mendes [Wed, 11 Feb 2026 22:22:37 +0000 (19:22 -0300)]
feat: add minimal POSIX sh shell (/bin/sh)

- user/sh.c: minimal sh-compatible shell with:
  - Line reading from stdin
  - Argument parsing (whitespace-delimited)
  - PATH resolution (/bin/, /disk/bin/)
  - Input/output redirection (< and >)
  - Pipeline support (up to 4 stages with |)
  - Builtins: exit, echo
  - External commands via fork+execve+waitpid
- Makefile: added SH_ELF build rule and initrd packaging as /bin/sh
- cppcheck clean, 19/19 smoke tests pass

7 weeks agofeat: VMIN/VTIME termios fields for non-canonical TTY reads
Tulio A M Mendes [Tue, 10 Feb 2026 13:23:13 +0000 (10:23 -0300)]
feat: VMIN/VTIME termios fields for non-canonical TTY reads

- Added c_cc[NCCS] array to struct termios with VMIN/VTIME indices
- TCGETS/TCSETS now get/set c_cc values
- tty_read_kbuf implements full POSIX non-canonical semantics:
  VMIN=0,VTIME=0: poll (return immediately)
  VMIN>0,VTIME=0: block until VMIN chars available
  VMIN=0,VTIME>0: timeout read (tenths of second)
  VMIN>0,VTIME>0: block with inter-char timeout
- tty_read refactored to delegate to tty_read_kbuf (no duplication)
- Default: VMIN=1, VTIME=0 (standard blocking single-char read)
- cppcheck clean, 19/19 smoke tests pass

7 weeks agofeat: multiple PTY pairs (up to 8 dynamic /dev/pts/N)
Tulio A M Mendes [Tue, 10 Feb 2026 12:55:26 +0000 (09:55 -0300)]
feat: multiple PTY pairs (up to 8 dynamic /dev/pts/N)

Refactored PTY subsystem from single global pair to array of up to 8 pairs:
- New pty_pair struct with per-pair buffers, waitqueues, session/pgrp
- pty_alloc_pair() allocates new pairs dynamically
- Inode encoding: masters=100+N, slaves=200+N
- pty_get_master_node()/pty_get_slave_node() return per-pair fs_node_t
- All _idx() variants for indexed pair access
- Old single-pair API preserved as wrappers around pair 0
- devfs /dev/pts/ now lists all active pairs dynamically
- syscall.c poll/nonblock/ioctl updated to use pty_is_master_ino/pty_is_slave_ino
- cppcheck clean, 19/19 smoke tests pass

7 weeks agofeat: add /dev/zero, /dev/random, /dev/urandom, /dev/console device nodes
Tulio A M Mendes [Tue, 10 Feb 2026 12:31:13 +0000 (09:31 -0300)]
feat: add /dev/zero, /dev/random, /dev/urandom, /dev/console device nodes

- /dev/zero: returns zeroes on read, discards writes
- /dev/random: xorshift32 PRNG seeded from PIT tick counter
- /dev/urandom: alias to /dev/random (same PRNG)
- /dev/console: aliases to TTY read/write (like /dev/tty)
- All registered in devfs finddir + readdir (8 devices total)
- cppcheck clean, 19/19 smoke tests pass

7 weeks agodocs: comprehensive documentation update reflecting current AdrOS state
Tulio A M Mendes [Tue, 10 Feb 2026 12:11:52 +0000 (09:11 -0300)]
docs: comprehensive documentation update reflecting current AdrOS state

Updated all 4 documentation files to accurately reflect the current codebase:

POSIX_ROADMAP.md:
- fork now marked as CoW (was 'full copy')
- execve marked complete (was partial)
- brk/sbrk, nanosleep, clock_gettime marked implemented
- O_CLOEXEC, FD_CLOEXEC marked implemented
- Signal defaults marked complete (Ctrl+C/Z/D/\)
- Raw TTY mode, TIOCGWINSZ marked implemented
- PMM now shows spinlock + refcount
- Slab allocator, CoW, shared memory, SMEP marked implemented
- Heap shows dynamic growth to 64MB
- PCI, ATA DMA, LAPIC/IOAPIC, SMP, ACPI, VBE, SYSENTER, CPUID added
- ulibc marked implemented
- procfs partial noted
- Priority roadmap updated: 9 items marked done, remaining reordered

SUPPLEMENTARY_ANALYSIS.md:
- POSIX score updated from ~45% to ~70%
- PMM: spinlock + refcount now implemented
- VMM: CoW + SMEP now implemented
- Heap: slab allocator + dynamic growth now implemented
- Scheduler: O(1) with bitmap now implemented
- TTY: raw mode, signal chars, TIOCGWINSZ now implemented
- Userland: ulibc + SYSENTER now implemented
- Drivers: PCI, ATA DMA, LAPIC/IOAPIC, SMP, ACPI, VBE now implemented
- Advanced: CoW, slab, shmem now implemented
- Part 3 comparison table updated (AdrOS ahead in 5/10 dimensions)
- Part 4 recommendations: 9 items marked completed, remaining reordered

README.md:
- Complete rewrite of Features section with organized subsections
- Added: Memory Management, Process & Scheduling, Syscalls, TTY/PTY,
  Filesystems (6 types), Drivers & Hardware, Userland, Security, Testing
- Updated TODO with near-term/medium-term/long-term priorities
- Updated Directory Structure with new paths

BUILD_GUIDE.md:
- Added expect and sparse to dependencies
- Added Testing section with all make targets
- Increased smoke test timeout from 40s to 60s

7 weeks agodocs: update audit report with fix status for all CRITICAL and HIGH findings
Tulio A M Mendes [Tue, 10 Feb 2026 11:45:57 +0000 (08:45 -0300)]
docs: update audit report with fix status for all CRITICAL and HIGH findings

7 weeks agotest: expand test suite with security unit tests and GDB scripted checks
Tulio A M Mendes [Tue, 10 Feb 2026 11:44:55 +0000 (08:44 -0300)]
test: expand test suite with security unit tests and GDB scripted checks

New test_security.c (19 tests):
- user_range_ok: 11 tests covering NULL, zero-len, valid user addr,
  kernel addr rejection, boundary spanning, overflow, max user range
- bitmap: 4 tests for set/unset/cross-byte/all-bits operations
- eflags sanitization: 4 tests verifying IOPL clearing and IF forcing

New gdb_checks.py:
- Automated GDB script for QEMU+GDB integrity checks
- Verifies heap magic, PMM bitmap frame 0, max_frames, VGA mapping
- Usage: make test-gdb

Updated Makefile:
- test-host now runs both test_utils (28) and test_security (19) = 47 tests
- Added test-gdb target for GDB scripted checks
- Total: 47 host unit tests + 19 smoke checks = 66 automated tests

7 weeks agofix: 5 HIGH severity bugs from audit
Tulio A M Mendes [Tue, 10 Feb 2026 11:38:03 +0000 (08:38 -0300)]
fix: 5 HIGH severity bugs from audit

2.3: Slab allocator now uses kmalloc(PAGE_SIZE) instead of
     pmm_alloc_page + hal_mm_phys_to_virt. The old approach could
     map physical addresses above 16MB to VAs that collide with the
     heap range (0xD0000000+), causing silent memory corruption.

3.3: execve now validates sp against stack base before each write.
     Prevents writing below the user stack page if E2BIG pre-check
     is somehow bypassed. Returns -E2BIG on underflow.

3.4: SMEP (Supervisor Mode Execution Prevention) enabled in CR4
     if CPU supports it. Prevents kernel from executing user-mapped
     pages, blocking a common exploit technique. SMAP detection added
     but not enabled yet (requires STAC/CLAC in uaccess.c first).
     CPUID leaf 7 detection added for SMEP (bit 7) and SMAP (bit 20).

4.1: Kernel heap now grows dynamically from 10MB up to 64MB max.
     When kmalloc can't find a free block, kheap_grow maps new
     physical pages at the end of the heap and creates a new free
     block. Coalesces with tail if adjacent and free.

2.4: process_waitpid circular list traversal now checks for NULL
     before comparing to start, preventing NULL deref if the list
     is broken by concurrent reaping.

7 weeks agofix: 4 CRITICAL security/race bugs from audit
Tulio A M Mendes [Tue, 10 Feb 2026 11:29:36 +0000 (08:29 -0300)]
fix: 4 CRITICAL security/race bugs from audit

3.1: user_range_ok weak default now rejects kernel addresses (>= 0xC0000000)
     Prevents privilege escalation via syscall arguments on non-x86 fallback.

3.2: sigreturn sanitizes eflags — clears IOPL bits, ensures IF set.
     Prevents userspace from gaining port I/O access via crafted sigframe.

2.1: PMM bitmap/refcount now protected by spinlock_t pmm_lock.
     Prevents SMP race where two CPUs could allocate the same physical frame.
     All public PMM functions (alloc, free, mark_region, incref, decref,
     get_refcount) now use spin_lock_irqsave/spin_unlock_irqrestore.

2.2: file->refcount now uses __sync_fetch_and_add / __sync_sub_and_fetch.
     Prevents use-after-free in fork/dup/dup2/dup3/close when timer IRQ
     fires and schedule() runs process_close_all_files_locked concurrently.

7 weeks agofeat: deep code audit + testing infrastructure (sparse, expect, host unit tests)
Tulio A M Mendes [Tue, 10 Feb 2026 11:07:09 +0000 (08:07 -0300)]
feat: deep code audit + testing infrastructure (sparse, expect, host unit tests)

Deep Code Audit (docs/AUDIT_REPORT.md):
- 18 findings across 4 categories: layer violations, logic/race
  conditions, security vulnerabilities, memory management
- CRITICAL: user_range_ok weak default allows kernel addr access
- CRITICAL: sigreturn allows IOPL escalation via eflags
- CRITICAL: PMM bitmap has no locking (SMP race)
- CRITICAL: file refcount manipulation not atomic
- HIGH: slab allocator hal_mm_phys_to_virt can hit heap VA
- HIGH: execve writes to user stack bypassing copy_to_user
- Full summary table with severity, category, location

Testing Infrastructure:
- make check    — cppcheck + sparse (kernel-oriented semantic checker)
- make analyzer — gcc -fanalyzer (interprocedural analysis)
- make test     — QEMU + expect automated smoke test (19 checks)
- make test-1cpu — single-CPU regression (50s timeout)
- make test-host — 28 host-side unit tests for pure functions
                   (itoa, itoa_hex, atoi, path_normalize, align)
- make test-all — all of the above

Testing Plan (docs/TESTING_PLAN.md):
- Layer 1: Static analysis (cppcheck + sparse + gcc -fanalyzer)
- Layer 2: QEMU + expect automated regression
- Layer 3: QEMU + GDB scripted debugging (future)
- Layer 4: Host-side unit tests for pure functions

All tests passing: 19/19 smoke, 28/28 unit, cppcheck clean.

7 weeks agofeat: Fase 9 — ATA Bus Master IDE DMA for read/write
Tulio A M Mendes [Tue, 10 Feb 2026 10:37:38 +0000 (07:37 -0300)]
feat: Fase 9 — ATA Bus Master IDE DMA for read/write

Implement Bus Master IDE DMA as a transparent upgrade over PIO:

- New ata_dma.c: Bus Master IDE DMA driver for PIIX3 IDE controller
  - Finds IDE controller via PCI class 0x01:0x01
  - Reads BAR4 for Bus Master I/O base, enables PCI bus mastering
  - Allocates PRDT and bounce buffer pages at dedicated VAs
    (0xC0220000/0xC0221000) to avoid heap VA collisions
  - Polling-based DMA completion (BSY clear + BM Active clear)
  - IRQ 14 handler with dma_active flag to prevent race between
    IRQ handler and polling loop on ATA status register
  - spin_lock (not irqsave) for serialization — PIIX3 requires
    interrupt delivery for DMA completion signaling

- Modified ata_pio.c: transparent DMA upgrade
  - ata_pio_init_primary_master registers IRQ 14 handler early
    (before IDENTIFY) to prevent INTRQ storm
  - Calls ata_dma_init after IDENTIFY to probe for DMA capability
  - ata_pio_read28/write28 delegate to DMA when available,
    fall back to PIO if DMA init failed

- New include/ata_dma.h: public API header

Key bugs fixed during development:
- hal_mm_phys_to_virt can map PMM pages into heap VA range
  (phys 0x10000000 -> virt 0xD0000000 = heap base) — use
  dedicated VAs instead
- ATA INTRQ must be deasserted by reading status register;
  without IRQ handler, unacknowledged INTRQ causes interrupt storm
- nIEN must be cleared before DMA so device asserts INTRQ
- DMA direction bit must be set before Start bit per ATA spec

Tested: 4-CPU (25s) and 1-CPU (45s) pass all init.elf tests
including diskfs getdents and /persist/counter.

7 weeks agofeat: Fase 8a — Per-CPU data infrastructure with GS-segment access
Tulio A M Mendes [Tue, 10 Feb 2026 09:26:46 +0000 (06:26 -0300)]
feat: Fase 8a — Per-CPU data infrastructure with GS-segment access

New files:
- include/arch/x86/percpu.h — Per-CPU data structure and GS-based
  accessors (percpu_get, percpu_cpu_index, percpu_current, etc.)
- src/arch/x86/percpu.c — Per-CPU init: creates GDT entries for each
  CPU's GS segment pointing to its percpu_data instance

Changes:
- include/arch/x86/smp.h: Split smp_init into smp_enumerate() and
  smp_start_aps() to allow percpu_init between enumeration and SIPI
- src/arch/x86/smp.c: Implement two-phase SMP init
- include/arch/x86/gdt.h: Export gdt_ptr struct, gp variable, and
  gdt_set_gate_ext() for per-CPU GDT entry creation
- src/arch/x86/gdt.c: Expand GDT from 6 to 24 entries (6 base +
  up to 16 per-CPU GS segments). Add gdt_set_gate_ext(). Make gp
  non-static.
- src/arch/x86/arch_platform.c: Call smp_enumerate() -> percpu_init()
  -> percpu_setup_gs(0) -> smp_start_aps() in correct order

Boot sequence for per-CPU setup:
1. smp_enumerate() — populate cpu_info from ACPI MADT
2. percpu_init() — create GDT entries for each CPU's GS segment
3. percpu_setup_gs(0) — BSP loads its own GS selector
4. smp_start_aps() — send INIT-SIPI-SIPI; each AP calls
   percpu_setup_gs(i) during its init

Passes: make, cppcheck, QEMU smoke test (-smp 1 and -smp 4)

7 weeks agofeat: Fase 7 — ACPI MADT parser + SMP AP bootstrap (INIT-SIPI-SIPI)
Tulio A M Mendes [Tue, 10 Feb 2026 09:16:11 +0000 (06:16 -0300)]
feat: Fase 7 — ACPI MADT parser + SMP AP bootstrap (INIT-SIPI-SIPI)

New files:
- include/arch/x86/acpi.h — ACPI RSDP/RSDT/MADT structures and API
- include/arch/x86/smp.h — SMP per-CPU info and bootstrap API
- src/arch/x86/acpi.c — ACPI table parser: find RSDP in EBDA/BIOS ROM,
  parse RSDT, extract MADT entries (LAPIC, IOAPIC, ISO). Uses temporary
  VMM mappings for tables above the 16MB identity-mapped range.
- src/arch/x86/smp.c — SMP bootstrap: copy 16-bit trampoline to 0x8000,
  patch GDT/CR3/stack/entry, send INIT-SIPI-SIPI per AP, wait for ready.
- src/arch/x86/ap_trampoline.S — 16-bit real-mode AP entry point:
  load GDT, enable protected mode, far-jump to 32-bit, load CR3,
  enable paging, jump to C ap_entry().

Changes:
- include/arch/x86/lapic.h: Add lapic_send_ipi(), rdmsr(), wrmsr() decls
- src/arch/x86/lapic.c: Implement lapic_send_ipi() using ICR_HI/ICR_LO
  with delivery-status polling. Make rdmsr/wrmsr non-static.
- include/arch/x86/gdt.h: Export struct gdt_ptr and gp variable
- src/arch/x86/gdt.c: Make gp non-static for AP trampoline access
- src/arch/x86/linker.ld: Include .ap_trampoline section in .rodata
- src/arch/x86/arch_platform.c: Call acpi_init() then smp_init() after
  LAPIC/IOAPIC setup
- src/arch/x86/idt.c: Move IRQ EOI before handler callback (critical fix:
  schedule() in timer handler context-switches away, blocking LAPIC if
  EOI is deferred). Add IDT gate + ISR stub for spurious vector 255.
- src/arch/x86/interrupts.S: Add ISR_NOERRCODE 255 stub

Key design decisions:
- Trampoline at fixed phys 0x8000, data area at 0x8F00
- APs share BSP's page directory (same CR3)
- APs enable their own LAPIC and halt (idle loop for now)
- ACPI tables mapped via temporary VMM window at 0xC0202000
- Each AP gets a 4KB kernel stack from static array

Tested: -smp 1 (single CPU, all init tests OK)
        -smp 4 (4 CPUs started, all init tests OK)
Passes: make, cppcheck, QEMU smoke test

7 weeks agofeat: Fase 6 — LAPIC + IOAPIC drivers, replace legacy PIC 8259
Tulio A M Mendes [Tue, 10 Feb 2026 08:40:28 +0000 (05:40 -0300)]
feat: Fase 6 — LAPIC + IOAPIC drivers, replace legacy PIC 8259

New files:
- include/arch/x86/lapic.h — LAPIC register definitions and API
- include/arch/x86/ioapic.h — IOAPIC register definitions and API
- src/arch/x86/lapic.c — Local APIC driver: init, EOI, MMIO access,
  timer calibration via PIT channel 2, pic_disable()
- src/arch/x86/ioapic.c — I/O APIC driver: init, IRQ routing,
  mask/unmask per-IRQ line

Changes:
- vmm.h: Add VMM_FLAG_PWT, VMM_FLAG_PCD, VMM_FLAG_NOCACHE for MMIO
- vmm.c: Translate PWT/PCD flags to x86 PTE bits in vmm_flags_to_x86
- arch_platform.c: Init LAPIC+IOAPIC after syscall_init, route ISA
  IRQs (timer=32, kbd=33, ATA=46) through IOAPIC, disable PIC only
  after IOAPIC routes are live
- idt.c: Send EOI BEFORE handler callback (critical: schedule() in
  timer handler context-switches away; deferred EOI blocks LAPIC).
  Add IDT gate for spurious vector 255; skip EOI for spurious
  interrupts per Intel spec.
- interrupts.S: Add ISR stub for vector 255 (LAPIC spurious)
- timer.c: Use LAPIC periodic timer when available, fallback to PIT

Key design decisions:
- LAPIC MMIO mapped at 0xC0200000 (above kernel _end, below heap)
- IOAPIC MMIO mapped at 0xC0201000
- Both mapped with PCD+PWT (cache-disable) to prevent MMIO caching
- PIC disabled only AFTER IOAPIC routes configured (avoids IRQ gap)
- EOI sent before handler to prevent LAPIC starvation on context switch
- Spurious vector 255 has IDT entry but no EOI (Intel requirement)
- LAPIC timer calibrated against PIT channel 2 (~10ms measurement)

Bugs fixed during development:
- VA 0xC0100000 overlapped kernel text — moved to 0xC0200000
- pic_disable() inside lapic_init() caused IRQ gap — moved to caller
- EOI after handler blocked LAPIC when schedule() context-switched
- Missing IDT entry for vector 255 caused triple fault on spurious IRQ

Passes: make, cppcheck, QEMU smoke test (all init tests OK).

7 weeks agofix: audit and correct bugs in Fases 1-4
Tulio A M Mendes [Tue, 10 Feb 2026 08:13:16 +0000 (05:13 -0300)]
fix: audit and correct bugs in Fases 1-4

Fase 1 (CPUID):
- cpuid.c: Replace strict-aliasing-violating uint32_t* casts for
  vendor string with memcpy() to avoid UB
- cpuid.c: Increase itoa tmp buffer from 4 to 12 bytes to prevent
  potential overflow with larger APIC IDs

Fase 2 (Spinlock): No bugs found — TTAS + cpu_relax + barriers OK

Fase 3 (SYSENTER):
- sysenter.S: Add 'cld' at entry to clear direction flag. Userspace
  could leave DF=1 and SYSENTER doesn't reset EFLAGS, which would
  corrupt any kernel string/memory operations using rep movsb/stosb

Fase 4 (ulibc):
- stdio.c: Fix PUTC macro underflow — use 'pos+1 < size' instead
  of 'pos < size-1' which underflows to SIZE_MAX when size==0
- stdio.c: Fix vsnprintf(buf, 0, fmt) — was counting raw format
  chars instead of returning 0; now returns 0 immediately
- stdlib.c: Use uintptr_t instead of unsigned int for brk() pointer
  comparison to be correct on all architectures
- unistd.c: Replace 'hlt' with 'nop' in _exit() fallback loop —
  hlt is privileged and causes #GP in ring 3

Passes: make, ulibc build, cppcheck, QEMU smoke test.

7 weeks agofix: correct 5 bugs in shared memory IPC (Fase 5 audit)
Tulio A M Mendes [Tue, 10 Feb 2026 08:04:52 +0000 (05:04 -0300)]
fix: correct 5 bugs in shared memory IPC (Fase 5 audit)

Bugs found and fixed during deep audit of the Fase 5 commit
(implemented during WSL2/GCC instability):

BUG 1 (CRITICAL): vmm_map_page args were inverted in shm_at().
  Signature is vmm_map_page(phys, virt, flags) but code passed
  (virt, phys, flags). Would map physical pages at wrong addresses
  causing memory corruption. Fixed both code paths.

BUG 2 (CRITICAL): shm_dt() used broken heuristic to find segment.
  Matched by npages count — if two segments had same page count,
  wrong one got decremented. Added shmid field to mmap entry struct
  for direct O(1) lookup. Removed dead code loop that computed
  expected_va and discarded it.

BUG 3: shm_at() with shmaddr!=0 didn't register in mmaps[].
  shm_dt() would never find the slot, returning -EINVAL.
  Now always registers in mmap table regardless of shmaddr.

BUG 4: shm_destroy() only cleared 'used' flag, leaving stale
  key/size/npages/nattch. Now memset()s entire struct to zero.

BUG 5: shm_ctl(IPC_STAT) wrote directly to userspace pointer
  while holding spinlock. Page fault under spinlock = deadlock.
  Now copies to local struct, releases lock, then copy_to_user().

Additional fixes:
- Added shmid field to process mmap entry (process.h)
- Initialize mmaps[].shmid = -1 in all 3 process creation paths
  (process_init, process_create_kernel, process_fork_create)
- Set shmid = -1 in syscall_mmap_impl and syscall_munmap_impl
- Fork now copies parent's mmap table to child (with shmid)

Passes: make, cppcheck, QEMU smoke test (all init tests OK).

7 weeks agofeat: implement shared memory IPC (shmget/shmat/shmdt/shmctl)
Tulio A M Mendes [Tue, 10 Feb 2026 07:39:00 +0000 (04:39 -0300)]
feat: implement shared memory IPC (shmget/shmat/shmdt/shmctl)

Add System V-style shared memory IPC subsystem:
- src/kernel/shm.c: kernel-side segment manager with up to 32
  segments, each up to 16 pages (64KB). Physical pages allocated
  via PMM, mapped into user address space via VMM.
- include/shm.h: API + constants (IPC_CREAT, IPC_EXCL, IPC_RMID,
  IPC_PRIVATE)
- Syscalls 46-49: SHMGET, SHMAT, SHMDT, SHMCTL wired in syscall.c
- shm_init() called from kernel_main after kheap_init
- Deferred destruction: IPC_RMID with nattch>0 defers free until
  last detach

Also fixes:
- tty.c: add utils.h include for memset (cross-compiler strictness)
- usermode.c: fix ebp clobber error with cross-compiler by using
  ESI as scratch register instead

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofeat: add ulibc — minimal userspace C library
Tulio A M Mendes [Tue, 10 Feb 2026 07:19:46 +0000 (04:19 -0300)]
feat: add ulibc — minimal userspace C library

Create user/ulibc/ with headers and implementations for:
- crt0.S: _start entry point that calls main() then exit()
- syscall.h: raw INT 0x80 wrappers (_syscall0..5)
- unistd.c/h: POSIX wrappers (read, write, open, close, fork,
  execve, pipe, dup2, brk, getpid, chdir, mkdir, etc)
- string.c/h: memcpy, memset, memmove, strlen, strcmp, strcpy,
  strchr, strcat, etc
- stdlib.c/h: malloc/free (bump allocator via brk), calloc,
  realloc, atoi, exit
- stdio.c/h: printf, puts, putchar, snprintf, vsnprintf with
  format specifiers: %d %i %u %x %X %s %c %p %%
- errno.c/h: errno variable + error codes + __syscall_ret helper

Build system: user/ulibc/Makefile produces libulibc.a static lib.
Main Makefile updated with ULIBC_LIB target.

Future user programs can link against libulibc.a instead of
duplicating syscall wrappers inline.

Passes: make (kernel), ulibc builds clean, QEMU smoke test OK.

7 weeks agofeat: implement SYSENTER/SYSEXIT fast syscall entry for x86-32
Tulio A M Mendes [Tue, 10 Feb 2026 07:07:14 +0000 (04:07 -0300)]
feat: implement SYSENTER/SYSEXIT fast syscall entry for x86-32

Add fast syscall support via SYSENTER/SYSEXIT (SEP), ~10x faster
than INT 0x80 (~30 cycles vs ~300 cycles overhead).

Components:
- src/arch/x86/sysenter.S: assembly entry point that builds a
  struct registers frame compatible with existing syscall_handler()
- src/arch/x86/sysenter_init.c: MSR setup (0x174=CS, 0x175=ESP,
  0x176=EIP), CPUID check for SEP support
- syscall_handler() made non-static so assembly can call it
- tss_set_kernel_stack() now also updates SYSENTER ESP MSR so
  context switches keep the fast path working

Userspace convention:
  push ecx; push edx; push $return; mov esp,ecx; sysenter
  EAX=syscall_no, EBX=arg1, ECX=arg2, EDX=arg3, ESI=arg4, EDI=arg5

INT 0x80 remains as fallback for CPUs without SEP.
QEMU confirms: [SYSENTER] Fast syscall enabled.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofeat: improve spinlock with per-arch cpu_relax() and memory barriers
Tulio A M Mendes [Tue, 10 Feb 2026 06:57:43 +0000 (03:57 -0300)]
feat: improve spinlock with per-arch cpu_relax() and memory barriers

Spinlock improvements for SMP readiness:
- Add cpu_relax() with per-arch spin-wait hints:
  x86: PAUSE, ARM/AArch64: YIELD, RISC-V: FENCE, MIPS: PAUSE
- Add __sync_synchronize() barrier before lock release in spin_unlock
- Add spin_is_locked() debug helper
- Add spin_trylock() for non-blocking lock attempts
- TTAS (test-and-test-and-set) pattern with cpu_relax() in inner loop
- __sync_lock_test_and_set maps to XCHG (x86), LDREX/STREX (ARM),
  AMOSWAP.W.AQ (RISC-V), LL/SC (MIPS)

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofeat: implement CPUID feature detection + HAL wrapper
Tulio A M Mendes [Tue, 10 Feb 2026 06:53:50 +0000 (03:53 -0300)]
feat: implement CPUID feature detection + HAL wrapper

Add x86 CPUID detection (src/arch/x86/cpuid.c) that queries:
- Leaf 0: vendor string, max leaf
- Leaf 1: feature flags (PAE, NX, APIC, SEP, SSE, SSE2, HTT, etc)
- Leaf 1 EBX: topology (APIC ID, logical CPUs)
- Extended leaves: NX, Long Mode, SYSCALL, brand string

HAL wrapper (include/hal/cpu_features.h):
- hal_cpu_detect_features() / hal_cpu_get_features() / hal_cpu_print_features()
- x86 impl in src/hal/x86/cpu_features.c
- Weak default stub in src/kernel/cpu_features.c

Called from kernel_main() right after console_init().
QEMU output: GenuineIntel, PAE APIC SEP SSE SSE2 FXSR HYPERVISOR.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: remove dead shell.c, integrate commands into kconsole
Tulio A M Mendes [Tue, 10 Feb 2026 06:27:16 +0000 (03:27 -0300)]
refactor: remove dead shell.c, integrate commands into kconsole

shell.c became dead code after kconsole_enter() replaced shell_init()
as the fallback when init_start() fails. Nobody called shell_init().

- Integrate useful shell commands into kconsole: ls, cat, clear,
  mem, sleep, ring3 (via arch_platform_usermode_test_start)
- Remove src/kernel/shell.c and include/shell.h
- Remove shell.h include from main.c
- kconsole is now the single kernel-mode interactive console

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: move x86 uaccess page table walking to src/arch/x86/uaccess.c
Tulio A M Mendes [Tue, 10 Feb 2026 06:19:36 +0000 (03:19 -0300)]
refactor: move x86 uaccess page table walking to src/arch/x86/uaccess.c

The uaccess implementation used x86-specific recursive page table
mapping (0xFFFFF000/0xFFC00000) for user_range_ok, copy_from_user,
copy_to_user, and uaccess_try_recover. This is 100% arch-dependent.

- Move full x86 implementation to src/arch/x86/uaccess.c (no guards)
- Replace src/kernel/uaccess.c with weak stubs (simple memcpy-based)
- The linker picks the arch-specific version when available

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: make pmm.c fully architecture-independent
Tulio A M Mendes [Tue, 10 Feb 2026 06:13:16 +0000 (03:13 -0300)]
refactor: make pmm.c fully architecture-independent

Extract all Multiboot2 x86-specific code from src/mm/pmm.c into
src/arch/x86/pmm_boot.c as pmm_arch_init().

Design:
- pmm.h now exposes pmm_mark_region(), pmm_set_limits(), pmm_arch_init()
- pmm_init() calls pmm_arch_init() (arch-specific) which discovers
  memory and calls pmm_set_limits() + pmm_mark_region()
- pmm.c provides a weak default pmm_arch_init() for archs without one
- Kernel protection uses hal_mm_virt_to_phys() (no #if MIPS/x86)
- x86 pmm_boot.c handles Multiboot2 parsing, module protection,
  and boot info protection
- Zero #if guards remain in pmm.c

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofeat: implement kconsole — kernel emergency console (like HelenOS kconsole)
Tulio A M Mendes [Tue, 10 Feb 2026 06:01:02 +0000 (03:01 -0300)]
feat: implement kconsole — kernel emergency console (like HelenOS kconsole)

When VFS mount or init fails, AdrOS now enters a minimal kernel-mode
emergency console instead of the full shell. This is similar to
HelenOS's kconsole — it runs entirely in kernel mode and provides
basic diagnostic commands.

Design:
- kconsole_enter() runs a blocking read loop using kgetc()/kprintf()
- Commands: help, dmesg, reboot, halt
- Activated from kernel_main() when init_start() returns < 0
- Fully architecture-independent (uses only generic console API)

The normal shell remains available for userspace-initiated sessions.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofeat: add kgetc() to console subsystem for kernel input
Tulio A M Mendes [Tue, 10 Feb 2026 05:56:54 +0000 (02:56 -0300)]
feat: add kgetc() to console subsystem for kernel input

kgetc() reads a single character via keyboard_read_blocking(),
providing a symmetric API alongside kprintf() for output.
This enables the kernel console (and future kconsole) to have
a generic input mechanism independent of architecture.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: remove #if x86 guard from scheduler fork_child_trampoline
Tulio A M Mendes [Tue, 10 Feb 2026 05:53:40 +0000 (02:53 -0300)]
refactor: remove #if x86 guard from scheduler fork_child_trampoline

Add hal_usermode_enter_regs() to the HAL usermode interface so
fork_child_trampoline() can call it generically without #if x86.

- Add declaration to include/hal/usermode.h
- Implement in src/hal/x86/usermode.c (calls x86_enter_usermode_regs)
- Add stubs in ARM, RISC-V, MIPS HAL usermode.c
- scheduler.c now uses hal_usermode_enter_regs() with no guards

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: remove all #if x86 guards from shell.c, migrate to kprintf + HAL
Tulio A M Mendes [Tue, 10 Feb 2026 05:47:20 +0000 (02:47 -0300)]
refactor: remove all #if x86 guards from shell.c, migrate to kprintf + HAL

shell.c is generic kernel code and should not contain any
architecture-specific guards or inline assembly.

Changes:
- Replace all uart_print() calls with kprintf() so output goes
  through the console subsystem and into the kernel log buffer
- Replace x86 'cli; ud2' panic asm with hal_cpu_disable_interrupts()
  + hal_cpu_idle() loop
- Replace #if x86 ring3 guard with arch_platform_usermode_test_start()
  which is already a generic wrapper with per-arch implementations
- Use console_write() for echo/backspace (no log buffer pollution)
- Remove unnecessary uart_console.h and vga_console.h includes

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: move x86 ATA PIO driver from src/drivers/ata_pio.c to src/hal/x86/ata_pio.c
Tulio A M Mendes [Tue, 10 Feb 2026 05:42:24 +0000 (02:42 -0300)]
refactor: move x86 ATA PIO driver from src/drivers/ata_pio.c to src/hal/x86/ata_pio.c

ATA PIO uses x86 I/O port instructions (inb/outb/inw/outw) for
disk access. The full implementation now lives in src/hal/x86/ata_pio.c
(no #if guards). src/drivers/ata_pio.c contains only weak stubs
returning -ENOSYS, overridden at link time for x86.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: move x86 PCI driver from src/drivers/pci.c to src/hal/x86/pci.c
Tulio A M Mendes [Tue, 10 Feb 2026 05:37:31 +0000 (02:37 -0300)]
refactor: move x86 PCI driver from src/drivers/pci.c to src/hal/x86/pci.c

PCI config space access via I/O ports 0xCF8/0xCFC is x86-specific.
The full PCI enumeration implementation now lives in src/hal/x86/pci.c
(no #if guards). src/drivers/pci.c contains only weak stubs that are
overridden by the arch-specific version at link time.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: move x86 ELF loader from src/kernel/elf.c to src/arch/x86/elf.c
Tulio A M Mendes [Tue, 10 Feb 2026 05:32:41 +0000 (02:32 -0300)]
refactor: move x86 ELF loader from src/kernel/elf.c to src/arch/x86/elf.c

The ELF loader uses x86-specific page table manipulation (recursive
mapping at 0xFFFFF000/0xFFC00000), EM_386 validation, and low-16MB
allocation. It is 100% architecture-dependent and should not live
in the generic kernel directory.

- Move full implementation to src/arch/x86/elf.c (no #if guards)
- Replace src/kernel/elf.c with a weak stub returning -1
- The linker picks the arch-specific version when available

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: remove include/multiboot2.h wrapper, use arch/x86/multiboot2.h directly
Tulio A M Mendes [Tue, 10 Feb 2026 05:26:38 +0000 (02:26 -0300)]
refactor: remove include/multiboot2.h wrapper, use arch/x86/multiboot2.h directly

The generic wrapper include/multiboot2.h only forwarded to
arch/x86/multiboot2.h under #if x86. Since Multiboot2 is purely
x86/GRUB-specific, the wrapper should not exist in the generic
include/ directory. pmm.c now includes arch/x86/multiboot2.h
directly (already inside its own #if x86 guard).

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: replace hardcoded 0xC0000000 in elf.c and uaccess.c with hal_mm_kernel_virt...
Tulio A M Mendes [Tue, 10 Feb 2026 05:01:18 +0000 (02:01 -0300)]
refactor: replace hardcoded 0xC0000000 in elf.c and uaccess.c with hal_mm_kernel_virt_base()

Both elf.c and uaccess.c had X86_KERNEL_VIRT_BASE defined as
0xC0000000U inside #if x86 blocks. While technically correct
(only compiled on x86), this is inconsistent with the rest of the
codebase which now uses hal_mm_kernel_virt_base() everywhere.

Replace with the HAL abstraction for consistency and to ensure
the kernel virtual base is defined in exactly one place per arch.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: replace x86 'cli; hlt' asm in syscall.c with HAL calls
Tulio A M Mendes [Tue, 10 Feb 2026 04:58:10 +0000 (01:58 -0300)]
fix: replace x86 'cli; hlt' asm in syscall.c with HAL calls

syscall.c used raw x86 inline assembly ('cli; hlt') in the exit
syscall idle loop. This would not compile on ARM/RISC-V/MIPS.

Add hal_cpu_disable_interrupts() to the HAL CPU interface with
implementations for x86 (cli) and stubs for other architectures.
Replace the raw asm with hal_cpu_disable_interrupts() + hal_cpu_idle().

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofeat: add dmesg command to kernel shell
Tulio A M Mendes [Tue, 10 Feb 2026 04:55:15 +0000 (01:55 -0300)]
feat: add dmesg command to kernel shell

Reads the kernel log ring buffer via klog_read() and prints it
to the UART console, allowing users to review boot messages and
earlier kprintf output — just like Linux's dmesg command.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofeat: add kernel log ring buffer to kprintf (printk-style dmesg support)
Tulio A M Mendes [Tue, 10 Feb 2026 04:53:00 +0000 (01:53 -0300)]
feat: add kernel log ring buffer to kprintf (printk-style dmesg support)

Like Linux's printk, kprintf() now writes every formatted message
into a 16KB circular ring buffer (klog_buf) before dispatching to
console drivers (UART, VGA). This allows old messages to be
retrieved later via klog_read(), enabling dmesg functionality.

Design:
- 16KB static ring buffer (KLOG_BUF_SIZE)
- klog_head tracks next write position, klog_count tracks fill
- klog_append() writes into ring, capping at buffer size
- klog_read(out, size) copies oldest-to-newest into caller buffer
- Protected by dedicated klog_lock spinlock

Flow: kprintf() -> kvsnprintf() -> klog_append() -> console_write()

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: replace x86 bsf asm in scheduler with portable __builtin_ctz
Tulio A M Mendes [Tue, 10 Feb 2026 04:50:27 +0000 (01:50 -0300)]
fix: replace x86 bsf asm in scheduler with portable __builtin_ctz

bsf32() used x86-only 'bsf' inline assembly to find the lowest
set bit in the O(1) scheduler bitmap. This would not compile on
ARM/RISC-V/MIPS. Replace with __builtin_ctz() which GCC supports
on all target architectures.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: x86 code uses arch-specific headers directly
Tulio A M Mendes [Tue, 10 Feb 2026 04:33:15 +0000 (01:33 -0300)]
refactor: x86 code uses arch-specific headers directly

arch_early_setup.c now includes arch/x86/multiboot2.h directly
instead of the generic wrapper, consistent with the pattern of
x86-only code using arch-specific headers.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: guard multiboot2.h include in pmm.c with #if x86
Tulio A M Mendes [Tue, 10 Feb 2026 04:30:39 +0000 (01:30 -0300)]
refactor: guard multiboot2.h include in pmm.c with #if x86

multiboot2.h is an x86/GRUB boot protocol header. pmm.c (generic
mm/ code) included it unconditionally even though all Multiboot2
usage is already inside #if x86 blocks. Guard the include so it
is not pulled in on ARM/RISC-V/MIPS builds.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agorefactor: move gdt.h/idt.h out of generic include/ into arch-specific paths
Tulio A M Mendes [Tue, 10 Feb 2026 04:27:48 +0000 (01:27 -0300)]
refactor: move gdt.h/idt.h out of generic include/ into arch-specific paths

gdt.h and idt.h are x86-only concepts (Global Descriptor Table,
Interrupt Descriptor Table) that do not exist on ARM/RISC-V/MIPS.
They should not live in the generic include/ directory.

Changes:
- Delete include/gdt.h wrapper; all 3 consumers (arch/x86/ and
  hal/x86/) now include arch/x86/gdt.h directly.
- Delete include/idt.h wrapper; create include/interrupts.h as
  the generic abstraction (provides struct registers + isr_handler_t
  with arch-specific dispatch).
- Generic kernel code (syscall.c, uaccess.c, process.h) now
  includes interrupts.h instead of idt.h.
- x86-only code (idt.c, timer HAL, keyboard HAL, usermode, etc.)
  now includes arch/x86/idt.h directly.
- Remove unused idt.h and io.h includes from kernel/main.c.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: implement VGA text-mode scrolling instead of wrap-to-row-0
Tulio A M Mendes [Tue, 10 Feb 2026 04:14:19 +0000 (01:14 -0300)]
fix: implement VGA text-mode scrolling instead of wrap-to-row-0

When the cursor reached the bottom of the 25-row VGA text buffer,
term_row was reset to 0, overwriting the top of the screen. This
made boot output unreadable once it exceeded 25 lines.

Add vga_scroll() that shifts all rows up by one and clears the
last row. Called from both vga_put_char and vga_print.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: implement real irq_save/irq_restore for ARM, RISC-V, MIPS
Tulio A M Mendes [Tue, 10 Feb 2026 04:12:07 +0000 (01:12 -0300)]
fix: implement real irq_save/irq_restore for ARM, RISC-V, MIPS

spinlock.h had no-op irq_save/irq_restore for non-x86 architectures,
meaning spin_lock_irqsave would not actually disable interrupts on
ARM, RISC-V, or MIPS — breaking all critical sections.

Add proper implementations:
- ARM: mrs/msr CPSR with cpsid i
- RISC-V: csrrci/csrsi mstatus MIE bit
- MIPS: mfc0/di/ei on CP0 Status IE bit

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: replace hardcoded 0xC0000000 in pmm.c with hal_mm_kernel_virt_base()
Tulio A M Mendes [Tue, 10 Feb 2026 04:09:56 +0000 (01:09 -0300)]
fix: replace hardcoded 0xC0000000 in pmm.c with hal_mm_kernel_virt_base()

pmm.c used raw 0xC0000000 to detect higher-half kernel and adjust
physical addresses. Replace with hal_mm_kernel_virt_base() so the
PMM works correctly on architectures with different kernel virtual
base addresses.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: replace hardcoded 0xC0000000 in syscall.c with hal_mm_kernel_virt_base()
Tulio A M Mendes [Tue, 10 Feb 2026 04:08:02 +0000 (01:08 -0300)]
fix: replace hardcoded 0xC0000000 in syscall.c with hal_mm_kernel_virt_base()

sys_brk and mmap used hardcoded 0xC0000000U (x86 kernel virtual
base) for bounds checking. Replace with hal_mm_kernel_virt_base()
so the code is architecture-independent.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: wrap pci.c in #if x86 guard with stubs for other architectures
Tulio A M Mendes [Tue, 10 Feb 2026 04:05:52 +0000 (01:05 -0300)]
fix: wrap pci.c in #if x86 guard with stubs for other architectures

PCI config space I/O port access (0xCF8/0xCFC) using outl/inl is
x86-only. The driver had no architecture guard, so it would fail
to compile on ARM, RISC-V, and MIPS.

Wrap the full implementation in #if defined(__i386__) and provide
no-op stubs for non-x86 targets.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: replace hardcoded 0xC0000000 in slab.c with hal_mm_phys_to_virt()
Tulio A M Mendes [Tue, 10 Feb 2026 04:04:05 +0000 (01:04 -0300)]
fix: replace hardcoded 0xC0000000 in slab.c with hal_mm_phys_to_virt()

slab.c used 'base + 0xC0000000U' to convert physical to virtual
addresses, which is x86 higher-half specific. This breaks on ARM,
RISC-V, and MIPS where the kernel virtual base differs.

Add hal_mm_phys_to_virt(), hal_mm_virt_to_phys(), and
hal_mm_kernel_virt_base() to the HAL mm interface with proper
implementations for x86 (0xC0000000 offset) and identity-mapped
stubs for ARM, RISC-V, MIPS.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: move VBE framebuffer VA from 0xD0000000 to 0xE0000000
Tulio A M Mendes [Tue, 10 Feb 2026 04:01:02 +0000 (01:01 -0300)]
fix: move VBE framebuffer VA from 0xD0000000 to 0xE0000000

The kernel heap starts at KHEAP_START=0xD0000000 and spans 10MB.
The VBE framebuffer was also mapped at 0xD0000000, causing a
virtual address collision that would corrupt the heap when a
framebuffer is present.

Move VBE mapping to 0xE0000000 which is safely above the heap.

Passes: make, cppcheck, QEMU smoke test.

7 weeks agofix: add rq_enqueue on wake in keyboard, tty, pty drivers
Tulio A M Mendes [Tue, 10 Feb 2026 03:59:11 +0000 (00:59 -0300)]
fix: add rq_enqueue on wake in keyboard, tty, pty drivers

keyboard.c, tty.c, pty.c all transition processes from BLOCKED to
READY without enqueuing them into the O(1) scheduler runqueue.
This causes woken processes to be invisible to rq_pick_next(),
leading to starvation until the active/expired swap rescues them.

Add sched_enqueue_ready() public API in scheduler.c and call it
from all three wake sites.

Passes: make, cppcheck, QEMU smoke test (10s, all init tests OK).

7 weeks agoPOSIX Tiers 1-3: signals, brk/sbrk, nanosleep, raw TTY, O_CLOEXEC, PMM refcount,...
Tulio A M Mendes [Tue, 10 Feb 2026 03:42:56 +0000 (00:42 -0300)]
POSIX Tiers 1-3: signals, brk/sbrk, nanosleep, raw TTY, O_CLOEXEC, PMM refcount, CoW fork, mmap/munmap, procfs, slab allocator, O(1) scheduler, PCI enumeration, VBE framebuffer

Tier 1:
- Signal characters (Ctrl+C/Z/\ -> SIGINT/SIGTSTP/SIGQUIT) in TTY/PTY
- brk/sbrk syscall with ELF loader heap break support
- nanosleep/clock_gettime syscalls (tick-based)
- Raw TTY mode (non-canonical) + ISIG flag + TIOCGWINSZ/TIOCSWINSZ

Tier 2:
- O_CLOEXEC/FD_CLOEXEC: per-FD flags, fcntl F_GETFD/F_SETFD, close on execve
- PMM ref-counting (uint16_t per-frame, atomic ops)
- Copy-on-Write fork: PTE bit 9 COW marker, page fault handler, vmm_as_clone_user_cow
- mmap/munmap: anonymous MAP_PRIVATE, per-process VMA tracker (32 slots)
- /proc filesystem: /proc/self/status, /proc/uptime, /proc/meminfo

Tier 3:
- Slab allocator: free-list-in-place, per-cache spinlock, auto-grow
- O(1) scheduler: 32-priority bitmap + active/expired runqueue swap
- PCI enumeration: bus/slot/func scan, vendor/device/class/BAR/IRQ
- VBE framebuffer: multiboot2 tag parsing, kernel VA mapping, pixel ops

All changes pass: make clean && make, cppcheck --enable=warning,performance,portability, and QEMU smoke test (10s stable boot, all init tests pass).

7 weeks agofix: heap coalesce early-return, process_create_kernel leak, pipe double-free, path...
Tulio A M Mendes [Tue, 10 Feb 2026 02:35:38 +0000 (23:35 -0300)]
fix: heap coalesce early-return, process_create_kernel leak, pipe double-free, path '..' resolution

7 weeks agodocs: update README, BUILD_GUIDE, and POSIX_ROADMAP to reflect current state
Tulio A M Mendes [Tue, 10 Feb 2026 02:16:07 +0000 (23:16 -0300)]
docs: update README, BUILD_GUIDE, and POSIX_ROADMAP to reflect current state

7 weeks agoposix: generic readdir/getdents across all VFS (tmpfs, devfs, overlayfs, diskfs)
Tulio A M Mendes [Tue, 10 Feb 2026 02:04:53 +0000 (23:04 -0300)]
posix: generic readdir/getdents across all VFS (tmpfs, devfs, overlayfs, diskfs)

7 weeks agoposix: add rename and rmdir syscalls (diskfs)
Tulio A M Mendes [Tue, 10 Feb 2026 01:56:35 +0000 (22:56 -0300)]
posix: add rename and rmdir syscalls (diskfs)

7 weeks agoposix: add openat, fstatat, unlinkat syscalls (AT_FDCWD)
Tulio A M Mendes [Tue, 10 Feb 2026 01:50:22 +0000 (22:50 -0300)]
posix: add openat, fstatat, unlinkat syscalls (AT_FDCWD)

7 weeks agoposix: add pipe2 and dup3 syscalls
Tulio A M Mendes [Tue, 10 Feb 2026 01:37:59 +0000 (22:37 -0300)]
posix: add pipe2 and dup3 syscalls

7 weeks agoposix: add chdir/getcwd and relative path resolution
Tulio A M Mendes [Tue, 10 Feb 2026 01:21:12 +0000 (22:21 -0300)]
posix: add chdir/getcwd and relative path resolution

7 weeks agoposix: add fcntl(F_SETFL) O_NONBLOCK for pipes and tty/pty
Tulio A M Mendes [Tue, 10 Feb 2026 01:12:20 +0000 (22:12 -0300)]
posix: add fcntl(F_SETFL) O_NONBLOCK for pipes and tty/pty

7 weeks agouser: add isatty smoke test via TCGETS
Tulio A M Mendes [Tue, 10 Feb 2026 01:01:09 +0000 (22:01 -0300)]
user: add isatty smoke test via TCGETS

7 weeks agovfs: add getdents syscall for diskfs directories
Tulio A M Mendes [Tue, 10 Feb 2026 00:54:17 +0000 (21:54 -0300)]
vfs: add getdents syscall for diskfs directories

7 weeks agodiskfs: add mkdir/unlink syscalls
Tulio A M Mendes [Tue, 10 Feb 2026 00:41:56 +0000 (21:41 -0300)]
diskfs: add mkdir/unlink syscalls

7 weeks agodiskfs: add hierarchical directories and migrate v2 layout
Tulio A M Mendes [Tue, 10 Feb 2026 00:32:53 +0000 (21:32 -0300)]
diskfs: add hierarchical directories and migrate v2 layout

7 weeks agopersistfs: back /persist/counter by diskfs
Tulio A M Mendes [Tue, 10 Feb 2026 00:23:15 +0000 (21:23 -0300)]
persistfs: back /persist/counter by diskfs

7 weeks agodiskfs: add minimal on-disk filesystem mounted at /disk
Tulio A M Mendes [Tue, 10 Feb 2026 00:11:50 +0000 (21:11 -0300)]
diskfs: add minimal on-disk filesystem mounted at /disk

7 weeks agouaccess: recover from kernel page faults during copy_*_user
Tulio A M Mendes [Tue, 10 Feb 2026 00:02:00 +0000 (21:02 -0300)]
uaccess: recover from kernel page faults during copy_*_user

7 weeks agopty: add minimal /dev/ptmx and /dev/pts/0
Tulio A M Mendes [Mon, 9 Feb 2026 23:41:42 +0000 (20:41 -0300)]
pty: add minimal /dev/ptmx and /dev/pts/0

7 weeks agosignal: add SA_SIGINFO and sigaction ABI
Tulio A M Mendes [Mon, 9 Feb 2026 23:25:14 +0000 (20:25 -0300)]
signal: add SA_SIGINFO and sigaction ABI

7 weeks agox86: deliver SIGSEGV on user page faults
Tulio A M Mendes [Mon, 9 Feb 2026 22:57:17 +0000 (19:57 -0300)]
x86: deliver SIGSEGV on user page faults

7 weeks agouser: add errno-based syscall wrappers
Tulio A M Mendes [Mon, 9 Feb 2026 22:46:39 +0000 (19:46 -0300)]
user: add errno-based syscall wrappers

7 weeks agotools: avoid host macro collisions in user init (cppcheck)
Tulio A M Mendes [Mon, 9 Feb 2026 22:40:42 +0000 (19:40 -0300)]
tools: avoid host macro collisions in user init (cppcheck)

7 weeks agodocs: update POSIX roadmap with sigreturn
Tulio A M Mendes [Mon, 9 Feb 2026 22:31:03 +0000 (19:31 -0300)]
docs: update POSIX roadmap with sigreturn

7 weeks agox86: add sigreturn trampoline and fix execve stack usage
Tulio A M Mendes [Mon, 9 Feb 2026 20:59:27 +0000 (17:59 -0300)]
x86: add sigreturn trampoline and fix execve stack usage

Implement SYSCALL_SIGRETURN and userland signal trampoline/sigframe so handlers can return safely.
Fix x86 signal delivery stack layout to avoid clobbering sigframe/trampoline.
Fix execve heap corruption by avoiding large on-stack argv/envp buffers and adding cleanup.
Add init.elf smoke test for sigreturn.

8 weeks agodocs: update POSIX roadmap and persistence notes
Tulio A M Mendes [Sun, 8 Feb 2026 11:08:52 +0000 (08:08 -0300)]
docs: update POSIX roadmap and persistence notes

8 weeks agostorage: add ATA PIO + persistfs mounted at /persist
Tulio A M Mendes [Sun, 8 Feb 2026 10:51:54 +0000 (07:51 -0300)]
storage: add ATA PIO + persistfs mounted at /persist

8 weeks agotty: add basic job control (fg pgrp) + SIGTTIN/SIGTTOU
Tulio A M Mendes [Sun, 8 Feb 2026 10:49:56 +0000 (07:49 -0300)]
tty: add basic job control (fg pgrp) + SIGTTIN/SIGTTOU

8 weeks agox86/vmm+elf: fix user ELF mapping and PT access
Tulio A M Mendes [Sun, 8 Feb 2026 10:29:50 +0000 (07:29 -0300)]
x86/vmm+elf: fix user ELF mapping and PT access

8 weeks agocppcheck: const cleanups (full vfs api)
Tulio A M Mendes [Sun, 8 Feb 2026 07:24:04 +0000 (04:24 -0300)]
cppcheck: const cleanups (full vfs api)

8 weeks agocppcheck: const cleanups (partial)
Tulio A M Mendes [Sun, 8 Feb 2026 07:14:56 +0000 (04:14 -0300)]
cppcheck: const cleanups (partial)

8 weeks agox86: fix fork addr_space clone; add tty ioctl + session/pgrp syscalls
Tulio A M Mendes [Sun, 8 Feb 2026 07:01:01 +0000 (04:01 -0300)]
x86: fix fork addr_space clone; add tty ioctl + session/pgrp syscalls

- fork clones from active CR3 and returns correct pid
- vmm_as_clone_user copies user pages via per-AS tmp mapping
- tty: implement ioctl (termios + pgrp) and ICANON/ECHO handling
- add setsid/setpgid/getpgrp syscalls + init.elf smoke tests
- overlayfs: fix cppcheck knownConditionTrueFalse

8 weeks agoposix: add select() syscall (minimal)
Tulio A M Mendes [Sun, 8 Feb 2026 04:07:46 +0000 (01:07 -0300)]
posix: add select() syscall (minimal)

Add a minimal select() syscall implemented as a wrapper over poll(). Uses uint64_t read/write fd masks (nfds<=64), timeout semantics aligned with poll, and a userland smoke test with a pipe.

8 weeks agox86: treat user page fault as SIGSEGV
Tulio A M Mendes [Sun, 8 Feb 2026 03:56:13 +0000 (00:56 -0300)]
x86: treat user page fault as SIGSEGV

Handle ISR14 page faults from ring3 by terminating the current process with a SIGSEGV-like status (128+11) instead of kernel panic. Add userland smoke test that triggers a NULL write and validates waitpid status.

8 weeks agoposix: add kill(SIGKILL) syscall
Tulio A M Mendes [Sun, 8 Feb 2026 03:53:48 +0000 (00:53 -0300)]
posix: add kill(SIGKILL) syscall

Introduce a minimal kill(pid,sig) syscall with SIGKILL support. Implement process_kill() to mark target as zombie, close its FDs with refcounting, and wake a waiting parent. Add ESRCH and a userland init.elf smoke test.

8 weeks agoposix: poll syscall (pipes + devfs tty/null)
Tulio A M Mendes [Sun, 8 Feb 2026 03:31:57 +0000 (00:31 -0300)]
posix: poll syscall (pipes + devfs tty/null)

Add a minimal poll() syscall (POLLIN/POLLOUT) with timeout semantics (0 non-blocking, <0 blocking). Support pipe endpoints and devfs char devices (/dev/null,/dev/tty) and add userland smoke tests.

8 weeks agodocs: update POSIX/Unix status (errno, devfs, getppid, WNOHANG)
Tulio A M Mendes [Sun, 8 Feb 2026 03:15:54 +0000 (00:15 -0300)]
docs: update POSIX/Unix status (errno, devfs, getppid, WNOHANG)

Document recently implemented Unix/POSIX features: getppid, waitpid(WNOHANG), devfs (/dev/null,/dev/tty), kernel -errno convention, and uaccess hardening.

8 weeks agoposix: standardize -errno in VFS/tmpfs/initrd
Tulio A M Mendes [Sun, 8 Feb 2026 03:12:50 +0000 (00:12 -0300)]
posix: standardize -errno in VFS/tmpfs/initrd

Replace remaining -1 style returns in core helpers used by syscalls and early init with negative errno codes (vfs_mount, tmpfs_add_file/mkdir_p, initrd alloc/path helpers). Add missing errno constants (EEXIST/ENOTDIR/ENOSPC).

8 weeks agoposix: remove -1 returns from ELF loader
Tulio A M Mendes [Sun, 8 Feb 2026 03:08:41 +0000 (00:08 -0300)]
posix: remove -1 returns from ELF loader

Convert elf32 loader helpers to return -errno codes (EINVAL/ENOMEM/ENOENT/EIO/EFAULT) instead of -1, aligning with kernel-wide -errno syscall convention.

8 weeks agoposix: tighten uaccess + errno helpers
Tulio A M Mendes [Sun, 8 Feb 2026 03:01:39 +0000 (00:01 -0300)]
posix: tighten uaccess + errno helpers

Return proper -errno from remaining syscall helpers (pipe/fd allocation) and harden copy_to_user to require writable user mappings on x86. copy_{to,from}_user now return -EFAULT on invalid ranges.

8 weeks agoposix: devfs with /dev/null and /dev/tty
Tulio A M Mendes [Sun, 8 Feb 2026 02:55:41 +0000 (23:55 -0300)]
posix: devfs with /dev/null and /dev/tty

Add a minimal devfs mounted at /dev providing /dev/null and /dev/tty char devices. Implement tty_read_kbuf/tty_write_kbuf to support VFS-backed tty IO and allow open/read/write through FS_CHARDEVICE nodes. Add userland smoke tests.

8 weeks agoposix: standardize -errno returns
Tulio A M Mendes [Sun, 8 Feb 2026 02:46:46 +0000 (23:46 -0300)]
posix: standardize -errno returns

Adopt negative errno return convention across waitpid/open/fd_close and TTY read/write, add missing errno constants, and return ENOSYS for unknown syscalls.

8 weeks agoposix: getppid syscall
Tulio A M Mendes [Sun, 8 Feb 2026 02:37:16 +0000 (23:37 -0300)]
posix: getppid syscall

Add SYSCALL_GETPPID and userland wrappers. Include a simple fork-based smoke test validating getppid() in init.elf.

8 weeks agofix: prevent fork clone stack overflow
Tulio A M Mendes [Sun, 8 Feb 2026 02:37:06 +0000 (23:37 -0300)]
fix: prevent fork clone stack overflow

Fix vmm_as_clone_user to use a heap-allocated 4KB temp buffer instead of a 4KB stack array (kernel stacks are 4KB). Harden heap free/coalesce logic and diagnostics to better catch corruption/double-free.

8 weeks agoposix: waitpid WNOHANG
Tulio A M Mendes [Sun, 8 Feb 2026 02:15:15 +0000 (23:15 -0300)]
posix: waitpid WNOHANG

Add WNOHANG option support to waitpid in kernel scheduler and syscall path, and include a userland smoke test.

8 weeks agodocs: update POSIX/Unix feature status
Tulio A M Mendes [Sun, 8 Feb 2026 02:02:09 +0000 (23:02 -0300)]
docs: update POSIX/Unix feature status

Refresh README, build guide, and POSIX roadmap to reflect implemented syscalls (dup/dup2/pipe/fork/execve), mounts/tmpfs/overlayfs, analysis targets, and remaining gaps.

8 weeks agoD3: execve argv/envp userland test
Tulio A M Mendes [Sun, 8 Feb 2026 01:56:55 +0000 (22:56 -0300)]
D3: execve argv/envp userland test

Pass argv/envp from init.elf into execve() and extend echo.elf to parse argc/argv/envp from the initial user stack for validation.