Skip to content

Latest commit

ย 

History

History
113 lines (82 loc) ยท 4.68 KB

File metadata and controls

113 lines (82 loc) ยท 4.68 KB

kpython: MicroPython in the Linux Kernel

kpython is a port of MicroPython designed to run as a loadable Linux kernel module (kpython.ko). It allows you to execute Python code directly within the kernel address space, enabling high-level scripting for kernel debugging, rapid prototyping, or dynamic policy handling.

โš ๏ธ DANGER: This project is EXPERIMENTAL / PRE-ALPHA. It involves running a garbage-collected runtime with a complex parser inside the Linux Kernel. This is extremely dangerous and intended solely for research and educational purposes. DO NOT use this on a production system.

โš ๏ธ WARNING: This module runs in Ring 0. While efforts have been made to sandbox the interpreter (stack limits, exception handling), a bug here can panic your kernel or corrupt memory. Use with caution.

Dev Note: This project was developed and tested on WSL2 (Windows Subsystem for Linux) using a custom kernel with CONFIG_MODULES enabled. This environment is highly recommended for development because a kernel panic in WSL2 typically only crashes the lightweight utility VM, leaving the Windows host unaffected. A similar panic on a bare-metal Linux host would force a full system reboot.

๐Ÿ“ Project Structure

  • micropython/: Git submodule containing the upstream MicroPython source. Kept pristine.
  • embed_cfg/: Configuration files (mpconfigport.h) used to generate the "Embed" source bundle.
  • kernel_mod/: The Linux Kernel Module source code. This contains the glue logic, shims, and the generated MicroPython embed source.
  • Makefile: Top-level build script that orchestrates the MicroPython generation and Kernel Module compilation.

๐Ÿ› ๏ธ Building

Prerequisites

  • Linux Kernel Headers for your running kernel.
  • build-essential (gcc, make, etc.).
  • Python 3 (for MicroPython build scripts).

Build Steps

  1. Initialize Submodule (if not done):

    git submodule update --init --recursive packages/kpython/micropython
  2. Build the Module:

    cd packages/kpython
    # Set M to the absolute path of kernel_mod if not automatically detected, 
    # or just run make if KDIR is standard.
    make

    If you are cross-compiling or targeting a specific kernel source tree:

    make KDIR=/path/to/kernel/source

    This will:

    1. Generate a single-file MicroPython source bundle (micropython_embed.c) tailored for the kernel.
    2. Patch the generated sources for kernel compatibility.
    3. Compile kpython.ko.

๐Ÿš€ Usage

Loading the Module

sudo insmod kernel_mod/kpython.ko

Check dmesg to confirm initialization:

dmesg | tail
# [  123.456] kpython: MicroPython kernel module initialised

Executing Python

The module exposes a debugfs interface at /sys/kernel/debug/kpython/exec. You can write Python scripts directly to this file.

Simple Print:

echo "print('Hello from Kernel Space!')" | sudo tee /sys/kernel/debug/kpython/exec

Calculations:

echo "print(2 * 100)" | sudo tee /sys/kernel/debug/kpython/exec

Defining Functions:

echo -e "def hello():\n  print('Called hello()')\nhello()" | sudo tee /sys/kernel/debug/kpython/exec

Unloading

sudo rmmod kpython

๐Ÿง  Technical Details

Architecture

  • Embed Port: Uses MicroPython's ports/embed to generate a self-contained C source file, decoupling the build from the kernel's Kbuild system.
  • Shims:
    • libc: Minimal wrappers for string.h functions are mapped to kernel equivalents (memcpy, strlen, etc.).
    • Allocation: malloc/free are mapped to vmalloc/vfree (or kmalloc for small allocations).
    • I/O: printf is wrapped to printk. puts is implemented via printk.
  • Safety Features:
    • Stack Protection: Explicit stack limits (12KB) are enforced to prevent overflowing the small kernel stack (16KB on x86_64).
    • Exception Handling: A custom x86_64 assembly implementation of setjmp/longjmp (NLR) handles Python exceptions without relying on userspace headers.
    • Atomic Context: sleep functions automatically switch between msleep (process context) and mdelay (atomic context).

Limitations

  • No Float Support: Floating point operations are disabled to avoid managing FPU state in the kernel.
  • No File I/O: The standard Python open() is not hooked up to the kernel VFS yet.
  • Architecture: Currently tested on x86_64. The assembly setjmp implementation is arch-specific.

๐Ÿ“ License

The kernel module wrapper is GPL, while the MicroPython core remains MIT.