Skip to content

Conversation

assembler-0
Copy link
Owner

@assembler-0 assembler-0 commented Jul 9, 2025

pls help, crashing

Summary by CodeRabbit

  • New Features

    • Introduced a dedicated security manager process to enhance system security.
    • Added security tokens and privilege enforcement for all processes.
  • Removals

    • Removed command-line shell functionality and related commands.
    • Eliminated keyboard and driver management subsystems.
  • Improvements

    • Enhanced process scheduling with security validation and privilege checks.
    • Streamlined kernel initialization to focus on core and security modules.
  • Bug Fixes

    • Improved error handling and messaging during kernel panic scenarios.

Copy link

coderabbitai bot commented Jul 9, 2025

Walkthrough

This update removes the kernel's shell and driver subsystems, eliminating their initialization and related process management. It introduces a security manager process (PID 1) running SecureKernelIntegritySubsystem with system privileges, enforces process privilege levels and security tokens, and updates process creation, scheduling, and validation to support these new security mechanisms.

Changes

Files/Groups Change Summary
Kernel/Core/Kernel.c Removes shell/driver init and KernelKeeper; creates security manager process; updates main loop for scheduling.
Kernel/Core/Panic.c Cleans up output and whitespace; standardizes delay logic; no functional changes to panic handling.
Kernel/Core/Shell.c, Kernel/Core/Shell.h Deletes shell implementation and its header, removing command input and shell loop from the kernel.
Kernel/Drivers/Driver.c, Kernel/Drivers/Driver.h Deletes driver management and interface code, removing driver registration/init and type-based lookup.
Kernel/Drivers/Keyboard.c Deletes keyboard driver implementation and its registration routine.
Kernel/Drivers/Interrupts.c Removes keyboard interrupt handling; cleans up related includes.
Kernel/Process/Process.c, Kernel/Process/Process.h Adds process privilege/security token system, security manager, secure process creation, and validation logic.
meson.build Removes deleted shell and driver source files from build configuration.

Sequence Diagram(s)

sequenceDiagram
    participant KernelMain
    participant SecureKernelIntegritySubsystem
    participant ProcessManager
    participant Scheduler

    KernelMain->>ProcessManager: CreateSecureProcess(SecureKernelIntegritySubsystem, system)
    Note right of KernelMain: Panic if creation fails
    KernelMain->>Scheduler: Loop: if scheduling needed, call Schedule()
    loop
        Scheduler->>ProcessManager: Validate process security tokens
        alt Invalid token
            ProcessManager->>Scheduler: Terminate and remove process
        end
        Scheduler->>ProcessManager: Switch to next process (privilege-aware)
    end
    SecureKernelIntegritySubsystem->>ProcessManager: Register as security manager
    SecureKernelIntegritySubsystem->>ProcessManager: Create system service process
    SecureKernelIntegritySubsystem->>ProcessManager: Continuously validate tokens
Loading

Possibly related PRs

  • Development #12: This PR previously added the shell, driver initialization, and KernelKeeper process to KernelMain, directly affecting the same components now being removed or refactored for security management.

Poem

A shell once echoed, now it's gone,
The drivers too have hopped along.
Security stands, ears tall and keen,
Guarding tokens, keeping things clean.
With privilege checks and manager new,
The kernel’s safer—hippity-hoo!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between deb184e and 3032e00.

📒 Files selected for processing (11)
  • Kernel/Core/Kernel.c (1 hunks)
  • Kernel/Core/Panic.c (1 hunks)
  • Kernel/Core/Shell.c (0 hunks)
  • Kernel/Core/Shell.h (0 hunks)
  • Kernel/Drivers/Driver.c (0 hunks)
  • Kernel/Drivers/Driver.h (0 hunks)
  • Kernel/Drivers/Interrupts.c (0 hunks)
  • Kernel/Drivers/Keyboard.c (0 hunks)
  • Kernel/Process/Process.c (5 hunks)
  • Kernel/Process/Process.h (2 hunks)
  • meson.build (0 hunks)
💤 Files with no reviewable changes (7)
  • Kernel/Drivers/Interrupts.c
  • Kernel/Core/Shell.h
  • meson.build
  • Kernel/Core/Shell.c
  • Kernel/Drivers/Driver.h
  • Kernel/Drivers/Driver.c
  • Kernel/Drivers/Keyboard.c
🧰 Additional context used
🧬 Code Graph Analysis (2)
Kernel/Core/Panic.c (3)
Kernel/Core/Panic.h (2)
  • Panic (7-7)
  • PanicWithCode (8-8)
Kernel/Core/Kernel.c (2)
  • ClearScreen (17-23)
  • PrintKernel (25-46)
Kernel/Core/Kernel.h (2)
  • ClearScreen (5-5)
  • PrintKernel (6-6)
Kernel/Process/Process.c (6)
Kernel/Process/Process.h (9)
  • ProcessInit (53-53)
  • CreateSecureProcess (55-55)
  • entry_point (54-54)
  • entry_point (55-55)
  • Schedule (58-58)
  • RegisterSecurityManager (63-63)
  • SystemService (65-65)
  • SecureKernelIntegritySubsystem (64-64)
  • GetCurrentProcess (60-60)
Kernel/Core/Panic.h (1)
  • Panic (7-7)
Kernel/Core/Kernel.c (2)
  • PrintKernel (25-46)
  • PrintKernelInt (96-140)
Kernel/Core/Kernel.h (2)
  • PrintKernel (6-6)
  • PrintKernelInt (7-7)
Kernel/Memory/Memory.c (1)
  • AllocPage (29-41)
Kernel/Memory/Memory.h (1)
  • AllocPage (10-10)
🔇 Additional comments (7)
Kernel/Core/Panic.c (1)

14-15: Improved consistency and clarity

The changes enhance code consistency by:

  • Using the same delay loop pattern across all panic functions
  • Removing the misleading "System halted." message before calling KernelPanicHandler()

Also applies to: 25-26, 34-34

Kernel/Core/Kernel.c (2)

161-179: Security-focused kernel initialization looks good

The kernel now creates a security manager as the critical first process, which aligns with the new security model. The panic on failure is appropriate for this critical component.


161-198: Incorrect driver-removal concern – no keyboard or shell code present

I searched the entire codebase and found no keyboard driver or shell component (no files or symbols matching “keyboard” or “shell” under Kernel/Drivers or elsewhere). There is no keyboard initialization to remove in Kernel/Core/Kernel.c, so this comment can be disregarded.

Likely an incorrect or invalid review comment.

Kernel/Process/Process.h (2)

13-20: Well-designed security token structure

The SecurityToken struct with magic number validation and checksum provides good integrity checking. The privilege level system and proper structure padding are also well implemented.

Also applies to: 38-43


21-26: Confirm explicit initialization of ProcessState

A quick AST search did not reveal any assignments to .state in process creation paths. Since PROC_TERMINATED = 0, any zero-initialized Process will appear terminated by default. Please verify that every process allocation or constructor explicitly sets

process.state = PROC_READY;

(or an equivalent initialization) before use to avoid accidentally treating uninitialized processes as terminated.

  • Check all process creation routines (e.g., in Kernel/Process/…)
  • Ensure any static or heap-allocated Process instances override the zero value
Kernel/Process/Process.c (2)

13-40: Robust security token implementation

The token validation with magic number and checksum provides good integrity checking. The checksum calculation correctly excludes the checksum field itself.


91-99: Critical: Array bounds check after array access

The bounds check at line 91 occurs after processes[current_process] is already accessed at line 96. This could cause a crash if current_process is invalid.

Move the bounds check before accessing the array:

 // Fast security check - only security manager can create system processes
 if (privilege == PROC_PRIV_SYSTEM) {
-    if (current_process >= MAX_PROCESSES) {
-        Panic("CreateSecureProcess: Invalid current process");
-    }
-
-    // Only security manager (or initial kernel) can create system processes
-    if (security_manager_pid != 0 && processes[current_process].pid != security_manager_pid) {
+    if (current_process >= MAX_PROCESSES) {
+        Panic("CreateSecureProcess: Invalid current process");
+    }
+
+    // Only security manager (or initial kernel) can create system processes
+    if (security_manager_pid != 0 && processes[current_process].pid != security_manager_pid) {

Likely an incorrect or invalid review comment.

Comment on lines +327 to +345
while (1) {
// Periodic security checks
for (int i = 0; i < MAX_PROCESSES; i++) {
if (processes[i].state != PROC_TERMINATED) {
// Validate process tokens
if (!ValidateToken(&processes[i].token)) {
PrintKernel("[SECURITY] Token validation failed for PID: ");
PrintKernelInt(processes[i].pid);
PrintKernel("\n");
// Terminate compromised process
processes[i].state = PROC_TERMINATED;
process_count--;
}
}
}

// Small delay to prevent excessive CPU usage
for (volatile int i = 0; i < 1000; i++);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Aggressive security token validation could cause system instability

The security manager continuously validates all process tokens in a tight loop. If token corruption occurs (e.g., due to memory issues), this could terminate legitimate processes and destabilize the system.

Consider adding:

  1. Rate limiting for security checks
  2. Logging before termination for debugging
  3. Grace period or retry mechanism for token validation failures
 while (1) {
     // Periodic security checks
+    static int check_counter = 0;
+    if (++check_counter % 1000 != 0) {
+        for (volatile int i = 0; i < 1000; i++);
+        continue;
+    }
+    
     for (int i = 0; i < MAX_PROCESSES; i++) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while (1) {
// Periodic security checks
for (int i = 0; i < MAX_PROCESSES; i++) {
if (processes[i].state != PROC_TERMINATED) {
// Validate process tokens
if (!ValidateToken(&processes[i].token)) {
PrintKernel("[SECURITY] Token validation failed for PID: ");
PrintKernelInt(processes[i].pid);
PrintKernel("\n");
// Terminate compromised process
processes[i].state = PROC_TERMINATED;
process_count--;
}
}
}
// Small delay to prevent excessive CPU usage
for (volatile int i = 0; i < 1000; i++);
}
while (1) {
// Periodic security checks
static int check_counter = 0;
if (++check_counter % 1000 != 0) {
for (volatile int i = 0; i < 1000; i++);
continue;
}
for (int i = 0; i < MAX_PROCESSES; i++) {
if (processes[i].state != PROC_TERMINATED) {
// Validate process tokens
if (!ValidateToken(&processes[i].token)) {
PrintKernel("[SECURITY] Token validation failed for PID: ");
PrintKernelInt(processes[i].pid);
PrintKernel("\n");
// Terminate compromised process
processes[i].state = PROC_TERMINATED;
process_count--;
}
}
}
// Small delay to prevent excessive CPU usage
for (volatile int i = 0; i < 1000; i++);
}
🤖 Prompt for AI Agents
In Kernel/Process/Process.c around lines 327 to 345, the current infinite loop
aggressively validates all process tokens without delay or retry, risking system
instability by terminating legitimate processes on transient token validation
failures. To fix this, implement rate limiting by adding a longer delay or timer
between validation cycles, add detailed logging before terminating a process to
aid debugging, and introduce a grace period or retry mechanism that allows a
process token to fail validation a few times before termination to reduce false
positives.

Comment on lines +170 to +178
} else {
// Invalid token - terminate process
PrintKernel("[SECURITY] Invalid token detected, terminating process\n");
processes[next].state = PROC_TERMINATED;
if (processes[next].stack) {
// FreePage(processes[next].stack); // Assuming you have this function
}
process_count--;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Memory leak when terminating processes

The FreePage call is commented out, causing memory leaks when processes with invalid tokens are terminated. This could exhaust memory over time and cause crashes.

Uncomment the FreePage call or implement proper memory cleanup:

-                    // FreePage(processes[next].stack); // Assuming you have this function
+                    if (processes[next].stack) {
+                        FreePage(processes[next].stack);
+                        processes[next].stack = 0;
+                    }

🏁 Script executed:

#!/bin/bash
# Check if FreePage function exists
ast-grep --pattern 'FreePage($_)'

Length of output: 35


🏁 Script executed:

#!/bin/bash
# Search for any definition or usage of FreePage or variants in the repository
rg -n -A2 "FreePage"
rg -n -A2 "free_page"
rg -n -A2 "AllocPage"
rg -n -A2 "alloc_page"
rg -n -A2 "FreeMemory"
rg -n -A2 "ReleasePage"

Length of output: 2652


🏁 Script executed:

#!/bin/bash
# Display context around the termination block in Process.c
sed -n '150,200p' Kernel/Process/Process.c

Length of output: 2043


Free process stack on termination to prevent memory leaks

Terminating a process for an invalid token currently leaves its stack page allocated, which will eventually exhaust memory. Uncomment and invoke FreePage —and clear the pointer—inside the invalid-token block.

• File: Kernel/Process/Process.c
Location: inside Schedule() invalid-token branch (around line 175)

Suggested diff:

                     // Invalid token - terminate process
                     PrintKernel("[SECURITY] Invalid token detected, terminating process\n");
                     processes[next].state = PROC_TERMINATED;
-                    if (processes[next].stack) {
-                        // FreePage(processes[next].stack); // Assuming you have this function
-                    }
+                    if (processes[next].stack) {
+                        FreePage(processes[next].stack);
+                        processes[next].stack = NULL;
+                    }
                     process_count--;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} else {
// Invalid token - terminate process
PrintKernel("[SECURITY] Invalid token detected, terminating process\n");
processes[next].state = PROC_TERMINATED;
if (processes[next].stack) {
// FreePage(processes[next].stack); // Assuming you have this function
}
process_count--;
}
} else {
// Invalid token - terminate process
PrintKernel("[SECURITY] Invalid token detected, terminating process\n");
processes[next].state = PROC_TERMINATED;
if (processes[next].stack) {
FreePage(processes[next].stack);
processes[next].stack = NULL;
}
process_count--;
}
🤖 Prompt for AI Agents
In Kernel/Process/Process.c around lines 170 to 178 inside the Schedule()
function's invalid-token branch, the process stack is not freed when terminating
a process, causing a memory leak. Uncomment the call to
FreePage(processes[next].stack) to free the allocated stack page, then set
processes[next].stack to NULL to clear the pointer and prevent dangling
references.

@assembler-0 assembler-0 merged commit 4e5cfe8 into main Jul 9, 2025
1 check passed
This was referenced Jul 9, 2025
This was referenced Aug 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant