diff --git a/.github/actions/build-linux/action.yml b/.github/actions/build-linux/action.yml index 004ae920..9304fd44 100644 --- a/.github/actions/build-linux/action.yml +++ b/.github/actions/build-linux/action.yml @@ -23,8 +23,8 @@ runs: - if: steps.cache.outputs.cache-hit != 'true' shell: bash - # `clean --all` drops the kbuild objects before caching; the image and Module.symvers survive it + # `make clean` drops the kbuild objects before caching; .config, Module.symvers and the generated headers survive it, which is all the kmod build needs run: | - ./checkout.py ${{ inputs.version }} --tar - ./make.py --build ${{ inputs.version }} linux ${{ inputs.cov == 'true' && '--config linux/config.kstep.cov' || '' }} - ./make.py --build ${{ inputs.version }} clean --all + ./kstep.sh checkout ${{ inputs.version }} + ./kstep.sh build ${{ inputs.version }} --linux ${{ inputs.cov == 'true' && '--config linux/config.kstep.cov' || '' }} + make -C build/${{ inputs.version }}/linux clean diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1756230d..a38edf41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,18 +13,33 @@ env: jobs: deps: - name: Cache deps (${{ matrix.arm && 'aarch64' || 'x86_64' }}) + name: Deps (${{ matrix.arm && 'aarch64' || 'x86_64' }}) strategy: matrix: arm: [false, true] runs-on: ${{ matrix.arm && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }} steps: - uses: actions/checkout@v6 - - name: Cache deps + + - name: Cache apt packages uses: ./.github/actions/apt-deps with: packages: ${{ matrix.arm && env.PACKAGES_AARCH64 || env.PACKAGES_X86_64 }} + # target/ and the registry, shared with the test jobs (same key), saved only here + - name: Cache Rust + uses: Swatinem/rust-cache@v2 + with: + shared-key: kstep + - name: Build Rust + run: cargo build --workspace --release --locked + - name: Format + run: cargo fmt --all --check + - name: Lint + run: cargo clippy --workspace --all-targets --release --locked -- -D warnings + - name: Test + run: cargo test --workspace --release --locked + test: needs: deps name: ${{ matrix.fuzz && 'Fuzz' || 'Run' }} ${{ matrix.version }} (${{ matrix.arm && 'aarch64' || 'x86_64' }}) @@ -44,6 +59,13 @@ jobs: runs-on: ${{ matrix.arm && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }} steps: - uses: actions/checkout@v6 + - uses: Swatinem/rust-cache@v2 + with: + shared-key: kstep + save-if: false + + - name: Build kstep CLI + run: cargo build --release --locked -p kstep - name: Install deps uses: ./.github/actions/apt-deps @@ -58,35 +80,26 @@ jobs: cov: ${{ matrix.fuzz }} - name: Build kSTEP - run: ./make.py --build ${{ matrix.version }} kstep + run: ./kstep.sh build ${{ matrix.version }} + + # GitHub's x86_64 runners have nested virtualisation, but /dev/kvm is root-only; the arm + # runners have no /dev/kvm, and QEMU falls back to TCG + - name: Enable KVM + run: '[ -e /dev/kvm ] && sudo chmod 666 /dev/kvm || true' - - name: "[Run] Execute driver" + - name: "[Run] A cli session" if: ${{ ! matrix.fuzz }} - timeout-minutes: 1 - run: ./run.py --build ${{ matrix.version }} + timeout-minutes: 2 + run: printf 'create 2\ntick 5\npolicy-rt 1 fifo 50\ntick 5\n' | ./kstep.sh run ${{ matrix.version }} - - name: "[Run] Show driver output" + - name: "[Run] Show the driver's records" if: ${{ ! matrix.fuzz }} run: cat results/latest/kstep.jsonl - # - name: "[Fuzz] Execute workers" - # if: ${{ matrix.fuzz }} - # timeout-minutes: 5 - # run: | - # ./fuzz.py \ - # --build ${{ matrix.version }} \ - # --workers 1 \ - # --steps 10 \ - # --ci_mode - - # - name: "[Fuzz] Show fresh-mode log" - # if: ${{ matrix.fuzz }} - # run: cat results/fuzz/fresh/worker.debug.log - - # - name: "[Fuzz] Show replay-mode log" - # if: ${{ matrix.fuzz }} - # run: cat results/fuzz/replay/worker.debug.log + - name: Show the kernel log + if: ${{ failure() }} + run: cat results/latest/kernel.log - # - name: "[Fuzz] Show mutation-mode log" - # if: ${{ matrix.fuzz }} - # run: cat results/fuzz/mutation/worker.debug.log + - name: "[Fuzz] Build the fuzzer" + if: ${{ matrix.fuzz }} + run: cargo build --release --locked -p kstep-fuzz diff --git a/.gitignore b/.gitignore index 52f3ef3d..308584f9 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ __pycache__ .cache # Build artifacts -build/ -fuzzer/target -fuzzer/out +/build/ +/fuzz + +# Rust +/target diff --git a/AGENTS.md b/AGENTS.md index 04f6b6d2..1aa1654d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ To reproduce a bug fixed in commit `[hash]`, follow these steps: #### Planning Stage -- Check out the Linux source code just before the fix: `./checkout.py [hash]~1 [name]_buggy --git`. +- Check out the Linux source code just before the fix: `./kstep.sh checkout [hash]~1 [name]_buggy --git`. - Read the commit message and patch carefully: `git -C build/master show -U32 [hash]`. - Carefully analyze the changes introduced in the patch, focusing on modifications in `build/master/kernel/sched`. Trace the call chain that leads to the bug, ensuring you understand the purpose of each function and how they interact. Clearly identify the conditions and system state required to trigger the bug. - If the commit message contains links, carefully review the content of ALL links as they may provide the additional information about the bug (especially the reproduction conditions). For LKML links (e.g., `lore.kernel.org`, `lkml.kernel.org`, `patch.msgid.link`), extract the email ID and retrieve the message with: @@ -18,12 +18,12 @@ To reproduce a bug fixed in commit `[hash]`, follow these steps: - Try not to directly manipulate internal scheduler state. - Add detailed logging in your driver for all relevant fields to aid debugging. If necessary, add kernel-side logging with `printk()`. - Build and execute the driver on the buggy kernel with: - `./checkout.py [hash]~1 [name]_buggy --git && ./make.py --build [name]_buggy linux && ./run.py [driver_name] --build [name]_buggy` + `./kstep.sh checkout [hash]~1 [name]_buggy --git && ./kstep.sh run [name]_buggy [driver_name]` - Determine whether the bug is reproduced by examining the output logs: - `cat data/logs/latest.log` + `cat results/latest/kernel.log` and `results/latest/kstep.jsonl` - If you do not observe the bug, refine your implementation and repeat the process. - After confirming that your driver triggers the bug, rerun the same driver on the fixed kernel: - `./checkout.py [hash] [name]_fixed --git && ./make.py --build [name]_fixed linux && ./run.py [driver_name] --build [name]_fixed` + `./kstep.sh checkout [hash] [name]_fixed --git && ./kstep.sh run [name]_fixed [driver_name]` - Review the logs to ensure the bug no longer occurs. In rare cases where the issue persists despite the fix, provide clear documentation and report your findings. #### Refinement Stage @@ -31,7 +31,7 @@ To reproduce a bug fixed in commit `[hash]`, follow these steps: - If you manually altered internal scheduler state to trigger the bug during the triggering stage, refine your driver to reproduce the bug using only public kernel APIs or kSTEP interfaces (`kmod/driver.h`). If needed, consider extending kSTEP to provide the required functionality. - Make sure that the driver is deterministic, and produce the same trace on the same kernel. If not, investigate the root cause of the non-determinism. - After confirming your driver can trigger the bug, clearly demonstrate its impact through externally observable behavior, such as changes in task scheduling, rather than relying solely on kernel-internal state. -- Once complete, add your driver to BUGS_EXTRA in `reproduce.py` to enable automated testing. +- Once complete, add an entry for your driver to `bugs.yaml` (with `extra: true`) to enable automated testing. ## Coding Style diff --git a/fuzzer/Cargo.lock b/Cargo.lock similarity index 75% rename from fuzzer/Cargo.lock rename to Cargo.lock index ba1b289c..d03ccd93 100644 --- a/fuzzer/Cargo.lock +++ b/Cargo.lock @@ -38,6 +38,71 @@ dependencies = [ "memchr", ] +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "arbitrary-int" version = "2.2.0" @@ -85,6 +150,26 @@ dependencies = [ "virtue", ] +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bitbybit" version = "2.0.1" @@ -125,11 +210,30 @@ version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +[[package]] +name = "cc" +version = "1.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" +dependencies = [ + "find-msvc-tools", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" @@ -137,6 +241,68 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + [[package]] name = "cobs" version = "0.3.0" @@ -146,6 +312,12 @@ dependencies = [ "thiserror", ] +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "const_format" version = "0.2.36" @@ -176,6 +348,12 @@ dependencies = [ "typewit", ] +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "core_affinity2" version = "0.16.1" @@ -199,6 +377,12 @@ dependencies = [ "linktime-proc-macro", ] +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + [[package]] name = "embedded-io" version = "0.4.0" @@ -211,6 +395,12 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + [[package]] name = "erased-serde" version = "0.4.10" @@ -261,6 +451,12 @@ dependencies = [ "siphasher", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" + [[package]] name = "foldhash" version = "0.2.0" @@ -318,6 +514,12 @@ version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "hashbrown" version = "0.17.1" @@ -329,6 +531,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hostname" version = "0.4.2" @@ -340,6 +548,57 @@ dependencies = [ "windows-link", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -373,9 +632,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" [[package]] -name = "kstep-fuzzer" +name = "kstep" version = "0.1.0" dependencies = [ + "anyhow", + "chrono", + "clap", + "indexmap", + "kstep-core", + "libc", + "serde", + "serde_json", + "serde_yaml_ng", +] + +[[package]] +name = "kstep-core" +version = "0.1.0" +dependencies = [ + "bindgen", + "serde", + "serde-wasm-bindgen", + "wasm-bindgen", +] + +[[package]] +name = "kstep-fuzz" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "kstep", + "kstep-core", "libafl", "libafl_bolts", ] @@ -489,7 +777,7 @@ checksum = "667f4c0ed30fb0c785f3e5b679c11e9b41ecf5fe964a372cda29deae6cb7316a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", ] [[package]] @@ -498,6 +786,16 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + [[package]] name = "libm" version = "0.2.16" @@ -596,6 +894,12 @@ dependencies = [ "windows", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -636,6 +940,16 @@ dependencies = [ "rustversion", ] +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nonzero_macros" version = "0.16.1" @@ -687,6 +1001,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "ownedref" version = "0.16.1" @@ -745,6 +1065,16 @@ dependencies = [ "serde", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -819,12 +1149,24 @@ version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "safe_arch" version = "1.2.0" @@ -850,6 +1192,17 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + [[package]] name = "serde_anymap" version = "0.16.1" @@ -883,7 +1236,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", ] [[package]] @@ -899,6 +1252,19 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_yaml_ng" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serial_test" version = "4.0.1" @@ -919,9 +1285,21 @@ checksum = "a22144e767da4ddd8416dbf383700542ffd8a5dc493dfecedfe1fe3ad03c98ae" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "shmem_providers" version = "0.16.1" @@ -967,6 +1345,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "syn" version = "2.0.119" @@ -980,9 +1364,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.5" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" dependencies = [ "proc-macro2", "quote", @@ -1006,7 +1390,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", ] [[package]] @@ -1072,9 +1456,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" [[package]] name = "unicode-xid" @@ -1082,12 +1466,24 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + [[package]] name = "unty" version = "0.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.26.1" @@ -1153,7 +1549,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", "wasm-bindgen-shared", ] @@ -1168,9 +1564,9 @@ dependencies = [ [[package]] name = "wide" -version = "1.7.0" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cf05ca94c9fba0c51316899caa1d1e74a064fc310a5efa7375e614343d415be" +checksum = "d920ac99c3c8edce110cb8d07dbb324d6d026011dce85b1e9355b70f0adacc4f" dependencies = [ "bytemuck", "safe_arch", @@ -1299,6 +1695,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-threading" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..754eb7ba --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,34 @@ +# kSTEP's host-side tooling. Everything that used to be Python glue around git, make, gcc and +# QEMU lives here; plotting stays in scripts/ (matplotlib) and reads what the kstep binary writes. +# +# ./kstep.sh ... +# +# crates/core kstep-core: what the wasm page shares with the binaries (shm decoder, QEMU argv) +# crates/kstep the `kstep` binary and its library (checkout, build, bugs.yaml, results, sessions) +# crates/fuzz kstep-fuzz: the LibAFL fuzzer, a client of the library; not a default member, so a +# plain `cargo build` never compiles LibAFL (`cargo build -p kstep-fuzz` does) +[workspace] +resolver = "2" +members = ["crates/*"] +default-members = ["crates/core", "crates/kstep"] +exclude = ["build", "website"] + +[workspace.package] +version = "0.1.0" +edition = "2021" +rust-version = "1.88" # slice::as_chunks +license = "MIT" +repository = "https://github.com/kstep-dev/kstep" + +# Symbols in optimized binaries: the fuzzer's panics and perf profiles should name functions. +[profile.release] +debug = 1 + +# The website's decoder: small above all +[profile.wasm] +inherits = "release" +debug = 0 +opt-level = "z" +lto = true +codegen-units = 1 +panic = "abort" diff --git a/README.md b/README.md index 75adedc1..12648885 100644 --- a/README.md +++ b/README.md @@ -21,16 +21,16 @@ git clone --recurse-submodules https://github.com/kstep-dev/kstep && cd kstep ```sh # 💾 Install dependencies -./install_deps.sh +./setup.sh ``` ```sh # 🐞 Reproduce bugs -# ./reproduce.py [--run ] -# 1. Checks out the buggy and/or fixed kernels -# 2. Builds and runs the specified driver (or all drivers) -# 3. Plots the results -./reproduce.py sync_wakeup +# ./kstep.sh reproduce [--steps buggy fixed plot] +# 1. Checks out the buggy and fixed kernels +# 2. Builds and runs the bug's driver on each +# 3. Plots the two traces +./kstep.sh reproduce sync_wakeup ``` ## 📊 Results @@ -58,35 +58,33 @@ For driver development, please refer to [AGENTS.md](AGENTS.md) for recommended w #### 🐧 Checkout Linux source code ```sh -./checkout.py [] [--tar | --git] +./kstep.sh checkout [] [--git] [--patch ] [--keep-current] ``` -- ``: Linux tag (e.g., `v6.14`) or commit hash (e.g., `6d7e478`, `5068d84~1`). -- `--tar` (default): download tarball from kernel.org / GitHub (fast, one-shot). -- `--git`: add a worktree from `build/master` (multi-version dev, supports `git log`/`git diff`). - -- **Example:** `./checkout.py v6.14 foo_buggy` checks out Linux v6.14 under `build/foo_buggy/linux/` and points `build/current` at `build/foo_buggy/`. +- ``: Linux tag (e.g., `v6.14`) or commit hash (e.g., `6d7e478`, `5068d84~1`). +- Default: download a tarball from kernel.org / GitHub (fast, one-shot). `--git`: add a worktree of `build/master` (multi-version dev, supports `git log`/`git diff`). +- **Example:** `./kstep.sh checkout v6.14 foo_buggy` checks out Linux v6.14 under `build/foo_buggy/linux/` and points `build/current` at `build/foo_buggy/`. #### 🛠️ Build kSTEP ```sh -./make.py [--build ] # Build kSTEP rootfs (kmod + user). Builds the kernel first if needed. -./make.py [--build ] linux # Full kernel build. Run this after Linux file changes. +./kstep.sh build [] # kmod + user + rootfs.cpio; builds the kernel first if needed +./kstep.sh build [] --linux [--config F] # reconfigure and rebuild the kernel; run after Linux file changes ``` -- `[--build ]`: build directory name under `build/`; defaults to whatever `build/current` points to. +- `[]`: build directory under `build/`; defaults to whatever `build/current` points to. A bug's build (`_buggy`, `_fixed`) or a Linux version (`v6.18`) is checked out first if missing. #### 🏃‍♂️ Run kSTEP ```sh -./run.py [--num_cpus ] [--mem_mb ] [--build ] [--label ] +./kstep.sh run [] [] [--num-cpus ] [--mem-mb ] [-o ] [-i ] ``` -- ``: Driver to run (see `*.c` files in [`kmod/drivers/`](kmod/drivers/)). -- `[--build ]`: kernel build to run against (defaults to `build/current`). -- `[--label ]`: subdir under `results/` for output; defaults to a timestamped `tmp_*` dir. `results/latest` symlinks to it. -- See `./run.py --help` for `--topology`, `--frequency`, `--capacity`, `--debug`, etc. +- `[]`: kernel build to run against (defaults to `build/current`). A bug's build, `_buggy` or `_fixed`, brings the bug's driver and machine from `bugs.yaml`. +- `[]`: driver to run (see `*.c` files in [`kmod/drivers/`](kmod/drivers/)); defaults to `cli`, an interactive session: type commands (listed at the top of [`kmod/cli.c`](kmod/cli.c)), see the machine after each. `-i ` or a pipe scripts one. +- `[-o ]`: subdir under `results/` for output; defaults to a timestamped `tmp_*` dir. `results/latest` symlinks to it. +- `--debug` starts the guest stopped with a gdb stub; `./kstep.sh gdb []` attaches. -- **Example:** `./run.py sync_wakeup` runs the `sync_wakeup` driver with default parameters. +- **Example:** `./kstep.sh run sync_wakeup_buggy` runs the `sync_wakeup` driver on its buggy kernel, checking it out and building it first if needed. ## 📁 Directory Structure @@ -106,16 +104,16 @@ For driver development, please refer to [AGENTS.md](AGENTS.md) for recommended w - `*.patch`: Fixes for specific bugs - **build/**: Per-kernel build artifacts (gitignored, regenerable) - - `current`: symlink to the active `/` (set by `checkout.py`) - - `master/`: bare kernel clone reused by `checkout.py --git` + - `current`: symlink to the active `/` (set by `kstep checkout`) + - `master/`: kernel clone reused by `kstep checkout --git` - `user`: statically linked userspace binary - `/`: `kernel` (the image QEMU boots: the bzImage on x86, the Image on arm64; plus `vmlinux` for gdb/addr2line) and `rootfs.cpio` (kmod.ko + user); `linux/` source tree; `kmod/` module build dir with `kmod.ko` and the clangd `compile_commands.json` (the project root symlinks to it) - **results/**: Run outputs. See [`results/README.md`](https://github.com/kstep-dev/results). `repro_/` is tracked; `tmp_*` are gitignored. The fuzzer's per-client runs land in `fuzz__/`. -- **fuzzer/**: LibAFL fuzzer (`./fuzz.sh `), a host-side client of the `cli` driver; corpora and findings under `fuzzer/out/` (gitignored) - - the earlier in-guest fuzzer it replaced is kept for reference in [`docs/archive/old_fuzzer/`](docs/archive/old_fuzzer/) +- **crates/**: the Rust tooling. `core/` is what the website's wasm decoder shares with the binaries (the `kmod/shm.h` decoder, generated from the header, and the QEMU command line); `kstep/` is the `kstep` command (`./kstep.sh`): checkout, build, run, reproduce, viz; `fuzz/` is the LibAFL fuzzer (`./kstep-fuzz.sh `), a host-side client of the `cli` driver, with corpora and findings under `fuzz/` (gitignored) + - the earlier in-guest fuzzer is kept for reference in [`docs/archive/old_fuzzer/`](docs/archive/old_fuzzer/) -- **scripts/**: Python utilities for log parsing and plotting. +- **scripts/**: the plot scripts (Python, self-contained: `uv run --script scripts/plot_.py `), which `kstep reproduce` runs. -- **bugs.yaml**: one entry per bug -- how to build, run, reproduce and fuzz it; read by `reproduce.py`, `run.py --bug` and the fuzzer +- **bugs.yaml**: one entry per bug -- how to build, run, reproduce and fuzz it; read by `kstep run`, `kstep reproduce` and the fuzzer diff --git a/bugs.yaml b/bugs.yaml index a6503343..e793f037 100644 --- a/bugs.yaml +++ b/bugs.yaml @@ -1,13 +1,14 @@ # The bugs kSTEP reproduces and fuzzes: one entry per bug, the single place that records what a -# bug needs. Loaded by reproduce.py, which `run.py --bug X` (the X driver, or `run.py cli --bug X`, -# on X's machine) and `kstep-fuzzer X` read through. Kernels live in build/_buggy and +# bug needs. Read by `kstep reproduce X`, `kstep run X_buggy` (the X driver on X's machine; `kstep +# run X_fixed cli` for a session there) and `kstep-fuzz X`. Kernels live in build/_buggy and # build/_fixed. Fields: # fix the fix commit; buggy = fix~1, fixed = fix # ref, patch or: buggy = ref, fixed = ref + linux/ +# upstream_fix with ref + patch: the commit that later fixed it upstream (shown by the website) # config extra kernel config fragment to merge # extra true for the bugs outside the paper's main table # plot_format scripts/plot_.py draws the reproduction -# num_cpus, mem_mb the machine (run.py Driver fields); capacity, topology and frequency +# num_cpus, mem_mb the machine; capacity, topology and frequency # are cli verbs, so they belong in fuzz.setup # fuzz: what the fuzzer needs beyond the machine # checks checkers/ rules to enable @@ -19,6 +20,7 @@ sync_wakeup: ref: v6.14 patch: sync_wakeup.patch + upstream_fix: aa3ee4f0b7541382c9f6f43f7408d73a5d4f4042 num_cpus: 3 plot_format: curr_task fuzz: diff --git a/checkout.py b/checkout.py deleted file mode 100755 index e1eb0eee..00000000 --- a/checkout.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import logging -from dataclasses import dataclass -from pathlib import Path - -from scripts import ( - BUILD_CURR_DIR, - BUILD_DIR, - PROJ_DIR, - decompress, - download, - system, -) - -LINUX_MASTER_DIR = BUILD_DIR / "master" -LINUX_MASTER_URL = "https://github.com/gregkh/linux.git" - - -@dataclass(frozen=True) -class Linux: - # A descriptive name for the Linux build - name: str - # Git ref (tag/branch/commit) of the kernel to use - ref: str - # The patch to apply to the kernel - patch: Path | None = None - # Extra kernel config fragment to merge - config: Path | None = None - - -def fmt_path(path: Path) -> str: - return f"`{path.relative_to(PROJ_DIR)}`" - - -def add_worktree(ref: str, linux_dir: Path): - if not LINUX_MASTER_DIR.exists(): - system(f"git clone --filter=blob:none {LINUX_MASTER_URL} {LINUX_MASTER_DIR}") - system(f"cd {LINUX_MASTER_DIR} && git fetch") - system(f"cd {LINUX_MASTER_DIR} && git worktree prune -v") - system(f"cd {LINUX_MASTER_DIR} && git worktree add {linux_dir} {ref}") - - -def set_current_build(kernel: str): - BUILD_CURR_DIR.parent.mkdir(parents=True, exist_ok=True) - BUILD_CURR_DIR.unlink(missing_ok=True) - BUILD_CURR_DIR.symlink_to(BUILD_DIR / kernel) - - -def get_download_url(ref: str) -> str: - if "." in ref: - ref = ref.removeprefix("v") - major = ref.split(".", 1)[0] - return f"https://cdn.kernel.org/pub/linux/kernel/v{major}.x/linux-{ref}.tar.xz" - else: - return f"https://github.com/torvalds/linux/archive/{ref}.tar.gz" - - -def patch_linux(linux_dir: Path, patch: Path): - system(f"cd {linux_dir} && patch -p1 --forward --batch < {patch}") - - -def checkout( - ref: str, - kernel: str, - patch: Path | None = None, - tarball: bool = False, - set_current: bool = True, -): - linux_dir = BUILD_DIR / kernel / "linux" - if not linux_dir.exists(): - linux_dir.parent.mkdir(parents=True, exist_ok=True) - if tarball: - tarball_path = BUILD_DIR / kernel / f"{ref}.tar.xz" - url = get_download_url(ref) - download(url, tarball_path) - decompress(tarball_path, linux_dir) - else: - add_worktree(ref, linux_dir) - - if patch: - patch_linux(linux_dir, patch) - if set_current: - set_current_build(kernel) - logging.info(f"Build {fmt_path(BUILD_DIR / kernel)} (Linux {ref}) is now current") - else: - logging.info(f"Build {fmt_path(BUILD_DIR / kernel)} (Linux {ref}) checked out") - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("ref", type=str, nargs="?", default="v6.18") - parser.add_argument("kernel", type=str, nargs="?", default=None) - source = parser.add_mutually_exclusive_group() - source.add_argument("--tar", dest="tarball", action="store_true", default=True) - source.add_argument("--git", dest="tarball", action="store_false") - parser.add_argument("--patch", type=Path, default=None) - parser.add_argument("--no-current", dest="set_current", action="store_false", help="leave build/current alone") - args = parser.parse_args() - - checkout( - ref=args.ref, - kernel=args.kernel if args.kernel else args.ref, - tarball=args.tarball, - patch=args.patch, - set_current=args.set_current, - ) diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml new file mode 100644 index 00000000..27a187eb --- /dev/null +++ b/crates/core/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "kstep-core" +description = "kSTEP's shared library: shared-memory decoder and QEMU command line" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[lib] +crate-type = ["rlib", "cdylib"] # cdylib for the wasm build + +[dependencies] +serde = { version = "1", features = ["derive"] } +wasm-bindgen = { version = "0.2", optional = true } +serde-wasm-bindgen = { version = "0.6", optional = true } + +[build-dependencies] +bindgen = "0.72" + +[features] +# The website's module: cargo build -p kstep-core --profile wasm --target wasm32-unknown-unknown --features wasm +wasm = ["dep:wasm-bindgen", "dep:serde-wasm-bindgen"] diff --git a/crates/core/build.rs b/crates/core/build.rs new file mode 100644 index 00000000..51beb53d --- /dev/null +++ b/crates/core/build.rs @@ -0,0 +1,23 @@ +//! kmod/shm.h -> Rust, so the header stays the only description of the shared region. The +//! header wants the kernel's fixed-width typedefs; include/ shims them, so no kernel tree is +//! needed. bindgen also emits layout tests: `cargo test` holds the structs to clang's offsets. + +use std::path::PathBuf; + +fn main() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let header = root.join("../../kmod/shm.h"); + println!("cargo:rerun-if-changed={}", header.display()); + println!("cargo:rerun-if-changed=include"); + bindgen::Builder::default() + .header(header.to_str().unwrap()) + .clang_arg(format!("-I{}", root.join("include").display())) + .allowlist_item("kstep_.*|KSTEP_.*") + .prepend_enum_name(false) + .layout_tests(true) // clang's offsets, checked by `cargo test` + .derive_default(true) + .generate() + .expect("bindgen kmod/shm.h") + .write_to_file(PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("shm_h.rs")) + .expect("write bindings"); +} diff --git a/crates/core/include/linux/types.h b/crates/core/include/linux/types.h new file mode 100644 index 00000000..d066a77b --- /dev/null +++ b/crates/core/include/linux/types.h @@ -0,0 +1,4 @@ +// The kernel typedefs kmod/shm.h uses, from the compiler's own macros: no sysroot needed, so +// bindgen works for any target (the wasm32 build included). +typedef __UINT8_TYPE__ u8; typedef __UINT16_TYPE__ u16; typedef __UINT32_TYPE__ u32; typedef __UINT64_TYPE__ u64; +typedef __INT8_TYPE__ s8; typedef __INT16_TYPE__ s16; typedef __INT32_TYPE__ s32; typedef __INT64_TYPE__ s64; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs new file mode 100644 index 00000000..56317b8d --- /dev/null +++ b/crates/core/src/lib.rs @@ -0,0 +1,7 @@ +//! Shared by the `kstep` CLI, the fuzzer and (through wasm) the website: the shm decoder and the +//! QEMU command line. No clap, no LibAFL. + +pub mod qemu; +pub mod shm; +#[cfg(feature = "wasm")] +mod wasm; diff --git a/crates/core/src/qemu.rs b/crates/core/src/qemu.rs new file mode 100644 index 00000000..e0be8816 --- /dev/null +++ b/crates/core/src/qemu.rs @@ -0,0 +1,388 @@ +//! Everything about QEMU in one place: what differs between x86_64 and aarch64, the kernel +//! command line, and the argv (never a shell string) for one kSTEP boot, natively (KVM when +//! /dev/kvm is usable, TCG otherwise) or in the website's Emscripten build; they differ only in +//! where the channels go. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// A guest arch. Natively it is the host's (`ARCH`): kSTEP never cross-compiles or +/// cross-emulates; the website's QEMU is always aarch64. Every arch-specific fact lives here. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Arch { + X86_64, + Aarch64, +} + +#[cfg(target_arch = "x86_64")] +pub const ARCH: Arch = Arch::X86_64; +#[cfg(target_arch = "aarch64")] +pub const ARCH: Arch = Arch::Aarch64; + +impl Arch { + /// As `uname -m` spells it: the config fragment suffix and the qemu-system binary + pub const fn name(self) -> &'static str { + match self { + Arch::X86_64 => "x86_64", + Arch::Aarch64 => "aarch64", + } + } + /// The image QEMU boots, relative to the kernel tree + pub const fn kernel_image(self) -> &'static str { + match self { + Arch::X86_64 => "arch/x86/boot/bzImage", + Arch::Aarch64 => "arch/arm64/boot/Image", + } + } + /// Guest-physical address of the first byte of RAM: offset 0 of a RAM file + pub const fn ram_base(self) -> u64 { + match self { + Arch::X86_64 => 0, + Arch::Aarch64 => 0x4000_0000, + } + } + /// QEMU's machine type; None for the arch's default (pc) + const fn machine(self) -> Option<&'static str> { + match self { + Arch::X86_64 => None, + Arch::Aarch64 => Some("virt"), + } + } + /// The CPU model under TCG (KVM uses `host`) + const fn tcg_cpu(self) -> &'static str { + match self { + Arch::X86_64 => "max", + Arch::Aarch64 => "cortex-a57", + } + } + /// The virtio-serial transport: PCI on pc, MMIO on virt (no PCI host there) + const fn virtio_serial(self) -> &'static str { + match self { + Arch::X86_64 => "virtio-serial-pci", + Arch::Aarch64 => "virtio-serial-device", + } + } + /// The kernel console on the machine's UART, and what the clock needs under emulation + const fn console_args(self) -> &'static [&'static str] { + match self { + Arch::X86_64 => &["console=ttyS0", "tsc=nowatchdog", "tsc=reliable"], + Arch::Aarch64 => &["console=ttyAMA0"], + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Machine { + pub num_cpus: u32, + pub mem_mb: u32, +} + +impl Default for Machine { + fn default() -> Self { + Machine { + num_cpus: 2, + mem_mb: 512, + } + } +} + +/// KVM when /dev/kvm can be opened read-write (what KVM_CREATE_VM needs); never in the browser. +pub fn kvm_available() -> bool { + cfg!(not(target_arch = "wasm32")) + && std::fs::OpenOptions::new() + .read(true) + .write(true) + .open("/dev/kvm") + .is_ok() +} + +/// A two-way channel at `path`: natively a unix socket QEMU serves there (clients connect and +/// go); in the browser the pipe device node kstep.mjs registers there. +#[cfg(not(target_arch = "wasm32"))] +fn served(path: &Path) -> String { + format!("socket,path={},server=on,wait=off", path.display()) +} +#[cfg(target_arch = "wasm32")] +fn served(path: &Path) -> String { + format!("pipe,path={}", path.display()) +} + +/// One kSTEP boot, native or in the browser. +#[derive(Debug, Clone)] +pub struct Boot { + /// The guest's arch: the host's natively, aarch64 in the browser + pub arch: Arch, + pub kernel: PathBuf, + pub rootfs: PathBuf, + pub driver: String, + pub machine: Machine, + /// Where the three channels go: the kernel's console output, and two-way, kSTEP's own + /// (kmod/io.c: a virtio console port the kmod drives, the driver's records out and the + /// cli's commands in) and QEMU's monitor. Natively under the results dir, the last two unix + /// sockets; in the browser, Emscripten device nodes kstep.mjs registers under these names, + /// the log a write-only file, the "sockets" pipes (Emscripten has no unix sockets). + pub kernel_log: PathBuf, + pub kstep_socket: PathBuf, + pub monitor_socket: PathBuf, + /// Every record the driver wrote (results/kstep.jsonl, the published transcript). None in + /// the browser, which keeps the stream itself. + pub kstep_log: Option, + /// Natively: the console on the terminal too, with the monitor multiplexed in (ctrl-a c) + pub terminal: bool, + /// Start stopped with the gdb stub on :1234 + pub debug: bool, + /// Back guest RAM with this shared file so the host can read kmod/shm.h out of it + pub ram_file: Option, + /// Resume from this migration stream (`migrate file:...` on the monitor, taken at the driver's + /// ready line) instead of booting the kernel: the website skips the ~4 s boot this way + pub snapshot: Option, +} + +impl Boot { + /// Machine, accelerator, CPU, memory, kernel, command line, kSTEP's channel (one virtio + /// console port whose virtqueues the kmod drives itself, kmod/io.c: one kick per record + /// instead of one port I/O exit per byte on a 16550), then where the channels go. QEMU + /// creates chardevs before devices, whatever the order. + pub fn argv(&self) -> Vec { + let mut machine: Vec<&str> = self.arch.machine().into_iter().collect(); + if self.ram_file.is_some() { + machine.push("memory-backend=ram"); + } + let mut argv: Vec = vec![]; + if !machine.is_empty() { + argv.extend(["-machine".into(), machine.join(",")]); + } + if let Some(ram) = &self.ram_file { + let m = self.machine.mem_mb; + argv.extend([ + "-object".into(), + format!( + "memory-backend-file,id=ram,size={m}M,mem-path={},share=on", + ram.display() + ), + ]); + } + // KVM where the host offers it, else TCG: one host thread per vCPU (MTTCG) and a 64 MB + // translation cache, enough for kSTEP's small kernels and what fits next to guest RAM in + // the website's 1 GB wasm heap + let (accel, cpu) = if kvm_available() { + ("kvm", "host") + } else { + ("tcg,tb-size=64,thread=multi", self.arch.tcg_cpu()) + }; + argv.extend( + [ + "-accel", + accel, + "-cpu", + cpu, + "-smp", + &self.machine.num_cpus.to_string(), + "-m", + &format!("{}M", self.machine.mem_mb), + ] + .map(String::from), + ); + // A snapshot restores RAM, so the kernel, initrd and command line it was booted with are + // not loaded again; the machine and devices must match what it was taken on. + match &self.snapshot { + Some(snap) => argv.extend(["-incoming".into(), format!("file:{}", snap.display())]), + None => argv.extend([ + "-kernel".into(), + self.kernel.display().to_string(), + "-initrd".into(), + self.rootfs.display().to_string(), + "-append".into(), + self.cmdline(), + ]), + } + argv.extend( + [ + "-nographic", + "-nodefaults", + "-no-reboot", // no automatic reboot after a panic + "-serial", + "chardev:console", + "-device", + &format!("{},id=vs0", self.arch.virtio_serial()), + "-device", + "virtconsole,bus=vs0.0,nr=0,chardev=port", + ] + .map(String::from), + ); + argv.extend(self.channels()); + if self.debug { + argv.extend(["-s".into(), "-S".into()]); + } + argv + } + + /// The chardevs `console`, `port` and `monitor` (QEMU's names: the serial console, the virtio + /// console port, the monitor) at the three paths. The kernel log is a file either way; the + /// two-way channels are served as the build allows. + fn channels(&self) -> Vec { + let mut argv = if self.terminal { + // the console on the terminal too, with the monitor multiplexed in (ctrl-a c) + vec![ + "-chardev".to_string(), + format!( + "stdio,id=console,mux=on,logfile={},signal=off", + self.kernel_log.display() + ), + "-mon".into(), + "chardev=console".into(), + ] + } else { + vec![ + "-chardev".to_string(), + format!("file,id=console,path={}", self.kernel_log.display()), + ] + }; + let log = match &self.kstep_log { + Some(log) => format!(",logfile={}", log.display()), + None => String::new(), + }; + argv.extend([ + "-chardev".into(), + format!("{}{log},id=port", served(&self.kstep_socket)), + "-chardev".into(), + format!("{},id=monitor", served(&self.monitor_socket)), + "-monitor".into(), + "chardev:monitor".into(), + ]); + argv + } + + /// The kernel command line: CPU 0 runs the driver, the rest are isolated for the test. After + /// `--`, the kmod's one parameter, the driver to run. + /// https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html + pub fn cmdline(&self) -> String { + let num_cpus = self.machine.num_cpus; + let isol = if num_cpus > 2 { + format!("1-{}", num_cpus - 1) + } else { + "1".to_string() + }; + let mut args = vec![ + "rw".to_string(), + "nokaslr".into(), + "loglevel=7".into(), // up to KERN_DEBUG, so KERN_WARNING always appears + "sched_verbose".into(), + format!("isolcpus=nohz,managed_irq,{isol}"), + "irqaffinity=0".into(), + format!("rcu_nocbs={isol}"), + format!("nohz_full={isol}"), + "init=/user".into(), + "panic=-1".into(), // exit immediately on panic + ]; + args.extend(self.arch.console_args().iter().map(|s| s.to_string())); + args.push("--".into()); + args.push(format!("driver={}", self.driver)); + args.join(" ") + } + + pub fn command(&self) -> Command { + let mut c = Command::new(format!("qemu-system-{}", self.arch.name())); + c.args(self.argv()); + c + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The page's boot, as wasm.rs makes it + fn browser(smp: u32) -> Boot { + Boot { + arch: Arch::Aarch64, + kernel: "/kernel".into(), + rootfs: "/rootfs.cpio".into(), + driver: "cli".into(), + machine: Machine { + num_cpus: smp, + mem_mb: 64, + }, + kernel_log: "/kernel.log".into(), + kstep_socket: "/kstep".into(), + kstep_log: None, + monitor_socket: "/monitor".into(), + terminal: false, + debug: false, + ram_file: None, + snapshot: None, + } + } + + #[test] + fn cmdline_isolates_the_test_cpus() { + let mut boot = browser(3); + let c = boot.cmdline(); + assert!(c.contains("isolcpus=nohz,managed_irq,1-2 "), "{c}"); + assert!(c.ends_with("console=ttyAMA0 -- driver=cli"), "{c}"); + boot.arch = Arch::X86_64; + boot.machine.num_cpus = 2; + boot.driver = "default".into(); + let x = boot.cmdline(); + assert!( + x.contains("nohz_full=1 ") + && x.ends_with("console=ttyS0 tsc=nowatchdog tsc=reliable -- driver=default"), + "{x}" + ); + } + + #[test] + fn emscripten_boot() { + let boot = browser(3); + let a = boot.argv().join(" "); + // the accelerator is the host's: KVM where /dev/kvm is usable + assert!(a.starts_with("-machine virt -accel "), "{a}"); + assert!( + a.contains("-smp 3 -m 64M -kernel /kernel -initrd /rootfs.cpio -append rw nokaslr"), + "{a}" + ); + // the browser's two-way channels are the wasm32 build's (served()); run.mjs --check boots them + assert!(a.contains("-device virtio-serial-device,id=vs0 -device virtconsole,bus=vs0.0,nr=0,chardev=port -chardev file,id=console,path=/kernel.log -chardev "), "{a}"); + } + + #[test] + fn native_boot_wires_the_channels() { + let mut boot = Boot { + arch: Arch::X86_64, + kernel: "/b/kernel".into(), + rootfs: "/b/rootfs.cpio".into(), + driver: "cli".into(), + machine: Machine { + num_cpus: 3, + mem_mb: 128, + }, + kernel_log: "/r/kernel.log".into(), + kstep_socket: "/r/kstep.sock".into(), + kstep_log: Some("/r/kstep.jsonl".into()), + monitor_socket: "/r/monitor.sock".into(), + terminal: false, + debug: false, + ram_file: None, + snapshot: None, + }; + let a = boot.argv().join(" "); + assert!( + a.contains("-accel kvm -cpu host") + || a.contains("-accel tcg,tb-size=64,thread=multi -cpu "), + "{a}" + ); + assert!(a.ends_with("-chardev file,id=console,path=/r/kernel.log -chardev socket,path=/r/kstep.sock,server=on,wait=off,logfile=/r/kstep.jsonl,id=port -chardev socket,path=/r/monitor.sock,server=on,wait=off,id=monitor -monitor chardev:monitor"), "{a}"); + assert!(!a.contains("memory-backend")); + boot.ram_file = Some("/dev/shm/x".into()); + boot.debug = true; + boot.terminal = true; + let a = boot.argv().join(" "); + assert!( + a.contains("memory-backend=ram") + && a.contains("mem-path=/dev/shm/x,share=on") + && a.contains("-mon chardev=console") + && a.ends_with("-s -S"), + "{a}" + ); + } +} diff --git a/crates/core/src/shm.rs b/crates/core/src/shm.rs new file mode 100644 index 00000000..e98b4498 --- /dev/null +++ b/crates/core/src/shm.rs @@ -0,0 +1,496 @@ +//! kmod/shm.h, byte for byte: the region of guest memory the cli driver rewrites after every +//! command. The structs come from the header itself, through bindgen (build.rs), as `raw`, so a +//! snapshot of the region is read as one `kstep_shm` and each table sliced by its count. `gen` is +//! odd while the writer is mid-update; a snapshot with an odd gen is `Busy`. That is the whole +//! check: the kmod rewrites the region before it replies, and a host snapshots after the reply, +//! so a snapshot never straddles an update. A host that read live memory concurrently would have +//! to compare gen before and after its copy itself. + +use serde::Serialize; + +/// kmod/shm.h as bindgen reads it. +#[allow(non_camel_case_types, non_upper_case_globals, dead_code)] +pub mod raw { + include!(concat!(env!("OUT_DIR"), "/shm_h.rs")); +} +use raw::*; + +pub const MAGIC: u32 = KSTEP_SHM_MAGIC; +pub const LAYOUT: u32 = KSTEP_SHM_LAYOUT; +/// The whole region: what to snapshot +pub const SIZE: usize = std::mem::size_of::(); +/// cov.c's edge map: saturating byte counts +pub const COV_SIZE: usize = KSTEP_COV_SIZE as usize; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// Not a kSTEP region + Magic(u32), + /// A region this decoder was not built for: rebuild the image from the current kmod + Layout(u32), + /// Mid-update: read again + Busy, + /// The snapshot is shorter than the region + Short, +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Error::Magic(m) => write!(f, "not a kSTEP shared region (magic {m:#x})"), + Error::Layout(l) => write!(f, "shm layout {l}, this decoder speaks {LAYOUT}: rebuild the image from the current kmod"), + Error::Busy => f.write_str("shm mid-update"), + Error::Short => write!(f, "shm snapshot shorter than the region ({SIZE} bytes)"), + } + } +} +impl std::error::Error for Error {} + +#[allow(clippy::unnecessary_cast)] // c_char is u8 on aarch64 and i8 on x86_64 +fn cstr(s: &[std::os::raw::c_char]) -> String { + let bytes: Vec = s + .iter() + .take_while(|&&c| c != 0) + .map(|&c| c as u8) + .collect(); + String::from_utf8_lossy(&bytes).into_owned() +} + +// ---- the decoded state: field names as kstep.mjs reports them, so the page can switch ---------- + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct State { + /// Logical ticks + pub timestamp: u32, + pub cpus: Vec, + pub tasks: Vec, + /// The cgroups, root first + pub groups: Vec, + pub domains: Vec, + /// The fair class: its root queue per CPU, and every entity on it + pub cfs: Vec, + pub entities: Vec, + /// The real-time class: its queue per CPU, and the tasks on it + pub rt: Vec, + pub rt_entities: Vec, +} + +/// The runqueue itself; each class's queue on it is in that class's table, joined by cpu. +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Cpu { + pub cpu: u32, + /// kSTEP task number running there, 0 for none or another process + pub current: u32, + pub idle: bool, + pub capacity: u32, + pub freq: u32, + /// Ticks until rq->next_balance comes due, 0 when it already has + pub next_balance_in: u32, + pub nr_running: u64, + pub nr_switches: u64, +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Task { + pub task: u32, + /// running, runnable, sleeping, blocked + pub state: &'static str, + pub cpu: u32, + /// normal, fifo, rr, batch, idle + pub policy: &'static str, + pub nice: i32, + /// 1..99 under fifo/rr, 0 otherwise + pub rt_priority: u32, + /// The cgroup's path + pub cgroup: String, + /// Allowed CPUs as a bitmask + pub cpus: u64, + pub sum_exec_runtime: u64, +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Cgroup { + pub path: String, + /// cpuset.cpus.effective as a bitmask + pub cpus: u64, + /// cpu.weight, 0 where the controller is off + pub weight: u32, +} + +/// rq->cfs on one CPU +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Cfs { + pub cpu: u32, + pub min_vruntime: i64, + pub util_avg: u64, + pub load_avg: u64, + pub runnable_avg: u64, + /// Runnable tasks as the balancer counts them + pub h_nr_runnable: u64, +} + +/// A sched_entity: a task's (task > 0) or a cgroup's on one CPU (task 0). The flags are the +/// kernel's own answers: eligible is entity_eligible, pick is pick_eevdf on its queue. +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Entity { + pub task: u32, + pub cgroup: String, + pub cpu: u32, + pub eligible: bool, + pub delayed: bool, + pub on_rq: bool, + pub curr: bool, + pub pick: bool, + /// Of the CPU, 1.0 being all of it + pub share: f64, + pub weight: u64, + pub sum_exec_runtime: u64, + pub vruntime: i64, + pub deadline: i64, + pub slice: u64, + /// Queue average vruntime minus this entity's, weighted: 0 fair, positive owed time + pub lag: i64, +} + +/// rq->rt on one CPU +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Rt { + pub cpu: u32, + pub nr_running: u32, + /// 0 (highest) .. 98; 100 when empty + pub highest_prio: u32, + pub throttled: bool, + pub rt_time: u64, + pub rt_runtime: u64, +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct RtEntity { + pub task: u32, + pub cpu: u32, + pub on_rq: bool, + pub curr: bool, + /// The head of the highest list: what pick_next_task_rt would take + pub pick: bool, + /// Place in its priority's list, 0 the head + pub position: u32, + /// RR time left, in ticks + pub time_slice: u32, +} + +/// One sched domain as the kernel built it, per CPU, innermost first. +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Domain { + pub cpu: u32, + pub span: u64, + /// SMT, CLS, MC, PKG, NODE + pub name: String, + /// SD_* names, "SD_" stripped + pub flags: String, + pub imbalance_pct: u32, + pub balance_interval: u32, + pub busy_factor: u32, + pub cache_nice_tries: u32, + pub nr_balance_failed: u32, + pub last_balance_ago: u32, + pub groups: Vec, +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Group { + pub span: u64, + pub capacity: u32, + pub min_capacity: u32, + pub max_capacity: u32, + pub weight: u32, +} + +const TASK_STATES: [&str; 4] = ["running", "runnable", "sleeping", "blocked"]; + +fn policy(n: u32) -> &'static str { + match n { + 0 => "normal", + 1 => "fifo", + 2 => "rr", + 3 => "batch", + 5 => "idle", + _ => "?", + } +} + +/// The first `n` records of a table, or `Busy` when a half-written header claims more than fit. +fn table(rows: &[R], n: u32, f: impl Fn(&R) -> T) -> Result, Error> { + rows.get(..n as usize) + .ok_or(Error::Busy) + .map(|rows| rows.iter().map(f).collect()) +} + +/// Decode one snapshot of the region (`SIZE` bytes). `Busy` means the writer was mid-update: +/// snapshot again. +pub fn decode(b: &[u8]) -> Result { + if b.len() < SIZE { + return Err(Error::Short); + } + // SAFETY: kstep_shm is a repr(C) struct of integers and byte arrays, so any SIZE bytes are a + // valid value; read unaligned from a checked range. + let r: kstep_shm = unsafe { std::ptr::read_unaligned(b.as_ptr() as *const kstep_shm) }; + let h = &r.hdr; + if h.magic != MAGIC { + return Err(Error::Magic(h.magic)); + } + if h.layout != LAYOUT { + return Err(Error::Layout(h.layout)); + } + if h.gen_ & 1 == 1 { + return Err(Error::Busy); + } + + let cpus = table(&r.cpu, h.ncpus, |c| Cpu { + cpu: c.cpu, + current: c.curr, + idle: c.idle != 0, + capacity: c.capacity, + freq: c.freq, + next_balance_in: c.next_balance_in, + nr_running: c.nr_running, + nr_switches: c.nr_switches, + })?; + let groups = table(&r.cgroup, h.ncgroups, |g| Cgroup { + path: cstr(&g.path), + cpus: g.cpus, + weight: g.weight, + })?; + let group_path = |i: u32| { + groups + .get(i as usize) + .map_or_else(|| "/".to_string(), |g| g.path.clone()) + }; + let tasks = table(&r.task, h.ntasks, |t| Task { + task: t.task, + state: TASK_STATES.get(t.state as usize).copied().unwrap_or("?"), + cpu: t.cpu, + policy: policy(t.policy), + nice: t.nice, + rt_priority: t.rt_priority, + cgroup: group_path(t.cgroup), + cpus: t.cpus, + sum_exec_runtime: t.sum_exec_runtime, + })?; + let cfs = table(&r.cfs, h.ncpus, |q| Cfs { + cpu: q.cpu, + min_vruntime: q.min_vruntime, + util_avg: q.util_avg, + load_avg: q.load_avg, + runnable_avg: q.runnable_avg, + h_nr_runnable: q.h_nr_runnable, + })?; + let entities = table(&r.entity, h.nentities, |e| Entity { + task: e.task, + cgroup: group_path(e.cgroup), + cpu: e.cpu, + eligible: e.se.flags & KSTEP_SE_ELIGIBLE != 0, + delayed: e.se.flags & KSTEP_SE_DELAYED != 0, + on_rq: e.se.flags & KSTEP_SE_ON_RQ != 0, + curr: e.se.flags & KSTEP_SE_CURR != 0, + pick: e.se.flags & KSTEP_SE_PICK != 0, + share: e.se.share as f64 / 1024.0, + weight: e.se.weight, + sum_exec_runtime: e.se.sum_exec_runtime, + vruntime: e.se.vruntime, + deadline: e.se.deadline, + slice: e.se.slice, + lag: e.se.lag, + })?; + let rt = table(&r.rt, h.ncpus, |q| Rt { + cpu: q.cpu, + nr_running: q.nr_running, + highest_prio: q.highest_prio, + throttled: q.throttled != 0, + rt_time: q.rt_time, + rt_runtime: q.rt_runtime, + })?; + let rt_entities = table(&r.rt_entity, h.nrt_entities, |e| RtEntity { + task: e.task, + cpu: e.cpu, + on_rq: e.flags & KSTEP_RT_ON_RQ != 0, + curr: e.flags & KSTEP_RT_CURR != 0, + pick: e.flags & KSTEP_RT_PICK != 0, + position: e.position, + time_slice: e.time_slice, + })?; + let domains = table(&r.domain, h.ndomains, |d| Domain { + cpu: d.cpu, + span: d.span, + name: cstr(&d.name), + flags: cstr(&d.flags), + imbalance_pct: d.imbalance_pct, + balance_interval: d.balance_interval, + busy_factor: d.busy_factor, + cache_nice_tries: d.cache_nice_tries, + nr_balance_failed: d.nr_balance_failed, + last_balance_ago: d.last_balance_ago, + groups: d.group[..(d.ngroups as usize).min(d.group.len())] + .iter() + .map(|g| Group { + span: g.span, + capacity: g.capacity, + min_capacity: g.min_capacity, + max_capacity: g.max_capacity, + weight: g.weight, + }) + .collect(), + })?; + Ok(State { + timestamp: h.timestamp, + cpus, + tasks, + groups, + domains, + cfs, + entities, + rt, + rt_entities, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bytes(r: &kstep_shm) -> Vec { + // SAFETY: a plain repr(C) struct of integers, viewed as its bytes + unsafe { std::slice::from_raw_parts(r as *const kstep_shm as *const u8, SIZE) }.to_vec() + } + + /// A region built through the generated structs: one CPU running one rr task in cgroup /a. + #[test] + fn decodes_a_region() { + let mut r = kstep_shm { + hdr: kstep_shm_hdr { + magic: MAGIC, + layout: LAYOUT, + gen_: 2, + timestamp: 7, + ncpus: 1, + ntasks: 1, + ncgroups: 1, + ndomains: 0, + nentities: 1, + nrt_entities: 1, + }, + ..Default::default() + }; + r.cpu[0] = kstep_shm_cpu { + cpu: 1, + curr: 1, + nr_running: 2, + ..Default::default() + }; + r.task[0] = kstep_shm_task { + task: 1, + state: 0, + cpu: 1, + policy: 2, + nice: -3, + rt_priority: 5, + cgroup: 0, + cpus: 0b110, + ..Default::default() + }; + r.cgroup[0].path[..2].copy_from_slice(&[b'/' as _, b'a' as _]); + r.cgroup[0].weight = 100; + r.cfs[0] = kstep_shm_cfs { + cpu: 1, + min_vruntime: 1000, + ..Default::default() + }; + r.entity[0] = kstep_shm_entity { + task: 1, + cpu: 1, + se: kstep_shm_se { + flags: KSTEP_SE_ELIGIBLE | KSTEP_SE_CURR, + share: 512, + lag: -8, + ..Default::default() + }, + ..Default::default() + }; + r.rt[0] = kstep_shm_rt { + cpu: 1, + highest_prio: 100, + ..Default::default() + }; + r.rt_entity[0] = kstep_shm_rt_entity { + task: 1, + cpu: 1, + flags: KSTEP_RT_ON_RQ | KSTEP_RT_PICK, + time_slice: 99, + ..Default::default() + }; + + let st = decode(&bytes(&r)).unwrap(); + assert_eq!(st.timestamp, 7); + assert_eq!( + st.cpus, + [Cpu { + cpu: 1, + current: 1, + idle: false, + capacity: 0, + freq: 0, + next_balance_in: 0, + nr_running: 2, + nr_switches: 0 + }] + ); + let t = &st.tasks[0]; + assert_eq!( + ( + t.state, + t.cpu, + t.policy, + t.nice, + t.rt_priority, + t.cgroup.as_str(), + t.cpus + ), + ("running", 1, "rr", -3, 5, "/a", 0b110) + ); + assert_eq!( + (st.groups[0].path.as_str(), st.groups[0].weight), + ("/a", 100) + ); + assert_eq!(st.cfs[0].min_vruntime, 1000); + let e = &st.entities[0]; + assert_eq!( + ( + e.task, + e.cgroup.as_str(), + e.eligible, + e.curr, + e.pick, + e.share, + e.lag + ), + (1, "/a", true, true, false, 0.5, -8) + ); + assert_eq!( + ( + st.rt[0].highest_prio, + st.rt_entities[0].pick, + st.rt_entities[0].time_slice + ), + (100, true, 99) + ); + assert!(st.domains.is_empty()); + + r.hdr.gen_ = 3; + assert_eq!(decode(&bytes(&r)), Err(Error::Busy)); + r.hdr.gen_ = 2; + r.hdr.ntasks = KSTEP_SHM_TASKS + 1; + assert_eq!(decode(&bytes(&r)), Err(Error::Busy)); + r.hdr.layout = LAYOUT + 1; + assert_eq!(decode(&bytes(&r)), Err(Error::Layout(LAYOUT + 1))); + assert_eq!(decode(&bytes(&r)[..100]), Err(Error::Short)); + } +} diff --git a/crates/core/src/wasm.rs b/crates/core/src/wasm.rs new file mode 100644 index 00000000..d402cf04 --- /dev/null +++ b/crates/core/src/wasm.rs @@ -0,0 +1,53 @@ +//! kSTEP's core for the website: kstep.mjs asks for QEMU's arguments, then copies the shared +//! region out of QEMU's memory after each command and hands the bytes here. JS owns that memory, +//! so it also owns the seqlock retry: a `null` result means "snapshot again". + +use wasm_bindgen::prelude::*; + +use crate::qemu::{Arch, Boot, Machine}; +use crate::shm; + +/// The argv for the page's QEMU (an aarch64 build): the cli driver on `smp` CPUs with `mem` MB, +/// the kernel and initramfs at fixed paths in the module's file system; with `snapshot`, resumed +/// from the migration stream at /snap instead (run.mjs --snapshot writes it, at the ready line). +#[wasm_bindgen] +pub fn qemu_args(smp: u32, mem: u32, snapshot: bool) -> Vec { + Boot { + arch: Arch::Aarch64, + snapshot: snapshot.then(|| "/snap".into()), + kernel: "/kernel".into(), + rootfs: "/rootfs.cpio".into(), + driver: "cli".into(), + machine: Machine { + num_cpus: smp, + mem_mb: mem, + }, + // the device nodes kstep.mjs registers (its pipe() and createDevice calls) + kernel_log: "/kernel.log".into(), + kstep_socket: "/kstep".into(), + kstep_log: None, + monitor_socket: "/monitor".into(), + terminal: false, + debug: false, + ram_file: None, + } + .argv() +} + +/// How many bytes to snapshot: the whole region. +#[wasm_bindgen] +pub fn shm_size() -> usize { + shm::SIZE +} + +/// The machine's state from a snapshot of the region; `null` when the writer was mid-update. +/// Fails on a region this decoder was not built for. Every field fits a JS number: the kernel's +/// wrapping vruntimes are decoded signed, and nothing else gets near 2^53. +#[wasm_bindgen] +pub fn shm_decode(region: &[u8]) -> Result { + match shm::decode(region) { + Ok(state) => serde_wasm_bindgen::to_value(&state).map_err(|e| JsError::new(&e.to_string())), + Err(shm::Error::Busy) => Ok(JsValue::NULL), + Err(e) => Err(JsError::new(&e.to_string())), + } +} diff --git a/crates/fuzz/Cargo.toml b/crates/fuzz/Cargo.toml new file mode 100644 index 00000000..84d3b2f3 --- /dev/null +++ b/crates/fuzz/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "kstep-fuzz" +description = "kSTEP's LibAFL fuzzer: a client of the cli driver" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[[bin]] +name = "kstep-fuzz" +path = "src/main.rs" + +[dependencies] +kstep = { path = "../kstep" } +kstep-core = { path = "../core" } +anyhow = "1" +clap = { version = "4", features = ["derive"] } +libafl = "0.16" +libafl_bolts = "0.16" diff --git a/crates/fuzz/src/main.rs b/crates/fuzz/src/main.rs new file mode 100644 index 00000000..76b1ed03 --- /dev/null +++ b/crates/fuzz/src/main.rs @@ -0,0 +1,452 @@ +//! kSTEP fuzzer: a LibAFL client of the cli driver. +//! +//! A test case is a byte string. The host decodes it into cli lines (see `decode`), boots the +//! image, feeds the lines to the driver, and reads the replies. A `warn` record from an enabled +//! checker, or an oops in the console, is a finding; a stalled reply is a timeout. Coverage is +//! the guest's edge map (kmod/cov.c), read out of guest RAM after the run. The guest has no +//! fuzzer-specific code. +//! +//! One fuzzing client per core, each with its own QEMU and result directory; LibAFL's Launcher +//! forks them and a broker merges their corpora. + +use std::fmt::Write as _; +use std::fs; +use std::num::NonZeroUsize; +use std::path::PathBuf; +use std::time::Duration; + +use anyhow::{Context, Result}; +use clap::Parser; +use kstep::bugs::Bug; +use kstep::{bugs, Build, ResultDir, Session}; +use kstep_core::qemu::Boot; +use kstep_core::shm::COV_SIZE; +use libafl::{ + corpus::{InMemoryOnDiskCorpus, OnDiskCorpus}, + events::{ClientDescription, EventConfig, Launcher}, + executors::{Executor, ExitKind, HasObservers}, + feedbacks::{CrashFeedback, MaxMapFeedback}, + fuzzer::{Fuzzer, StdFuzzer}, + generators::RandBytesGenerator, + inputs::{BytesInput, HasTargetBytes}, + monitors::MultiMonitor, + mutators::{havoc_mutations, HavocScheduledMutator}, + observers::StdMapObserver, + schedulers::QueueScheduler, + stages::StdMutationalStage, + state::StdState, +}; +use libafl_bolts::{ + core_affinity::Cores, + current_nanos, + rands::StdRand, + shmem::{ShMemProvider, StdShMemProvider}, + tuples::{tuple_list, RefIndexable}, + ToSliceMut, +}; + +const MAX_RECORDS: usize = 64; // commands per program + +/// Fuzz a bugs.yaml entry on build/_buggy, vetting findings against build/_fixed +#[derive(Parser)] +#[command(name = "kstep-fuzz", version)] +struct Args { + /// The bug (bugs.yaml) + bug: String, + /// Cores to run clients on, e.g. 0-7 (default: all) + #[arg(long)] + cores: Option, +} + +// ---- input decoding ------------------------------------------------------------------------ + +// The general verb table, indexed by the verb byte: what every bug needs, kept small so a bug's +// alphabet stays close to what its rule is about. A bug's own verbs (bugs.yaml) follow it; any cli +// verb may appear there, spelled as cli.c spells it. +// +// create is not here: a bug's setup makes the tasks, so the ids a record can name are fixed for +// the whole program and a mutation stays local. A bug that wants task arrival fuzzed asks for +// `create` among its own verbs. +const VERBS: &[&str] = &["tick", "policy-fair", "affinity", "pause", "wake"]; +const FAIR_POLICIES: &[&str] = &["normal", "batch", "idle"]; +const RT_POLICIES: &[&str] = &["fifo", "rr"]; + +/// Bytes to cli lines. Fixed 4-byte records (verb, a, b, c) keep mutations aligned. Arguments are +/// choices resolved against what the host knows for certain: tasks created, tasks it has killed, +/// cgroups created, and the CPU count. Nothing about scheduling state is mirrored; a line the +/// guest rejects costs one error reply. +fn decode(bytes: &[u8], bug: &Bug) -> Vec { + let ncpus = bug.num_cpus as usize; + let mut lines: Vec = bug + .fuzz + .checks + .iter() + .map(|c| format!("check {c}")) + .collect(); + let mut alive: Vec = vec![]; // task numbers not yet killed + let mut ntasks = 0usize; + let mut cgroups: Vec = vec![]; // paths created, "/g1", "/g1/g2", ..; destroyed ones stay (one error reply) + let test_cpus = ncpus - 1; // CPUs 1..N-1; 0 is kSTEP's controller + + // The setup lines come first; what they create, the program can refer to. + for line in &bug.fuzz.setup { + match line.split_once(' ').unwrap_or((line, "")) { + ("create", n) => { + for _ in 0..n.trim().parse().unwrap_or(1) { + ntasks += 1; + alive.push(ntasks); + } + } + ("cgroup-create", path) => cgroups.push(path.to_string()), + _ => {} + } + lines.push(line.clone()); + } + + let verbs = &bug.fuzz.verbs; + for rec in bytes.as_chunks::<4>().0.iter().take(MAX_RECORDS) { + let (index, a, b) = ( + rec[0] as usize % (VERBS.len() + verbs.len()), + rec[1] as usize, + rec[2] as usize, + ); + let verb = if index < VERBS.len() { + VERBS[index] + } else { + verbs[index - VERBS.len()].as_str() + }; + let task = |a: usize| alive[a % alive.len()]; + let cpu = |b: usize| 1 + b % test_cpus; + let needs_task = !matches!( + verb, + "tick" | "create" | "cpu-freq" | "cgroup-create" | "cgroup-weight" | "cgroup-destroy" + ); + if needs_task && alive.is_empty() { + lines.push("tick".into()); + continue; + } + let line = match verb { + "tick" => "tick".to_string(), // one tick: a count would only repeat the event and hide which tick mattered + // One task at a time: the scheduler event is a task arriving, and a count only repeats + // it, at the price of guest time and of shifting every later task reference (a task is + // resolved against how many are alive, so a count makes a one-byte mutation global). + // A program that wants to start from n tasks says so in the bug's setup. + "create" => { + ntasks += 1; + alive.push(ntasks); + "create".to_string() + } + // one CPU's frequency, as cpufreq would change it: a scale of 1..1024 + "cpu-freq" => format!("cpu-freq {} {}", cpu(a), 1 + b % 1024), + // a fair policy with a nice, or a real-time one with a priority: what the class reads + "policy-fair" => format!( + "policy-fair {} {} {}", + task(a), + FAIR_POLICIES[b % FAIR_POLICIES.len()], + rec[3] as i32 % 40 - 20 + ), + "policy-rt" => format!( + "policy-rt {} {} {}", + task(a), + RT_POLICIES[b % RT_POLICIES.len()], + 1 + rec[3] as usize % 99 + ), + "affinity" => { + // b's low bits pick the allowed test CPUs; at least one + let mut cpus: Vec = (0..test_cpus) + .filter(|i| b >> i & 1 == 1) + .map(|i| (i + 1).to_string()) + .collect(); + if cpus.is_empty() { + cpus.push(cpu(b).to_string()); + } + format!("affinity {} {}", task(a), cpus.join(",")) + } + "kill" => { + let t = task(a); + alive.retain(|&x| x != t); + format!("kill {t}") + } + "cgroup-create" => { + // under the root or an existing cgroup, so hierarchies form + let parent = if cgroups.is_empty() || b % 2 == 0 { + String::new() + } else { + cgroups[b % cgroups.len()].clone() + }; + cgroups.push(format!("{parent}/g{}", cgroups.len() + 1)); + format!("cgroup-create {}", cgroups.last().unwrap()) + } + "cgroup-weight" if !cgroups.is_empty() => { + let weight = 1 + (b << 8 | rec[3] as usize) % 10000; + format!("cgroup-weight {} {weight}", cgroups[a % cgroups.len()]) + } + "cgroup-destroy" if !cgroups.is_empty() => { + format!("cgroup-destroy {}", cgroups[a % cgroups.len()]) + } + "cgroup-weight" | "cgroup-destroy" => "tick".to_string(), // nothing to name yet + "cgroup-attach" => match b % (cgroups.len() + 1) { + 0 => format!("cgroup-attach / {}", task(a)), + g => format!("cgroup-attach {} {}", cgroups[g - 1], task(a)), + }, + _ => format!("{verb} {}", task(a)), // pause, wake, block, chan-read, chan-write, freeze, thaw + }; + lines.push(line); + } + lines.extend(["tick", "tick", "tick"].map(String::from)); + lines +} + +// ---- the executor -------------------------------------------------------------------------- + +/// One QEMU boot per test case, driven over the driver's socket. +struct QemuExecutor { + boot: Boot, + fixed: Option, // the same bug's fixed kernel, which vets every candidate + bug: Bug, + findings: PathBuf, + nfindings: usize, + observers: (StdMapObserver<'static, u8, false>, ()), +} + +enum Outcome { + Ok, + Warn(String), + Timeout(String), +} + +/// A program's run: what it came to, the transcript, and the coverage map when asked for. A +/// warn record from a checker or an oops in the console is a `Warn`; a stalled reply a `Timeout`. +fn run_program(boot: &Boot, lines: &[String], map: Option<&mut [u8]>) -> (Outcome, String) { + let mut transcript = String::new(); + let mut session = match Session::start(boot, Duration::from_secs(30)) { + Ok(s) => s, + Err(e) => return (Outcome::Timeout(format!("boot: {e:#}")), transcript), + }; + let mut warn = None; + for cmd in lines { + let Ok(r) = session.cmd(cmd) else { + return (Outcome::Timeout(format!("no reply to `{cmd}`")), transcript); + }; + for e in &r.events { + let _ = writeln!(transcript, "{cmd:24} {e}"); + if warn.is_none() && e.get("type").and_then(|t| t.as_str()) == Some("warn") { + warn = Some(e.to_string()); + } + } + let _ = writeln!(transcript, "{cmd:24} {}", r.reply); + } + if let Some(map) = map { + // A kernel built without linux/config.kstep.cov has no map, and the map stays as it was. + let _ = session.coverage(map); + } + let _ = session.exit(); + if warn.is_none() && console_oops(boot) { + warn = Some("kernel oops/warning in console".into()); + } + (warn.map_or(Outcome::Ok, Outcome::Warn), transcript) +} + +// Only once the driver runs: a kernel that warns while booting (6.12-rc1 does, in +// pick_task_fair) would otherwise turn every test case into a finding. A resumed machine's log +// holds nothing but the run. +fn console_oops(boot: &Boot) -> bool { + let log = fs::read_to_string(&boot.kernel_log).unwrap_or_default(); + let run = log.find("Starting cli").map_or(log.as_str(), |i| &log[i..]); + [ + "Oops", + "Kernel panic", + "BUG:", + "WARNING:", + "KASAN:", + "UBSAN:", + "general protection fault", + ] + .iter() + .any(|m| run.contains(m)) +} + +impl QemuExecutor { + /// The same program on the kernel with the fix. Only a run that gets to the end of the program + /// with nothing to say confirms the candidate: a rule that warns there is describing ordinary + /// scheduling, and a run that timed out or never booted has not shown anything either way, so + /// neither is evidence of the bug. Without a fixed build there is nothing to compare against + /// and the candidate is kept. + fn confirmed_on_fixed(&self, lines: &[String]) -> Result { + let Some(fixed) = &self.fixed else { + return Ok("not vetted: no fixed build".into()); + }; + match run_program(fixed, lines, None).0 { + Outcome::Ok => Ok("fixed kernel: silent".into()), + Outcome::Warn(w) => Err(format!("fixed kernel warns too: {w}")), + Outcome::Timeout(t) => Err(format!("fixed kernel: {t}")), + } + } + + fn save_finding(&mut self, lines: &[String], transcript: &str, why: &str) { + self.nfindings += 1; + let base = self.findings.join(format!("{:04}", self.nfindings)); + let _ = fs::write( + base.with_extension("cli"), + format!("# {why}\n{}\n", lines.join("\n")), + ); + let _ = fs::write(base.with_extension("jsonl"), transcript); + let _ = fs::copy(&self.boot.kernel_log, base.with_extension("log")); + println!("finding {}: {why}", base.display()); + } +} + +impl Executor for QemuExecutor { + fn run_target( + &mut self, + _fuzzer: &mut Z, + _state: &mut S, + _mgr: &mut EM, + input: &BytesInput, + ) -> Result { + let lines = decode(&input.target_bytes(), &self.bug); + let map = self.observers.0.to_slice_mut(); + map.fill(0); + let (outcome, transcript) = run_program(&self.boot, &lines, Some(map)); + Ok(match outcome { + Outcome::Ok => ExitKind::Ok, + // A candidate until the fixed kernel has been shown to be quiet on the same program: + // one extra boot, and only for a candidate. + Outcome::Warn(what) => match self.confirmed_on_fixed(&lines) { + Ok(how) => { + self.save_finding(&lines, &transcript, &format!("{what} [{how}]")); + ExitKind::Crash + } + Err(_) => ExitKind::Ok, // ordinary scheduling, or nothing shown either way + }, + Outcome::Timeout(why) => { + self.save_finding(&lines, &transcript, &format!("timeout: {why}")); + ExitKind::Timeout + } + }) + } +} + +impl HasObservers for QemuExecutor { + type Observers = (StdMapObserver<'static, u8, false>, ()); + fn observers(&self) -> RefIndexable<&Self::Observers, Self::Observers> { + RefIndexable::from(&self.observers) + } + fn observers_mut(&mut self) -> RefIndexable<&mut Self::Observers, Self::Observers> { + RefIndexable::from(&mut self.observers) + } +} + +// ---- main ------------------------------------------------------------------------------------ + +/// A headless cli boot of `build` on the bug's machine, logging under results/