Kpython – A MicroPython Sidecar for the Linux Kernel (Experimental)

4 pointsposted 12 hours ago
by kpython

1 Comments

kpython

12 hours ago

Hi HN,

I’ve been working on a little experiment rooted in a simple "What if?": Could we embed a high-level, garbage-collected runtime directly into the Linux Kernel to act as a programmable sidecar?

The goal wasn't to replace C or Rust, but to enable rapid prototyping and dynamic logic in Ring 0 without the "edit-compile-reboot" loop.

The result is kpython. It runs a stripped-down MicroPython interpreter inside a kernel module, allowing you to pipe Python code directly into debugfs for immediate execution.

* Repo:* https://github.com/pymergetic/kpython

The "Sidecar" Concept

Think of it as a dynamic scripting layer sitting alongside your rigid kernel modules.

Rapid Debugging: Inspect kernel structures or variables interactively.

Dynamic Logic: Imagine filtering network packets with a Python one-liner like if pkt.ip.src in blocklist: drop() (Socket bindings are conceptually possible and currently WIP).

AI Integration: It opens the door for LLMs to read dmesg and suggest/apply non-destructive fixes or diagnostics live.

Technical Implementation

Porting a runtime like MicroPython to the kernel space required solving a few interesting challenges:

Memory Safety: I mapped the Python allocator to vmalloc and implemented atomic-aware wrappers to prevent sleeping in interrupt contexts.

Exception Handling: Since the kernel lacks setjmp/longjmp, I implemented a custom x86_64 assembly shim to handle Python's non-local returns (NLR) safely.

Stack Constraints: To respect the small kernel stack (16KB), the interpreter enforces a strict 12KB stack limit to catch recursion early.

Minimalism: No FPU usage, no standard libc dependencies.

Status: Experimental

This is a research prototype. Running a GC in Ring 0 comes with risks. A bug here panics the kernel. Please do not use this on production systems.

Call for Collaboration

I’ve built the core engine, but there is huge potential for specific integrations (Netfilter hooks, VFS access, etc.). If you are a kernel developer or interested in embedded Python, I’d love your feedback or PRs to help stabilize the "sidecar".