{"id":29747002,"url":"https://github.com/multikernel/kernelscript","last_synced_at":"2025-07-26T08:02:23.127Z","repository":{"id":304884848,"uuid":"1019261571","full_name":"multikernel/kernelscript","owner":"multikernel","description":"KernelScript is a modern, type-safe, domain-specific programming language for eBPF development","archived":false,"fork":false,"pushed_at":"2025-07-24T21:43:26.000Z","size":2419,"stargazers_count":20,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-24T21:58:15.898Z","etag":null,"topics":["ebpf","linux-kernel"],"latest_commit_sha":null,"homepage":"","language":"OCaml","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/multikernel.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-14T04:08:28.000Z","updated_at":"2025-07-24T21:43:30.000Z","dependencies_parsed_at":"2025-07-17T01:37:55.666Z","dependency_job_id":"e6dc1e7f-b71e-4acd-a846-2454026508db","html_url":"https://github.com/multikernel/kernelscript","commit_stats":null,"previous_names":["multikernel/kernelscript"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/multikernel/kernelscript","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multikernel%2Fkernelscript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multikernel%2Fkernelscript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multikernel%2Fkernelscript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multikernel%2Fkernelscript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/multikernel","download_url":"https://codeload.github.com/multikernel/kernelscript/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multikernel%2Fkernelscript/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267138341,"owners_count":24041586,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-26T02:00:08.937Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ebpf","linux-kernel"],"created_at":"2025-07-26T08:01:44.424Z","updated_at":"2025-07-26T08:02:23.055Z","avatar_url":"https://github.com/multikernel.png","language":"OCaml","funding_links":[],"categories":["OCaml"],"sub_categories":[],"readme":"![KernelScript Logo](logo.png)\n\n# KernelScript\n\n\u003e **⚠️ Beta Version Notice**\n\u003e KernelScript is currently in beta development. The language syntax, APIs, and features are subject to change at any time without backward compatibility guarantees. This software is intended for experimental use and early feedback. Production use is not recommended at this time.\n\n**A Domain-Specific Programming Language for eBPF-Centric Development**\n\nKernelScript is a modern, type-safe, domain-specific programming language that unifies eBPF, userspace, and kernelspace development in a single codebase. Built with an eBPF-centric approach, it provides a clean, readable syntax while generating efficient C code for eBPF programs, coordinated userspace programs, and seamless kernel module (kfunc) integration.\n\nKernelScript aims to become the programming language for Linux kernel customization and application-specific optimization. By leveraging kfunc and eBPF capabilities, it provides a modern alternative to traditional kernel module interfaces such as procfs and debugfs.\n\n## Why KernelScript?\n\n### The Problem with Current eBPF Development\n\nWriting eBPF programs today is challenging and error-prone:\n\n- **Raw C + libbpf**: Requires deep eBPF knowledge, verbose boilerplate, manual memory management, and complex build systems\n- **Kernel development complexity**: Understanding verifier constraints, BPF helper functions, and kernel APIs\n- **Complex tail call management**: Manual program array setup, explicit `bpf_tail_call()` invocation, and error handling for failed tail calls\n- **Intricate dynptr APIs**: Manual management of `bpf_ringbuf_reserve_dynptr()`, `bpf_dynptr_data()`, `bpf_dynptr_write()`, and proper cleanup sequences\n- **Complex struct_ops implementation**: Manual function pointer setup, intricate BTF type registration, kernel interface compliance, and lifecycle management\n- **Complex kfunc implementation**: Manual kernel module creation, BTF symbol registration, export management, and module loading coordination\n- **Userspace coordination**: Manually writing loaders, map management, and program lifecycle code\n- **Multi-program systems**: No coordination between related eBPF programs sharing resources\n\n### Why Not Existing Tools?\n\n**Why not Rust?**\n- **Mixed compilation targets**: Rust's crate-wide, single-target compilation model cannot emit both eBPF bytecode and userspace binaries from one source file. KernelScript's `@xdp`, `@tc`, and regular functions compile to different targets automatically\n- **No first-class eBPF program values**: Rust lacks compile-time reflection to treat functions as values with load/attach lifecycle guarantees. KernelScript's type system prevents calling `attach()` before `load()` succeeds\n- **Cross-domain shared maps**: Rust's visibility and orphan rules conflict with KernelScript's implicit map sharing across programs. Safe userspace APIs for BPF maps require complex build-time generation in Rust\n- **Verifier-incompatible features**: Rust's generics and complex type system often produce code rejected by the eBPF verifier. KernelScript uses fixed-width arrays (`u8[64]`) and simplified types designed for verifier compatibility\n- **Error handling mismatch**: Rust's `Result\u003cT,E\u003e` model doesn't align with eBPF's C-style integer error codes. KernelScript's throw/catch works seamlessly in both userspace and eBPF contexts\n- **Missing eBPF-specific codegen**: Rust/LLVM cannot automatically generate BPF tail calls or kernel module code for `@kfunc` attributes - features that require deep compiler integration\n\n**Why not bpftrace?**\n- Domain-specific for tracing only (no XDP, TC, etc.)\n- Limited programming constructs (no complex data structures, functions)\n- Interpreted at runtime rather than compiled\n- No support for multi-program coordination\n\n**Why not Python/Go eBPF libraries?**\n- Still require writing eBPF programs in C\n- Only handle userspace coordination, not the eBPF programs themselves\n- Complex build systems and dependency management\n\n### KernelScript's Solution\n\nKernelScript addresses these problems through revolutionary language features:\n\n✅ **Single-file multi-target compilation** - Write userspace, eBPF, and kernel module code in one file. The compiler automatically targets each function correctly based on attributes (`@xdp`, `@helper`, regular functions)\n\n✅ **Automatic tail call orchestration** - Simply write `return other_xdp_func(ctx)` and the compiler handles program arrays, `bpf_tail_call()` generation, and error handling automatically\n\n✅ **Transparent dynptr integration** - Use simple pointer operations (`event_log.reserve()`, `buffer[index]`) while the compiler automatically uses complex dynptr APIs (`bpf_ringbuf_reserve_dynptr`, `bpf_dynptr_write`) behind the scenes\n\n✅ **First-class program lifecycle safety** - Programs are typed values with compile-time guarantees that prevent calling `attach()` before `load()` succeeds\n\n✅ **Zero-boilerplate shared state** - Global maps and config blocks are automatically accessible across all programs without imports, exports, or coordination code\n\n✅ **Custom kernel functions (@kfunc)** - Write full-privilege kernel functions that eBPF programs can call, automatically generating kernel modules and BTF registrations\n\n✅ **Unified error handling** - C-style integer throw/catch works seamlessly in both eBPF and userspace contexts, unlike complex Result types\n\n✅ **Verifier-optimized type system** - Fixed-size arrays (`u8[64]`), simple type aliases, and no complex generics that confuse the eBPF verifier\n\n✅ **Complete automated toolchain** - Generate ready-to-use projects with Makefiles, userspace loaders, and build systems from a single source file  \n\n## Language Overview\n\n### Program Types and Contexts\n\nKernelScript supports all major eBPF program types with typed contexts:\n\n```kernelscript\n// XDP program for packet processing\n@xdp fn packet_filter(ctx: *xdp_md) -\u003e xdp_action {\n    var packet_size = ctx-\u003edata_end - ctx-\u003edata\n    if (packet_size \u003e 1500) {\n        return XDP_DROP\n    }\n    return XDP_PASS\n}\n\n// TC program for traffic control\n@tc fn traffic_shaper(ctx: *__sk_buff) -\u003e i32 {\n    if (ctx-\u003elen \u003e 1000) {\n        return TC_ACT_SHOT  // Drop large packets\n    }\n    return TC_ACT_OK\n}\n\n// Kprobe for kernel function tracing\n@kprobe fn trace_syscall(ctx: *pt_regs) -\u003e i32 {\n    // Trace system call entry\n    return 0\n}\n```\n\n### Type System\n\nKernelScript has a rich type system designed for systems programming:\n\n```kernelscript\n// Type aliases for clarity\ntype IpAddress = u32\ntype Counter = u64\ntype PacketSize = u16\n\n// Struct definitions\nstruct PacketInfo {\n    src_ip: IpAddress,\n    dst_ip: IpAddress,\n    protocol: u8,\n    size: PacketSize\n}\n\n// Enums for constants\nenum FilterAction {\n    ALLOW = 0,\n    BLOCK = 1,\n    LOG = 2\n}\n```\n\n### Maps and Data Structures\n\nBuilt-in support for all eBPF map types:\n\n```kernelscript\n// Pinned maps persist across program restarts\npin var connection_count : hash\u003cIpAddress, Counter\u003e(1024)\n\n// Per-CPU maps for better performance\nvar cpu_stats : percpu_array\u003cu32, u64\u003e(256)\n\n// LRU maps for automatic eviction\nvar recent_packets : lru_hash\u003cIpAddress, PacketInfo\u003e(1000)\n\n```\n\n### Functions and Helpers\n\nClean function syntax with helper function support:\n\n```kernelscript\n// Helper functions for eBPF programs\n@helper\nfn extract_src_ip(ctx: *xdp_md) -\u003e IpAddress {\n    // Packet parsing logic\n    return 0x7f000001  // 127.0.0.1\n}\n\n// Regular functions\nfn update_stats(ip: IpAddress, size: PacketSize) {\n    connection_count[ip] = connection_count[ip] + 1\n}\n\n// Function pointers for callbacks\ntype PacketHandler = fn(PacketInfo) -\u003e FilterAction\n\nfn process_packet(info: PacketInfo, handler: PacketHandler) -\u003e FilterAction {\n    return handler(info)\n}\n```\n\n### Pattern Matching and Control Flow\n\nModern control flow with pattern matching:\n\n```kernelscript\n// Pattern matching on enums\nfn handle_action(action: FilterAction) -\u003e xdp_action {\n    return match (action) {\n        ALLOW: XDP_PASS,\n        BLOCK: XDP_DROP,\n        LOG: {\n            // Log and allow\n            event_log[0] = 1\n            XDP_PASS\n        }\n    }\n}\n\n// Truthy/falsy patterns for maps\nfn lookup_or_create(ip: IpAddress) -\u003e Counter {\n    var count = connection_count[ip]\n    if (count != none) {\n        return count  // Entry exists\n    } else {\n        connection_count[ip] = 1  // Create new entry\n        return 1\n    }\n}\n```\n\n### Multi-Program Coordination\n\nKernelScript can coordinate multiple eBPF programs:\n\n```kernelscript\n// Shared map between programs\npin var shared_counter : hash\u003cu32, u32\u003e(1024)\n\n// XDP program increments counter\n@xdp fn packet_counter(ctx: *xdp_md) -\u003e xdp_action {\n    shared_counter[1] = shared_counter[1] + 1\n    return XDP_PASS\n}\n\n// TC program reads counter\n@tc fn packet_reader(ctx: *__sk_buff) -\u003e int {\n    var count = shared_counter[1]\n    if (count \u003e 1000) {\n        return TC_ACT_SHOT  // Rate limiting\n    }\n    return TC_ACT_OK\n}\n\n// Userspace coordination\nfn main() -\u003e i32 {\n    var xdp_prog = load(packet_counter)\n    var tc_prog = load(packet_reader)\n    \n    attach(xdp_prog, \"eth0\", 0)\n    attach(tc_prog, \"eth0\", 0)\n    \n    return 0\n}\n```\n\n📖 **For detailed language specification, syntax reference, and advanced features, please read [`SPEC.md`](SPEC.md).**\n\n## Command Line Usage\n\n### Initialize a New Project\n\nCreate a new KernelScript project with template code:\n\n```bash\n# Create XDP project\nkernelscript init --btf-vmlinux-path /sys/kernel/btf/vmlinux xdp my_packet_filter\n\n# Create TC project  \nkernelscript init --btf-vmlinux-path /sys/kernel/btf/vmlinux tc my_traffic_shaper\n\n# Create kprobe project\nkernelscript init --btf-vmlinux-path /sys/kernel/btf/vmlinux kprobe my_tracer\n\n# Create project with custom BTF path\nkernelscript init --btf-vmlinux-path /custom/path/vmlinux xdp my_project\n\n# Create struct_ops project\nkernelscript init --btf-vmlinux-path /sys/kernel/btf/vmlinux tcp_congestion_ops my_congestion_control\n```\n\nAfter initialization, you get:\n\n```\nmy_project/\n├── my_project.ks          # Generated KernelScript source without user code\n└── README.md              # Usage instructions\n```\n\n**Available program types:**\n- `xdp` - XDP programs for packet processing\n- `tc` - Traffic control programs  \n- `kprobe` - Kernel function tracing\n- `uprobe` - User function tracing\n- `tracepoint` - Kernel tracepoint programs\n- `lsm` - Linux Security Module programs\n- `cgroup_skb` - Cgroup socket buffer programs\n\n**Available struct_ops:**\n- `tcp_congestion_ops` - TCP congestion control\n- `bpf_iter_ops` - BPF iterator operations\n- `bpf_struct_ops_test` - Test struct operations\n- Custom struct_ops names\n\n\n### Compile KernelScript Programs\n\nCompile `.ks` files to eBPF C code and userspace programs:\n\n```bash\n# Basic compilation\nkernelscript compile my_project/my_project.ks\n\n# Specify output directory\nkernelscript compile my_project/my_project.ks -o my_output_dir\nkernelscript compile my_project/my_project.ks --output my_output_dir\n\n# Verbose compilation\nkernelscript compile my_project/my_project.ks -v\nkernelscript compile my_project/my_project.ks --verbose\n\n# Don't generate Makefile\nkernelscript compile my_project/my_project.ks --no-makefile\n\n# Also generates tests and only @test functions become main\nkernelscript compile --test my_project/my_project.ks\n\n# Custom BTF path\nkernelscript compile my_project/my_project.ks --btf-vmlinux-path /custom/path/vmlinux\n```\n\n### Complete Project Structure\n\nAfter compilation, you get a complete project:\n\n```\nmy_project/\n├── my_project.ks          # KernelScript source\n├── my_project.c           # Generated userspace program\n├── my_project.ebpf.c      # Generated eBPF C code\n├── my_project.mod.c       # Generated kernel module (when any kfunc exists)\n├── my_project.test.c      # Generated test run code (when using --test mode)\n├── Makefile               # Build system\n└── README.md              # Usage instructions\n```\n\n### Build and Run\n\n```bash\ncd my_project/\nmake                       # Build both eBPF and userspace programs\nsudo ./my_project          # Run the program\n```\n\n## Getting Started\n\n1. **Install KernelScript:**\n   ```bash\n   git clone https://github.com/multikernel/kernelscript.git\n   cd kernelscript\n   opam install . --deps-only\n   eval $(opam env) \u0026\u0026 dune build \u0026\u0026 dune install\n   ```\n\n2. **Create your first project:**\n   ```bash\n   kernelscript -- init xdp hello_world\n   cd hello_world/\n   ```\n\n3. **Edit the generated code:**\n   ```bash\n   # Edit hello_world.ks with your logic\n   vim hello_world.ks\n   ```\n\n4. **Compile and run:**\n   ```bash\n   kernelscript compile hello_world/hello_world.ks\n   cd hello_world/\n   make\n   sudo ./hello_world\n   ```\n\n## Examples\n\nThe `examples/` directory contains comprehensive examples:\n\n- `packet_filter.ks` - Basic XDP packet filtering\n- `multi_programs.ks` - Multiple coordinated programs\n- `maps_demo.ks` - All map types and operations\n- `functions.ks` - Function definitions and calls\n- `types_demo.ks` - Type system features\n- `error_handling_demo.ks` - Error handling patterns\n\n## Why Choose KernelScript?\n\n| Feature | Raw C + libbpf | Rust eBPF | bpftrace | **KernelScript** |\n|---------|---------------|-----------|----------|------------------|\n| **Syntax** | Complex C | Complex Rust | Simple but limited | Clean \u0026 readable |\n| **Type Safety** | Manual | Yes | Limited | Yes |\n| **Multi-program** | Manual | Manual | No | Automatic |\n| **Build System** | Manual Makefiles | Cargo complexity | N/A | Generated |\n| **Userspace Code** | Manual | Manual | N/A | Generated |\n| **Learning Curve** | Steep | Steep | Easy but limited | Moderate |\n| **Program Types** | All | Most | Tracing only | All |\n\nKernelScript combines the power of low-level eBPF programming with the productivity of modern programming languages, making eBPF development accessible to a broader audience while maintaining the performance and flexibility that makes eBPF powerful.\n\n## License\n\nCopyright 2025 Multikernel Technologies, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n## Contributing\n\nBy contributing to this project, you agree that your contributions will be licensed under the Apache License 2.0.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmultikernel%2Fkernelscript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmultikernel%2Fkernelscript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmultikernel%2Fkernelscript/lists"}