From 00625064d42aee382fd1247e151528b2a27f2d96 Mon Sep 17 00:00:00 2001 From: Rosen Penev Date: Fri, 30 Oct 2026 19:37:08 -0700 Subject: [PATCH 1/4] drmcru: fix cargo audit findings Upgrade ratatui to 0.30 and crossterm to 0.29, dropping the unmaintained paste crate and the unsound lru 0.12. ratatui 0.30.2 and the patched time 0.3.47+ (RUSTSEC-2026-0009) require Rust 1.88, so raise the MSRV and update CI and the README to match. Disable ratatui's unused default features to trim the lockfile, and refresh anyhow past RUSTSEC-2026-0190. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Rosen Penev --- .github/workflows/ci.yml | 4 +- Cargo.lock | 543 +++++++++++++++++++++++++-------------- Cargo.toml | 6 +- README.md | 2 +- 4 files changed, 359 insertions(+), 196 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a9a4835..e34e845 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,8 +13,8 @@ jobs: steps: - uses: actions/checkout@v6 - name: Install minimum supported Rust - run: rustup toolchain install 1.87.0 --profile minimal - - run: cargo +1.87.0 test --locked + run: rustup toolchain install 1.88.0 --profile minimal + - run: cargo +1.88.0 test --locked checks: runs-on: ubuntu-22.04 diff --git a/Cargo.lock b/Cargo.lock index 451f99d..9253825 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,21 +10,36 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "anyhow" -version = "1.0.102" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "bitflags" -version = "2.11.1" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] -name = "cassowary" -version = "0.3.0" +name = "by_address" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" [[package]] name = "castaway" @@ -37,15 +52,15 @@ dependencies = [ [[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 = "compact_str" -version = "0.8.1" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b79c4069c6cad78e2e0cdfcbd26275770669fb39fd308a752dc110e83b9af32" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" dependencies = [ "castaway", "cfg-if", @@ -55,14 +70,25 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "crossterm" -version = "0.28.1" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" dependencies = [ "bitflags", "crossterm_winapi", + "derive_more", + "document-features", "mio", "parking_lot", "rustix", @@ -82,9 +108,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.11" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" dependencies = [ "darling_core", "darling_macro", @@ -92,27 +118,63 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.11" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" dependencies = [ - "fnv", "ident_case", "proc-macro2", "quote", "strsim", - "syn", + "syn 3.0.9", ] [[package]] name = "darling_macro" -version = "0.20.11" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core", "quote", - "syn", + "syn 3.0.9", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", ] [[package]] @@ -129,15 +191,15 @@ dependencies = [ [[package]] name = "either" -version = "1.15.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" @@ -146,26 +208,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - [[package]] name = "foldhash" -version = "0.1.5" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "hashbrown" -version = "0.15.5" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ "allocator-api2", "equivalent", @@ -186,31 +242,31 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "indoc" -version = "2.0.7" +version = "2.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" dependencies = [ "rustversion", ] [[package]] name = "instability" -version = "0.3.10" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6778b0196eefee7df739db78758e5cf9b37412268bfa5650bfeed028aed20d9c" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" dependencies = [ "darling", "indoc", "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] name = "itertools" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" dependencies = [ "either", ] @@ -221,17 +277,49 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "kasuari" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f14c90e40a6133f4805b83542a7ed7364f56070b447f56e7f4e90297122209" +dependencies = [ + "hashbrown", + "portable-atomic", + "thiserror", +] + [[package]] name = "libc" -version = "0.2.186" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "line-clipping" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e" +dependencies = [ + "bitflags", +] [[package]] name = "linux-raw-sys" -version = "0.4.15" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" [[package]] name = "lock_api" @@ -244,35 +332,92 @@ dependencies = [ [[package]] name = "log" -version = "0.4.29" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "lru" -version = "0.12.5" +version = "0.18.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" dependencies = [ "hashbrown", ] [[package]] name = "memchr" -version = "2.8.0" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "mio" -version = "1.2.0" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "log", "wasi", - "windows-sys 0.61.2", + "windows-sys", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", ] [[package]] @@ -299,48 +444,99 @@ dependencies = [ ] [[package]] -name = "paste" -version = "1.0.15" +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "powerfmt" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.45" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] [[package]] name = "ratatui" -version = "0.29.0" +version = "0.30.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-crossterm", + "ratatui-widgets", + "serde", +] + +[[package]] +name = "ratatui-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" dependencies = [ "bitflags", - "cassowary", "compact_str", + "hashbrown", + "itertools", + "kasuari", + "lru", + "palette", + "serde", + "strum", + "thiserror", + "unicode-segmentation", + "unicode-truncate", + "unicode-width", +] + +[[package]] +name = "ratatui-crossterm" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" +dependencies = [ + "cfg-if", "crossterm", + "instability", + "ratatui-core", +] + +[[package]] +name = "ratatui-widgets" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags", + "hashbrown", "indoc", "instability", "itertools", - "lru", - "paste", + "line-clipping", + "ratatui-core", + "serde", "strum", + "time", "unicode-segmentation", - "unicode-truncate", - "unicode-width 0.2.0", + "unicode-width", ] [[package]] @@ -352,24 +548,33 @@ dependencies = [ "bitflags", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" -version = "0.38.44" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys", ] [[package]] name = "rustversion" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "ryu" @@ -383,11 +588,17 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -395,29 +606,29 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] name = "serde_json" -version = "1.0.149" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -459,9 +670,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" [[package]] name = "static_assertions" @@ -477,31 +688,41 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "strum" -version = "0.26.3" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" dependencies = [ "strum_macros", ] [[package]] name = "strum_macros" -version = "0.26.4" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" dependencies = [ "heck", "proc-macro2", "quote", - "rustversion", - "syn", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", ] [[package]] name = "syn" -version = "2.0.117" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -510,58 +731,73 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde_core", + "time-core", ] +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-segmentation" -version = "1.13.2" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] name = "unicode-truncate" -version = "1.1.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" dependencies = [ "itertools", "unicode-segmentation", - "unicode-width 0.1.14", + "unicode-width", ] [[package]] name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" - -[[package]] -name = "unicode-width" -version = "0.2.0" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "wasi" @@ -597,15 +833,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -615,72 +842,8 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - [[package]] name = "zmij" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 52f9656..bdf1259 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "drmcru" version = "0.1.5" edition = "2024" -rust-version = "1.87" +rust-version = "1.88" description = "Linux DRM/KMS custom resolution and EDID override utility" readme = "README.md" license = "GPL-3.0-or-later" @@ -22,8 +22,8 @@ exclude = [ [dependencies] anyhow = "1.0" -crossterm = "0.28" -ratatui = "0.29" +crossterm = "0.29" +ratatui = { version = "0.30", default-features = false, features = ["crossterm_0_29"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" thiserror = "2.0" diff --git a/README.md b/README.md index 0b2e3fc..a052d3c 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ can hide the active Hyprland session and create root-owned exports. ## Build From Source -Rust 1.87 or newer is required. +Rust 1.88 or newer is required. ```sh git clone https://github.com/ssupt/drmcru.git From 899791d7e761a9ce694b736a389abc99d8ce5754 Mon Sep 17 00:00:00 2001 From: Rosen Penev Date: Fri, 30 Oct 2026 20:02:51 -0700 Subject: [PATCH 2/4] Fix clippy warnings from stable toolchain Collapse nested ifs and use as_chunks instead of constant-size chunks_exact. Co-Authored-By: Claude Sonnet 5.5 --- src/doctor.rs | 35 ++++++++--------- src/edid.rs | 86 ++++++++++++++++++++++++++++++------------ src/export.rs | 16 +++++--- src/hyprland_config.rs | 42 ++++++++++----------- src/tui/actions.rs | 55 ++++++++++++++------------- src/tui/input.rs | 17 ++++----- src/workspace.rs | 2 +- 7 files changed, 146 insertions(+), 107 deletions(-) diff --git a/src/doctor.rs b/src/doctor.rs index 4e97e7a..c291040 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -118,12 +118,11 @@ fn report_text( } } else { lines.push(" EDID: unavailable".to_string()); - if monitor.status != ConnectorStatus::Disconnected { - if let Some(path) = &monitor.drm_path { - if let Err(error) = discovery::read_edid(path) { - lines.push(format!(" EDID error: {error}")); - } - } + if monitor.status != ConnectorStatus::Disconnected + && let Some(path) = &monitor.drm_path + && let Err(error) = discovery::read_edid(path) + { + lines.push(format!(" EDID error: {error}")); } } @@ -168,19 +167,17 @@ fn report_text( " Hyprland config mode: {}", last.normalized_rule() )); - if let Some(hyprland) = &monitor.hyprland { - if let Some(requested) = parse_mode_request(&last.mode) { - if !hyprland - .available_modes - .iter() - .any(|mode| available_mode_matches_request(mode, requested)) - { - lines.push(format!( - " Hyprland config warning: requested mode {} is not currently exposed", - last.mode - )); - } - } + if let Some(hyprland) = &monitor.hyprland + && let Some(requested) = parse_mode_request(&last.mode) + && !hyprland + .available_modes + .iter() + .any(|mode| available_mode_matches_request(mode, requested)) + { + lines.push(format!( + " Hyprland config warning: requested mode {} is not currently exposed", + last.mode + )); } } } diff --git a/src/edid.rs b/src/edid.rs index 212407d..03a339b 100644 --- a/src/edid.rs +++ b/src/edid.rs @@ -169,7 +169,7 @@ pub fn parse_edid(raw: Vec) -> Result { let mut descriptor_text = Vec::new(); let mut detailed_timings = Vec::new(); - for descriptor in base[DTD_START..126].chunks_exact(DTD_LEN) { + for descriptor in base[DTD_START..126].as_chunks::().0.iter() { if descriptor[0] == 0 && descriptor[1] == 0 { match descriptor[3] { 0xfc => monitor_name = parse_descriptor_text(descriptor), @@ -212,10 +212,10 @@ pub fn slot_summary(raw: &[u8]) -> Result { return Err(EdidError::InvalidHeader); } - let base_descriptors = raw[DTD_START..126].chunks_exact(DTD_LEN); + let base_descriptors = raw[DTD_START..126].as_chunks::().0.iter(); let base_dtd_used = base_descriptors .clone() - .filter(|descriptor| parse_detailed_timing(descriptor).is_some()) + .filter(|descriptor| parse_detailed_timing(*descriptor).is_some()) .count(); let base_dtd_free = base_descriptors .filter(|descriptor| descriptor.iter().all(|byte| *byte == 0)) @@ -223,8 +223,10 @@ pub fn slot_summary(raw: &[u8]) -> Result { let standard_used = parse_standard_timings(&raw[..BASE_BLOCK_LEN]).len(); let standard_free = raw[STANDARD_TIMING_START ..STANDARD_TIMING_START + STANDARD_TIMING_SLOTS * STANDARD_TIMING_LEN] - .chunks_exact(STANDARD_TIMING_LEN) - .filter(|timing| *timing == [0x01, 0x01]) + .as_chunks::() + .0 + .iter() + .filter(|timing| **timing == [0x01, 0x01]) .count(); let mut cta_dtd_used = 0; @@ -243,7 +245,7 @@ pub fn slot_summary(raw: &[u8]) -> Result { let Some(dtd_range) = cta_dtd_range(block) else { continue; }; - for descriptor in block[dtd_range].chunks_exact(DTD_LEN) { + for descriptor in block[dtd_range].as_chunks::().0.iter() { if descriptor.iter().all(|byte| *byte == 0) { cta_dtd_free += 1; } else if parse_detailed_timing(descriptor).is_some() { @@ -515,7 +517,12 @@ pub fn detailed_timing_locations(raw: &[u8]) -> Result() + .0 + .iter() + .enumerate() + { if let Some(timing) = parse_detailed_timing(descriptor) { timings.push(LocatedDetailedTiming { location: DtdLocation::Base { slot }, @@ -538,7 +545,7 @@ pub fn detailed_timing_locations(raw: &[u8]) -> Result().0.iter().enumerate() { if let Some(timing) = parse_detailed_timing(descriptor) { timings.push(LocatedDetailedTiming { location: DtdLocation::Cta { @@ -578,7 +585,7 @@ pub fn cta_dtd_slots(raw: &[u8]) -> Result, EdidError> { continue; }; - for (slot, descriptor) in block[dtd_range].chunks_exact(DTD_LEN).enumerate() { + for (slot, descriptor) in block[dtd_range].as_chunks::().0.iter().enumerate() { let is_free = descriptor.iter().all(|byte| *byte == 0); let timing = (!is_free) .then(|| parse_detailed_timing(descriptor)) @@ -718,7 +725,12 @@ pub fn clear_detailed_timing_stereo(raw: &mut [u8]) -> usize { } let extension_blocks = raw[126]; let mut cleared = 0; - for (index, block) in raw.chunks_exact_mut(EDID_BLOCK_LEN).enumerate() { + for (index, block) in raw + .as_chunks_mut::() + .0 + .iter_mut() + .enumerate() + { if index > usize::from(extension_blocks) { break; } @@ -733,7 +745,7 @@ pub fn clear_detailed_timing_stereo(raw: &mut [u8]) -> usize { continue; }; let mut changed = false; - for descriptor in block[range].chunks_exact_mut(DTD_LEN) { + for descriptor in block[range].as_chunks_mut::().0.iter_mut() { if (descriptor[0] != 0 || descriptor[1] != 0) && descriptor[17] & 0x60 != 0 { descriptor[17] &= !0x61; cleared += 1; @@ -889,7 +901,9 @@ fn parse_displayid_type_i_dtds( payload: &[u8], ) -> Vec { payload - .chunks_exact(DISPLAYID_TYPE_I_DTD_LEN) + .as_chunks::() + .0 + .iter() .enumerate() .filter_map(|(descriptor_index, descriptor)| { parse_displayid_type_i_dtd( @@ -969,11 +983,15 @@ fn parse_cta_block(extension_index: u8, block: &[u8]) -> Option { let data_blocks = parse_cta_data_blocks(block); let (detailed_timings, available_dtd_slots) = if let Some(dtd_range) = cta_dtd_range(block) { let detailed_timings = block[dtd_range.clone()] - .chunks_exact(DTD_LEN) - .filter_map(parse_detailed_timing) + .as_chunks::() + .0 + .iter() + .filter_map(|descriptor| parse_detailed_timing(descriptor)) .collect(); let available_dtd_slots = block[dtd_range] - .chunks_exact(DTD_LEN) + .as_chunks::() + .0 + .iter() .filter(|descriptor| descriptor.iter().all(|byte| *byte == 0)) .count(); (detailed_timings, available_dtd_slots) @@ -1104,7 +1122,9 @@ fn cta_vic_mode(vic: u16, native: bool) -> Option { fn base_empty_dtd_slot(raw: &[u8]) -> Option<(usize, usize)> { raw[DTD_START..126] - .chunks_exact(DTD_LEN) + .as_chunks::() + .0 + .iter() .enumerate() .find(|(_, descriptor)| descriptor.iter().all(|byte| *byte == 0)) .map(|(slot, _)| (slot, DTD_START + slot * DTD_LEN)) @@ -1113,7 +1133,9 @@ fn base_empty_dtd_slot(raw: &[u8]) -> Option<(usize, usize)> { fn cta_empty_dtd_slot(block: &[u8]) -> Option<(usize, usize)> { let dtd_range = cta_dtd_range(block)?; block[dtd_range.clone()] - .chunks_exact(DTD_LEN) + .as_chunks::() + .0 + .iter() .enumerate() .find(|(_, descriptor)| descriptor.iter().all(|byte| *byte == 0)) .map(|(slot, _)| (slot, dtd_range.start + slot * DTD_LEN)) @@ -1121,8 +1143,10 @@ fn cta_empty_dtd_slot(block: &[u8]) -> Option<(usize, usize)> { fn empty_standard_timing_slot(raw: &[u8]) -> Option { raw[STANDARD_TIMING_START..STANDARD_TIMING_START + STANDARD_TIMING_SLOTS * STANDARD_TIMING_LEN] - .chunks_exact(STANDARD_TIMING_LEN) - .position(|timing| timing == [0x01, 0x01]) + .as_chunks::() + .0 + .iter() + .position(|timing| *timing == [0x01, 0x01]) } fn standard_timing_offset(raw: &[u8], slot: usize) -> Result { @@ -1258,7 +1282,9 @@ fn parse_established_timings(base: &[u8]) -> Vec { fn parse_standard_timings(base: &[u8]) -> Vec { base[STANDARD_TIMING_START..STANDARD_TIMING_START + STANDARD_TIMING_SLOTS * STANDARD_TIMING_LEN] - .chunks_exact(STANDARD_TIMING_LEN) + .as_chunks::() + .0 + .iter() .enumerate() .filter_map(|(slot, timing)| parse_standard_timing(slot, timing[0], timing[1])) .collect() @@ -1495,7 +1521,12 @@ mod tests { assert_eq!(raw[index], before[index]); } } - assert!(raw.chunks_exact(128).all(block_checksum_valid)); + assert!( + raw.as_chunks::<128>() + .0 + .iter() + .all(|block| block_checksum_valid(block)) + ); assert_eq!(clear_detailed_timing_stereo(&mut raw), 0); } } @@ -1526,7 +1557,12 @@ mod tests { assert_eq!(clear_detailed_timing_stereo(&mut raw), 0); assert_eq!(raw, before); - assert!(raw.chunks_exact(EDID_BLOCK_LEN).all(block_checksum_valid)); + assert!( + raw.as_chunks::() + .0 + .iter() + .all(|block| block_checksum_valid(block)) + ); } #[test] @@ -1954,8 +1990,10 @@ mod tests { assert_eq!(&patched[128..256], displayid.as_slice()); assert!( patched - .chunks_exact(EDID_BLOCK_LEN) - .all(block_checksum_valid) + .as_chunks::() + .0 + .iter() + .all(|block| block_checksum_valid(block)) ); let parsed = parse_edid(patched).expect("parse expanded EDID"); diff --git a/src/export.rs b/src/export.rs index 43b78df..933b92d 100644 --- a/src/export.rs +++ b/src/export.rs @@ -229,7 +229,7 @@ mod tests { raw[71] |= 0x61; raw[154] |= 0x61; // Repair fixture checksums before exercising validation and export. - for block in raw.chunks_exact_mut(128) { + for block in raw.as_chunks_mut::<128>().0.iter_mut() { block[127] = 0u8.wrapping_sub( block[..127] .iter() @@ -260,8 +260,10 @@ mod tests { } assert!( bytes - .chunks_exact(128) - .all(crate::edid::block_checksum_valid) + .as_chunks::<128>() + .0 + .iter() + .all(|block| crate::edid::block_checksum_valid(block)) ); fs::remove_dir_all(directory).unwrap(); } @@ -273,7 +275,7 @@ mod tests { for (offset, flags) in [(71, 0x19), (89, 0x1b), (154, 0x1b), (172, 0x19)] { raw[offset] = flags; } - for block in raw.chunks_exact_mut(128) { + for block in raw.as_chunks_mut::<128>().0.iter_mut() { block[127] = 0u8.wrapping_sub( block[..127] .iter() @@ -318,8 +320,10 @@ mod tests { assert_eq!(exported, expected); assert!( exported - .chunks_exact(128) - .all(crate::edid::block_checksum_valid) + .as_chunks::<128>() + .0 + .iter() + .all(|block| crate::edid::block_checksum_valid(block)) ); fs::remove_dir_all(directory).unwrap(); } diff --git a/src/hyprland_config.rs b/src/hyprland_config.rs index f1dc66e..11c4d23 100644 --- a/src/hyprland_config.rs +++ b/src/hyprland_config.rs @@ -601,10 +601,10 @@ fn resolve_lua_require(module: &str, including_file: &Path) -> Option { let module_path = PathBuf::from(module.replace('.', "/")); let parent = including_file.parent().unwrap_or_else(|| Path::new(".")); let mut roots = vec![parent.to_path_buf()]; - if parent.file_name().is_some_and(|name| name == "hypr") { - if let Some(config_root) = parent.parent() { - roots.push(config_root.to_path_buf()); - } + if parent.file_name().is_some_and(|name| name == "hypr") + && let Some(config_root) = parent.parent() + { + roots.push(config_root.to_path_buf()); } for root in roots { @@ -622,11 +622,11 @@ fn resolve_lua_require(module: &str, including_file: &Path) -> Option { fn normalize_monitor_rule(rule: &str) -> Option { let rule = rule.trim(); - if let Some((key, value)) = parse_assignment(rule) { - if key == "monitor" { - return parse_monitor_rule(Path::new(""), 1, rule, value) - .map(|parsed| parsed.normalized_rule()); - } + if let Some((key, value)) = parse_assignment(rule) + && key == "monitor" + { + return parse_monitor_rule(Path::new(""), 1, rule, value) + .map(|parsed| parsed.normalized_rule()); } find_lua_calls(rule) @@ -732,20 +732,20 @@ fn resolve_source_paths( fn expand_config_path(value: &str) -> String { let value = value.trim_matches('"').trim_matches('\''); - if let Some(rest) = value.strip_prefix("~/") { - if let Some(home) = std::env::var_os("HOME") { - return PathBuf::from(home).join(rest).display().to_string(); - } + if let Some(rest) = value.strip_prefix("~/") + && let Some(home) = std::env::var_os("HOME") + { + return PathBuf::from(home).join(rest).display().to_string(); } - if let Some(rest) = value.strip_prefix("$HOME/") { - if let Some(home) = std::env::var_os("HOME") { - return PathBuf::from(home).join(rest).display().to_string(); - } + if let Some(rest) = value.strip_prefix("$HOME/") + && let Some(home) = std::env::var_os("HOME") + { + return PathBuf::from(home).join(rest).display().to_string(); } - if let Some(rest) = value.strip_prefix("$XDG_CONFIG_HOME/") { - if let Some(config_home) = std::env::var_os("XDG_CONFIG_HOME") { - return PathBuf::from(config_home).join(rest).display().to_string(); - } + if let Some(rest) = value.strip_prefix("$XDG_CONFIG_HOME/") + && let Some(config_home) = std::env::var_os("XDG_CONFIG_HOME") + { + return PathBuf::from(config_home).join(rest).display().to_string(); } value.to_string() } diff --git a/src/tui/actions.rs b/src/tui/actions.rs index d96da61..872fea2 100644 --- a/src/tui/actions.rs +++ b/src/tui/actions.rs @@ -660,10 +660,10 @@ impl App { let mut deleted = 0usize; for location in locations { - if let Some(workspace) = self.selected_workspace_mut() { - if workspace.delete_dtd(location).is_ok() { - deleted += 1; - } + if let Some(workspace) = self.selected_workspace_mut() + && workspace.delete_dtd(location).is_ok() + { + deleted += 1; } } self.selected_extension = None; @@ -1173,10 +1173,11 @@ impl App { } fn selected_or_first_free_cta_slot(&self) -> Option<(u8, usize)> { - if let Some(row) = self.selected_extension_slot() { - if row.timing.is_none() && !row.occupied_unknown { - return Some((row.extension_index, row.slot)); - } + if let Some(row) = self.selected_extension_slot() + && row.timing.is_none() + && !row.occupied_unknown + { + return Some((row.extension_index, row.slot)); } self.working_extension_rows() @@ -1432,17 +1433,17 @@ impl App { } } - if let Some(status) = override_status { - if !status.read_warnings.is_empty() { - lines.push(String::new()); - lines.push("Read warnings".to_string()); - lines.extend( - status - .read_warnings - .into_iter() - .map(|warning| format!("- {warning}")), - ); - } + if let Some(status) = override_status + && !status.read_warnings.is_empty() + { + lines.push(String::new()); + lines.push("Read warnings".to_string()); + lines.extend( + status + .read_warnings + .into_iter() + .map(|warning| format!("- {warning}")), + ); } self.detailed_editor = None; @@ -2156,15 +2157,15 @@ pub(super) fn normalize_import_path(value: &str, home: Option<&Path>) -> PathBuf .map(Path::to_path_buf) .unwrap_or_else(|| PathBuf::from(value)); } - if let Some(rest) = value.strip_prefix("~/") { - if let Some(home) = home { - return home.join(rest); - } + if let Some(rest) = value.strip_prefix("~/") + && let Some(home) = home + { + return home.join(rest); } - if let Some(rest) = value.strip_prefix("$HOME/") { - if let Some(home) = home { - return home.join(rest); - } + if let Some(rest) = value.strip_prefix("$HOME/") + && let Some(home) = home + { + return home.join(rest); } PathBuf::from(value) diff --git a/src/tui/input.rs b/src/tui/input.rs index e21795b..9c83ed4 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -67,15 +67,14 @@ impl App { pub(super) fn handle_mouse(&mut self, mouse: MouseEvent) { if self.vrr_editor.is_some() { - if let MouseEventKind::Down(MouseButton::Left) = mouse.kind { - if let Some(hitbox) = self.hit_test(mouse.column, mouse.row) { - if matches!( - hitbox.target, - HitTarget::VrrField(_) | HitTarget::ModalButton(_) - ) { - self.activate_hit(hitbox, mouse.column); - } - } + if let MouseEventKind::Down(MouseButton::Left) = mouse.kind + && let Some(hitbox) = self.hit_test(mouse.column, mouse.row) + && matches!( + hitbox.target, + HitTarget::VrrField(_) | HitTarget::ModalButton(_) + ) + { + self.activate_hit(hitbox, mouse.column); } return; } diff --git a/src/workspace.rs b/src/workspace.rs index 9ccc94d..4ce6273 100644 --- a/src/workspace.rs +++ b/src/workspace.rs @@ -289,7 +289,7 @@ impl EdidWorkspace { }); } - for (index, block) in self.working.raw.chunks_exact(128).enumerate() { + for (index, block) in self.working.raw.as_chunks::<128>().0.iter().enumerate() { if !block_checksum_valid(block) { issues.push(ValidationIssue { message: if index == 0 { From 656699b5c455fcc7b3fd462f6f1807403c961352 Mon Sep 17 00:00:00 2001 From: Lorenzo Golluscio <149246609+ssupt@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:27:33 +0100 Subject: [PATCH 3/4] Preserve boot arguments and images; fix CTA deletion and interlace Preserve the effective root, encryption and per-kernel arguments when consolidating EDID overrides, including settings outside drmcru's drop-in. Build and inspect each kernel and fallback image directly so a successful wrapper exit cannot hide failed or stale output. Snapshot the boot partition and restore generated images, boot entries, configuration and firmware on failure. Retain the previous entry and its resources for recovery, and verify images, arguments and hashes after hooks. Reject connector mappings that Linux would also apply to another connector. Compact CTA detailed timings on deletion and update the native timing count. Represent interlaced geometry in frame lines and convert field values only when decoding or encoding EDID, keeping editor and runtime rates consistent. Add regression fixtures for partial rebuilds, rollback, command-line ordering, multiple monitors, kernel changes, prefix collisions and timing edits. --- src/boot_transaction.sh | 542 +++++++++ src/edid.rs | 204 +++- src/export.rs | 1 + src/install.rs | 1760 +++------------------------ src/install_tests.rs | 1095 +++++++++++++++++ src/kernel_cmdline.awk | 66 + src/limine_entry.awk | 18 + src/models.rs | 29 +- src/timings.rs | 2 +- src/tui/actions.rs | 13 +- src/tui/mod.rs | 19 + src/tui/state.rs | 60 +- src/validation.rs | 14 +- src/workspace.rs | 5 + tests/fixtures/limine-entry-tool.py | 94 ++ tests/fixtures/mkinitcpio.sh | 40 + 16 files changed, 2323 insertions(+), 1639 deletions(-) create mode 100644 src/boot_transaction.sh create mode 100644 src/install_tests.rs create mode 100644 src/kernel_cmdline.awk create mode 100644 src/limine_entry.awk create mode 100644 tests/fixtures/limine-entry-tool.py create mode 100644 tests/fixtures/mkinitcpio.sh diff --git a/src/boot_transaction.sh b/src/boot_transaction.sh new file mode 100644 index 0000000..b19ca97 --- /dev/null +++ b/src/boot_transaction.sh @@ -0,0 +1,542 @@ +# The generated prologue supplies paths, plans and the literal config editors. +set -Eeuo pipefail +shopt -s nullglob +shopt -s inherit_errexit +die() { echo "[ERR] $*" >&2; exit 1; } +declare -a BACKUP_ORIGINALS=() BACKUP_PATHS=() NEW_PATHS=() NEW_DIRS=() +declare -a KERNEL_NAMES=() KERNEL_VERSIONS=() KEYS=() IMAGES=() IMAGE_KEYS=() IMAGE_NAMES=() DESTINATIONS=() +declare -A KEY_SEEN=() ORIGINAL_CMDLINES=() EXPECTED_CMDLINES=() +TX=""; MUTATED=0; SNAPSHOT_READY=0; COMMITTED=0; PACKAGE_LOCK_OWNED=0 +BACKUP_SUFFIX=".drmcru.$(date +%Y%m%d-%H%M%S-%N)-$$.bak" + +backup_file() { + local file="$1" previous + [ ! -L "$file" ] || die "Configuration or firmware is a symlink: $file" + for previous in "${BACKUP_ORIGINALS[@]}" "${NEW_PATHS[@]}"; do [ "$previous" != "$file" ] || return 0; done + if [ -e "$file" ]; then + [ -f "$file" ] && [ ! -L "$file" ] || die "Not a regular configuration file: $file" + cp -a -- "$file" "$file$BACKUP_SUFFIX" + BACKUP_ORIGINALS+=("$file"); BACKUP_PATHS+=("$file$BACKUP_SUFFIX") + else + NEW_PATHS+=("$file") + fi +} + +restore_boot() { + local path relative original failed=0 + [ "$SNAPSHOT_READY" -eq 1 ] || return 0 + # Remove newly created objects and type changes without following links. + while IFS= read -r -d '' path; do + relative="${path#"$BOOT_ROOT/"}"; original="$TX/boot/$relative" + if [ -d "$path" ] && [ ! -L "$path" ]; then + if [ ! -d "$original" ]; then rmdir -- "$path" || failed=1; fi + elif [ ! -f "$original" ] || [ -L "$path" ]; then + rm -f -- "$path" || failed=1 + fi + done < <(find "$BOOT_ROOT" -mindepth 1 -depth -print0) + cp -a -- "$TX/boot/." "$BOOT_ROOT/" || failed=1 + diff -qr --no-dereference -- "$TX/boot" "$BOOT_ROOT" >/dev/null || failed=1 + return "$failed" +} + +finish() { + local status="$?" failed=0 i + trap - EXIT HUP INT TERM + set +e + if [ "$COMMITTED" -eq 0 ] && [ "$MUTATED" -eq 1 ]; then + for ((i=${#BACKUP_ORIGINALS[@]} - 1; i >= 0; i--)); do + cp -a --remove-destination -- "${BACKUP_PATHS[$i]}" "${BACKUP_ORIGINALS[$i]}" || failed=1 + cmp -s -- "${BACKUP_PATHS[$i]}" "${BACKUP_ORIGINALS[$i]}" || failed=1 + done + for i in "${NEW_PATHS[@]}"; do rm -f -- "$i" || failed=1; done + restore_boot || failed=1 + for ((i=${#NEW_DIRS[@]} - 1; i >= 0; i--)); do rmdir -- "${NEW_DIRS[$i]}" 2>/dev/null || true; done + if [ "$failed" -eq 0 ]; then + echo "[OK] Restored configuration, firmware and boot artifacts after failure" >&2 + else + echo "[ERR] Recovery was incomplete. Do not reboot. Recovery files: $TX" >&2 + status=1 + fi + fi + if [ "$PACKAGE_LOCK_OWNED" -eq 1 ] && [ "$(cat "$PACKAGE_LOCK" 2>/dev/null)" = "drmcru-$$" ]; then rm -f -- "$PACKAGE_LOCK"; fi + if [ -n "$TX" ] && [ "$failed" -eq 0 ]; then rm -rf -- "$TX"; fi + exit "$status" +} +trap finish EXIT +trap 'exit 129' HUP +trap 'exit 130' INT +trap 'exit 143' TERM + +add_key() { + [[ "$1" =~ ^[A-Za-z0-9._+-]+$ ]] || die "Unsupported Limine kernel key: $1" + if [ -z "${KEY_SEEN[$1]:-}" ]; then KEYS+=("$1"); KEY_SEEN[$1]=1; fi +} +cmdline() { + local output + output="$("$ENTRY_TOOL_BIN" --get-cmdline "$1" --no-mutex --no-hooks)" + printf '%s\n' "$output" | tail -n 1 +} +canonical() { printf '%s\n' "$1" | awk -v operation=keep "$CMDLINE_AWK"; } +old_value() { + awk -v key="$1" ' + { + line=$0; state=sub(/^[[:space:]]*# drmcru-(map|extra)\[/,"KERNEL_CMDLINE[",line) + if(line !~ /^[[:space:]]*KERNEL_CMDLINE\[/) next + sub(/^[[:space:]]*KERNEL_CMDLINE\[/,"",line) + name=line; sub(/\].*/,"",name) + sub(/^[^]]*\][[:space:]]*/,"",line); append=state || (substr(line,1,2)=="+=") + sub(/^\+?=[[:space:]]*/,"",line) + if(line ~ /^".*"$/) line=substr(line,2,length(line)-2) + values[name]=append ? values[name] " " line : line; seen[name]=1 + } + END { + if(key in seen) print values[key] + else if(index(key,"fallback") && ("fallback" in seen)) print values["fallback"] + else print values["default"] + } + ' "$TX/old-owned.conf" +} +old_removals() { + awk -v key="$1" ' + /^# drmcru-remove\[/ { + line=$0; sub(/^# drmcru-remove\[/,"",line) + name=line; sub(/\].*/,"",name); sub(/^[^]]*\]=/,"",line) + values[name]=line; seen[name]=1 + } + END { + if(key in seen) print values[key] + else if(index(key,"fallback") && ("fallback" in seen)) print values["fallback"] + else print values["default"] + } + ' "$TX/old-owned.conf" +} + +check_mapping() { + local mapping="$1" name file path other + name="${mapping%%:*}"; file="${mapping#*:}" + if [ "$mapping" = "$file" ]; then name=""; fi + [[ "$file" =~ ^[A-Za-z0-9_./-]+$ ]] && [[ "$file" != /* && "/$file/" != *"/../"* && "/$file/" != *"/./"* ]] || die "Unsafe firmware mapping: $mapping" + if [ -n "$name" ]; then + [[ "$name" =~ ^[A-Za-z0-9._-]+$ ]] || die "Unsafe connector name: $name" + local matches=0 + for path in "$DRM_ROOT"/card*-*/status; do + other="${path%/status}"; other="${other##*/}"; other="${other#*-}" + if [[ "$other" == "$name"* ]]; then + [ "$other" = "$name" ] || die "Connector mapping $name also matches $other in Linux" + matches=$((matches + 1)) + fi + done + [ "$matches" -le 1 ] || die "Connector $name exists on multiple DRM devices" + if [ "$OPERATION" = add ] && [ "$name" = "$CONNECTOR" ]; then + [ "$matches" -eq 1 ] || die "Connector $name is no longer available" + fi + fi +} + +check_image() { + local image="$1" key="$2" extract="$TX/extract" mappings mapping file actual resolved embedded + [ -s "$image" ] || die "Image was not produced for $key" + rm -rf -- "$extract"; mkdir -- "$extract" + (cd "$extract"; "$LSINITCPIO_BIN" --extract "$image" >/dev/null) + mappings="$(printf '%s\n' "${EXPECTED_CMDLINES[$key]}" | awk -v operation=mappings "$CMDLINE_AWK")" + while IFS= read -r mapping; do + [ -n "$mapping" ] || continue + file="${mapping#*:}" + actual="$extract/usr/lib/firmware/$file" + [ -e "$actual" ] || actual="$extract/lib/firmware/$file" + resolved="$(realpath -e -- "$actual")" + [[ "$resolved" == "$extract/"* ]] || die "Firmware escapes extracted image: $file" + cmp -s -- "$FIRMWARE_ROOT/$file" "$resolved" || die "Image $key contains missing or outdated firmware: $file" + done <<< "$mappings" + if [ "$OPERATION" = remove ] && [ "$KEEP_FIRMWARE" -eq 0 ]; then + [ ! -e "$extract/usr/lib/firmware/edid/$EDID_NAME" ] && [ ! -e "$extract/lib/firmware/edid/$EDID_NAME" ] || die "Image $key still contains the removed EDID" + fi + if [ "$IMAGE_KIND" = uki ]; then + "$OBJCOPY_BIN" --only-section=.cmdline -O binary "$image" "$TX/embedded-cmdline" + embedded="$(tr -d '\000' < "$TX/embedded-cmdline")" + if [ "$EMBED_CMDLINE" -eq 1 ]; then + [ "$(canonical "$embedded")" = "${EXPECTED_CMDLINES[$key]}" ] || die "UKI command line differs for $key" + else + [ -z "$embedded" ] || die "Unexpected embedded UKI command line for $key" + fi + fi + rm -rf -- "$extract" +} + +strict_hooks() { + local hook + for hook in "$BOOT_HOOKS/$1.d/"*; do + [ -f "$hook" ] && [ -x "$hook" ] && [[ "$hook" != *.disabled ]] || continue + "$hook" + done +} +declare -A RESOURCE_HASHES=() +check_installed_entry() { + local key="$1" relative="$2" actual + awk -v wanted="$relative" "$ENTRY_AWK" "$LIMINE" > "$TX/installed-entry" + actual="$(sed -n 's/^[[:space:]]*cmdline:[[:space:]]*//p' "$TX/installed-entry" | tail -n1)" + if [ "$IMAGE_KIND" != uki ] || [ "$EMBED_CMDLINE" -eq 0 ] || [ -n "$actual" ]; then + [ "$(canonical "$actual")" = "${EXPECTED_CMDLINES[$key]}" ] || die "Installed boot arguments differ for $key" + fi +} +refresh_hashes() { + local line prefix uri relative + while IFS= read -r line || [ -n "$line" ]; do + if [[ "$line" =~ ^([[:space:]]*(path|kernel_path|module_path):[[:space:]]*)boot\(\):/(.*)$ ]]; then + prefix="${BASH_REMATCH[1]}"; uri="${BASH_REMATCH[3]}"; relative="${uri%%#*}" + if [ -n "${RESOURCE_HASHES[$relative]:-}" ]; then + printf '%sboot():/%s#%s\n' "$prefix" "$relative" "${RESOURCE_HASHES[$relative]}" + continue + fi + fi + printf '%s\n' "$line" + done < "$LIMINE" +} + +# Validate the supported stack before touching configuration or firmware. +[ "$(id -u)" -eq 0 ] || die "This installer must run as root" +[[ "$CONNECTOR" =~ ^[A-Za-z0-9._-]+$ && "$EDID_NAME" =~ ^[A-Za-z0-9._-]+$ && "$EDID_NAME" != . && "$EDID_NAME" != .. ]] || die "Unsafe connector or EDID file name" +for tool in mkinitcpio lsinitcpio objcopy limine-entry-tool limine-mkinitcpio pacman flock b2sum realpath diff findmnt; do + command -v "$tool" >/dev/null || die "$tool is required for verified automatic installation; use Export on this system" +done +for tool in "$MKINITCPIO_BIN" "$LSINITCPIO_BIN" "$ENTRY_TOOL_BIN" "$OBJCOPY_BIN"; do + [ -x "$tool" ] || die "Verified installation tool is missing: $tool" +done +[ -d "$BOOT_ROOT" ] && [ ! -L "$BOOT_ROOT" ] || die "Boot root must be a regular directory" +[ -f "$MKINIT" ] && [ ! -L "$MKINIT" ] || die "/etc/mkinitcpio.conf not found or not a regular file" +[ -f "$LIMINE" ] && [ ! -L "$LIMINE" ] || die "/boot/limine.conf not found or not a regular file" +grep -qE '^[[:space:]]*cmdline:' "$LIMINE" || die "/boot/limine.conf has no cmdline entries" +[ "$OPERATION" != add ] || [ -s "$EDID_SOURCE" ] || die "EDID source does not exist: $EDID_SOURCE" +[ -f "$LIMINE_FUNCTIONS" ] || die "Limine entry-tool integration is unavailable" +for directory in "$MKINIT_DROPIN_DIR" "$LIMINE_DROPIN_DIR" "${LIMINE_DEFAULT_CONFIG%/*}" "${FIRMWARE_TARGET%/*}"; do + [ ! -L "$directory" ] || die "Managed directory is a symlink: $directory" +done +# This is a root-owned library shipped by the supported Limine package. +source "$LIMINE_FUNCTIONS" +load_config +resolved_esp="$(realpath -e -- "$ESP_PATH")"; resolved_boot="$(realpath -e -- "$BOOT_ROOT")" +[ "$resolved_esp" = "$resolved_boot" ] || die "Automatic installation currently requires the Limine boot partition at $BOOT_ROOT" +check_boot_partition "$BOOT_ROOT" +[ -z "$(find "$BOOT_ROOT" -mindepth 1 ! -type f ! -type d -print -quit)" ] || die "Boot partition contains links or special files; use manual Export" +[ "$(findmnt -Rno TARGET "$BOOT_ROOT" | wc -l)" -eq 1 ] || die "Nested boot mounts require manual Export" +[ -s "$MACHINE_ID_FILE" ] || die "Machine ID is missing" +MACHINE_ID="$(cat "$MACHINE_ID_FILE")" +[[ "$MACHINE_ID" =~ ^[a-fA-F0-9]{32}$ ]] || die "Invalid machine ID" +UKI_PREFIX="${CUSTOM_UKI_NAME:-$MACHINE_ID}" +[[ "$UKI_PREFIX" =~ ^[a-z0-9]+$ ]] || die "Invalid custom UKI prefix" +IMAGE_KIND=initramfs; EMBED_CMDLINE=1 +if [ "${ENABLE_UKI:-no}" = yes ] && is_uefi; then + IMAGE_KIND=uki + if is_sb_installed && is_snapper_installed; then EMBED_CMDLINE=0; fi +fi +declare -a UKI_OPTIONS=() +read -r -a requested_options <<< "${MKINITCPIO_UKI_OPTIONS:-}" +for ((i=0; i<${#requested_options[@]}; i++)); do + option="${requested_options[$i]}" + case "$option" in + --no-ukify) UKI_OPTIONS+=("$option") ;; + --splash|--uefistub|--ukiconfig) + i=$((i+1)); [ "$i" -lt "${#requested_options[@]}" ] || die "Missing value for $option" + UKI_OPTIONS+=("$option" "${requested_options[$i]}") ;; + *) die "Unverified mkinitcpio option $option; use Export" ;; + esac +done +if [ "$OPERATION" = add ]; then check_mapping "$CONNECTOR:edid/$EDID_NAME"; fi +check_mkinitcpio_dropins +mkdir -p -- "${BOOT_LOCK%/*}" +exec 201>"$BOOT_LOCK"; flock --timeout=30 201 || die "Another boot operation is running" +(set -o noclobber; printf 'drmcru-%s' "$$" > "$PACKAGE_LOCK") 2>/dev/null || die "A package transaction is running" +PACKAGE_LOCK_OWNED=1 +TX="$(mktemp -d "$TRANSACTION_ROOT/drmcru-boot.XXXXXXXX")"; chmod 700 "$TX" +mkdir -- "$TX/boot" +cp -a -- "$BOOT_ROOT/." "$TX/boot/" +diff -qr --no-dereference -- "$TX/boot" "$BOOT_ROOT" >/dev/null +SNAPSHOT_READY=1 + +add_key default; add_key fallback +declare -A KERNEL_SEEN=() +for directory in "$MODULES_ROOT"/*; do + [ -f "$directory/modules.builtin" ] && [ -f "$directory/vmlinuz" ] || continue + name="$(pacman -Qqo "$directory/modules.builtin")" + [[ "$name" =~ ^[A-Za-z0-9._+-]+$ ]] || die "Unsupported kernel package name: $name" + [ -z "${KERNEL_SEEN[$name]:-}" ] || die "Multiple installed versions of $name require manual Export" + KERNEL_SEEN[$name]=1 + KERNEL_NAMES+=("$name"); KERNEL_VERSIONS+=("${directory##*/}") + add_key "$name"; add_key "$name-fallback" +done +[ "${#KERNEL_NAMES[@]}" -gt 0 ] || die "No installed kernels could be verified" +for config in "$LIMINE_VENDOR_DIR/"*.conf "$LIMINE_CONFIG" "$LIMINE_DROPIN_DIR/"*.conf "$LIMINE_DEFAULT_CONFIG"; do + [ -f "$config" ] || continue + config_keys="$(awk ' + /^[[:space:]]*KERNEL_CMDLINE\[/ { line=$0; sub(/^[[:space:]]*KERNEL_CMDLINE\[/,"",line); sub(/\].*/,"",line); print line } + ' "$config")" + while IFS= read -r key; do [ -z "$key" ] || add_key "$key"; done <<< "$config_keys" +done +for key in "${KEYS[@]}"; do + current="$(cmdline "$key")" + ORIGINAL_CMDLINES[$key]="$(canonical "$current")" +done + +# Keep an existing bootable entry and its exact resources for recovery. +RECOVERY_RECORD="$TX/recovery-entry" +for name in "${KERNEL_NAMES[@]}"; do + for relative in "EFI/Linux/${UKI_PREFIX}_${name}.efi" "$MACHINE_ID/$name/vmlinuz"; do + if awk -v wanted="$relative" "$ENTRY_AWK" "$TX/boot/limine.conf" > "$RECOVERY_RECORD"; then break 2; fi + done +done +[ -s "$RECOVERY_RECORD" ] || die "No existing kernel entry could be preserved for recovery" +if [ -e "$BOOT_ROOT/drmcru-recovery" ]; then + [ -f "$BOOT_ROOT/drmcru-recovery/.drmcru-owned" ] || die "Recovery path is not owned by drmcru" +fi + +for path in "$MKINIT" "$MKINIT_DROPIN" "$LIMINE_DROPIN" "$LIMINE_DEFAULT_CONFIG" "$FIRMWARE_TARGET"; do backup_file "$path"; done +for config in "$LIMINE_VENDOR_DIR/"*.conf "$LIMINE_CONFIG" "$LIMINE_DROPIN_DIR/"*.conf "$LIMINE_DEFAULT_CONFIG"; do + [ ! -f "$config" ] || backup_file "$config" +done +for directory in "$MKINIT_DROPIN_DIR" "$LIMINE_DROPIN_DIR" "${FIRMWARE_TARGET%/*}" "${LIMINE_DEFAULT_CONFIG%/*}"; do + if [ ! -d "$directory" ]; then NEW_DIRS+=("$directory"); fi +done +[ ! -f "$LIMINE_DROPIN" ] || cp -a -- "$LIMINE_DROPIN" "$TX/old-owned.conf" +touch "$TX/old-owned.conf" +MANAGED_SNAPSHOT=0 +if head -n 1 "$TX/old-owned.conf" | grep -q '^# drmcru mapping state v1$'; then + recorded="$(sed -n '2s/^# sha256=//p' "$TX/old-owned.conf")" + actual="$(tail -n +3 "$TX/old-owned.conf" | sha256sum | cut -d ' ' -f1)" + [ "$recorded" = "$actual" ] || die "Managed Limine configuration was edited; move custom settings to /etc/default/limine first" + awk '!/^[[:space:]]*(KERNEL_CMDLINE\[|# drmcru-(map|extra|remove)\[)/ && NR>2' "$TX/old-owned.conf" > "$TX/base-owned.conf" + MANAGED_SNAPSHOT=1 +else + # Legacy EDID-only defaults must disappear so the original fallback works. + awk '!/^[[:space:]]*KERNEL_CMDLINE\[/' "$TX/old-owned.conf" > "$TX/base-owned.conf" +fi +MUTATED=1 +mkdir -p -- "$LIMINE_DROPIN_DIR" +install -m 0644 -- "$TX/base-owned.conf" "$LIMINE_DROPIN" +mkdir -p -- "${LIMINE_DEFAULT_CONFIG%/*}" +touch "$LIMINE_DEFAULT_CONFIG" +awk ' + /^# BEGIN drmcru command lines$/ { if(inside || seen++) exit 1; inside=1; next } + /^# END drmcru command lines$/ { if(!inside) exit 1; inside=0; next } + !inside { print } + END { if(inside) exit 1 } +' "$LIMINE_DEFAULT_CONFIG" > "$TX/default-base.conf" +awk ' + /^# BEGIN drmcru command lines$/ { inside=1; next } + /^# END drmcru command lines$/ { inside=0; next } + inside { print } +' "$LIMINE_DEFAULT_CONFIG" > "$TX/old-command-lines.conf" +cat "$TX/default-base.conf" > "$LIMINE_DEFAULT_CONFIG" +cp -- "$TX/base-owned.conf" "$TX/new-owned.conf" +: > "$TX/command-lines.conf" +KEEP_FIRMWARE=0; NEED_COMMAND_BLOCK=0 +for key in "${KEYS[@]}"; do + current="$(cmdline "$key")" + base="$(canonical "$current")" + [ -n "$base" ] || die "Effective kernel command line is empty for $key" + inherited="$(old_value "$key")" + extra="$(printf '%s\n' "$inherited" | awk -v operation=strip "$CMDLINE_AWK")" + retained="$(printf '%s\n' "${ORIGINAL_CMDLINES[$key]}" | awk -v operation=strip "$CMDLINE_AWK")" + baseline_others="$(printf '%s\n' "$base" | awk -v operation=strip "$CMDLINE_AWK")" + previous="$(awk -v prefix="KERNEL_CMDLINE[$key]=" 'index($0,prefix)==1 { print substr($0,length(prefix)+1) }' "$TX/old-command-lines.conf")" + previous_others="$(printf '%s\n' "$previous" | awk -v operation=strip "$CMDLINE_AWK")" + if [ -z "$retained" ] || { [ "$MANAGED_SNAPSHOT" -eq 0 ] && [ "$retained" = "$extra" ]; } \ + || { [ -n "$previous" ] && [ "$retained" = "$previous_others" ]; }; then + retained="$baseline_others${extra:+ $extra}" + fi + removals="$(old_removals "$key")" + if [ "$OPERATION" = remove ]; then removals="${removals:+$removals,}$CONNECTOR:edid/$EDID_NAME"; fi + removals="$(printf '%s\n' "$base" | awk -v operation=mappings "$CMDLINE_AWK" | awk -v candidates="$removals" ' + BEGIN { split(candidates, parts, ","); for(i in parts) wanted[parts[i]]=1 } + $0 in wanted { result=result (result=="" ? "" : ",") $0 } + END { print result } + ')" + expected="$(printf '%s\n%s\n' "$base" "$inherited" | awk -v operation="$OPERATION" -v connector="$CONNECTOR" -v firmware="edid/$EDID_NAME" -v suppressed="$removals" -v replace_others=1 -v retained_others="$retained" "$CMDLINE_AWK")" + EXPECTED_CMDLINES[$key]="$expected" + contribution="$(printf '\n%s\n' "$inherited" | awk -v operation="$OPERATION" -v connector="$CONNECTOR" -v firmware="edid/$EDID_NAME" -v suppressed="$removals" "$CMDLINE_AWK")" + [ -z "$contribution" ] || printf '# drmcru-map[%s]= %s\n' "$key" "$contribution" >> "$TX/new-owned.conf" + [ -z "$extra" ] || printf '# drmcru-extra[%s]=%s\n' "$key" "$extra" >> "$TX/new-owned.conf" + [ -z "$removals" ] || printf '# drmcru-remove[%s]=%s\n' "$key" "$removals" >> "$TX/new-owned.conf" + printf 'KERNEL_CMDLINE[%s]=%s\n' "$key" "$expected" >> "$TX/command-lines.conf" + [ "$expected" = "$base" ] || NEED_COMMAND_BLOCK=1 + mappings="$(printf '%s\n' "$expected" | awk -v operation=mappings "$CMDLINE_AWK")" + while IFS= read -r mapping; do + [ -n "$mapping" ] || continue + check_mapping "$mapping" + [ "${mapping#*:}" != "edid/$EDID_NAME" ] || KEEP_FIRMWARE=1 + done <<< "$mappings" +done +body_hash="$(sha256sum "$TX/new-owned.conf")" +{ + echo '# drmcru mapping state v1' + printf '# sha256=%s\n' "${body_hash%% *}" + cat -- "$TX/new-owned.conf" +} > "$LIMINE_DROPIN" +if [ "$NEED_COMMAND_BLOCK" -eq 1 ]; then + { echo '# BEGIN drmcru command lines'; cat "$TX/command-lines.conf"; echo '# END drmcru command lines'; } >> "$LIMINE_DEFAULT_CONFIG" +fi +for key in "${KEYS[@]}"; do + current="$(cmdline "$key")" + [ "$(canonical "$current")" = "${EXPECTED_CMDLINES[$key]}" ] || die "A higher-priority Limine setting overrides $key; use Export" +done +if [ "$OPERATION" = add ]; then install -D -m 0644 -- "$EDID_SOURCE" "$FIRMWARE_TARGET"; +elif [ "$KEEP_FIRMWARE" -eq 0 ]; then rm -f -- "$FIRMWARE_TARGET"; fi +if [ "$OPERATION" = remove ] && [ "$KEEP_FIRMWARE" -eq 0 ]; then update_mkinitcpio_dropin remove; fi +remove_legacy_mkinitcpio_entry +# Every referenced firmware file must be available in each early initramfs. +for key in "${KEYS[@]}"; do + mappings="$(printf '%s\n' "${EXPECTED_CMDLINES[$key]}" | awk -v operation=mappings "$CMDLINE_AWK")" + while IFS= read -r mapping; do + [ -n "$mapping" ] || continue + file="${mapping#*:}" + [ -f "$FIRMWARE_ROOT/$file" ] || die "Referenced EDID firmware is missing: $file" + append_firmware() { local FIRMWARE_TARGET="$FIRMWARE_ROOT/$file"; update_mkinitcpio_dropin add; } + append_firmware + done <<< "$mappings" +done + +export HOOK_CALLER=drmcru HOOK_CMDLINE="$OPERATION $CONNECTOR" +strict_hooks pre +# Build and inspect every default/fallback before replacing any boot image. +for ((k=0; k<${#KERNEL_NAMES[@]}; k++)); do + name="${KERNEL_NAMES[$k]}"; version="${KERNEL_VERSIONS[$k]}" + fallbacks=(default) + if [ "${MKINITCPIO_FALLBACK:-}" = yes ] || [ "${MKINITCPIO_FALLBACK:-}" = "$name" ] \ + || [ -f "$TX/boot/$MACHINE_ID/$name/initramfs-fallback" ] \ + || [ -f "$TX/boot/EFI/Linux/${UKI_PREFIX}_${name}-fallback.efi" ]; then fallbacks+=(fallback); fi + for variant in "${fallbacks[@]}"; do + key="$name"; suffix=""; args=(--kernel "$version") + if [ "$variant" = fallback ]; then key="$name-fallback"; suffix=-fallback; args+=(-S autodetect); fi + # entry-tool retains initramfs basenames when copying regular images. + stage_dir="$TX/stage-${#IMAGES[@]}"; mkdir -- "$stage_dir" + stage="$stage_dir/initramfs$suffix" + if [ "$IMAGE_KIND" = uki ]; then + stage="$stage_dir/${UKI_PREFIX}_${key}.efi" + if [ "$EMBED_CMDLINE" -eq 1 ]; then + printf '%s\n' "${EXPECTED_CMDLINES[$key]}" > "$TX/cmdline" + args+=(--cmdline "$TX/cmdline") + else args+=(--no-cmdline); fi + args+=(--uki "$stage" "${UKI_OPTIONS[@]}") + destination="EFI/Linux/${UKI_PREFIX}_${key}.efi" + else + args+=(--no-cmdline --generate "$stage") + destination="$MACHINE_ID/$name/initramfs$suffix" + fi + "$MKINITCPIO_BIN" "${args[@]}" + check_image "$stage" "$key" + IMAGES+=("$stage"); IMAGE_KEYS+=("$key"); IMAGE_NAMES+=("$name"); DESTINATIONS+=("$destination") + done +done +growth=0; largest=0; recovery_size=0 +for ((i=0; i<${#IMAGES[@]}; i++)); do + size="$(stat -c %s "${IMAGES[$i]}")"; previous=0 + [ ! -f "$BOOT_ROOT/${DESTINATIONS[$i]}" ] || previous="$(stat -c %s "$BOOT_ROOT/${DESTINATIONS[$i]}")" + [ "$size" -le "$previous" ] || growth=$((growth + size - previous)) + [ "$size" -le "$largest" ] || largest="$size" +done +if [ "$IMAGE_KIND" = initramfs ]; then + for ((k=0; k<${#KERNEL_NAMES[@]}; k++)); do + name="${KERNEL_NAMES[$k]}"; version="${KERNEL_VERSIONS[$k]}" + size="$(stat -c %s "$MODULES_ROOT/$version/vmlinuz")"; previous=0 + [ ! -f "$BOOT_ROOT/$MACHINE_ID/$name/vmlinuz" ] || previous="$(stat -c %s "$BOOT_ROOT/$MACHINE_ID/$name/vmlinuz")" + [ "$size" -le "$previous" ] || growth=$((growth + size - previous)) + [ "$size" -le "$largest" ] || largest="$size" + done +fi +while IFS= read -r line; do + if [[ "$line" =~ ^[[:space:]]*(path|kernel_path|module_path):[[:space:]]*boot\(\):/(.*)$ ]]; then + relative="${BASH_REMATCH[2]}"; relative="${relative%%#*}" + [[ "/$relative/" != *'/../'* && "/$relative/" != *'/./'* && "$relative" != /* ]] || die "Unsafe recovery resource" + [ -f "$TX/boot/$relative" ] || die "Recovery resource is missing: $relative" + recovery_size=$((recovery_size + $(stat -c %s "$TX/boot/$relative"))) + fi +done < "$RECOVERY_RECORD" +needed=$((growth + largest + recovery_size + 16777216)) +available="$(df -B1 --output=avail "$BOOT_ROOT" | tail -n1 | tr -d ' ')" +[ "$available" -ge "$needed" ] || die "Insufficient boot space for verified images and recovery" + +# Preserve one original entry, including all its original boot resources. +rm -rf -- "$BOOT_ROOT/drmcru-recovery" +mkdir -- "$BOOT_ROOT/drmcru-recovery"; touch "$BOOT_ROOT/drmcru-recovery/.drmcru-owned" +echo '/drmcru recovery (before last change)' > "$TX/recovery-menu" +resource_index=0 +while IFS= read -r line; do + [[ "$line" =~ ^[[:space:]]*/ ]] && continue + if [[ "$line" =~ ^([[:space:]]*(path|kernel_path|module_path):[[:space:]]*)(.*)$ ]]; then + prefix="${BASH_REMATCH[1]}"; uri="${BASH_REMATCH[3]}"; uri="${uri%%#*}" + [[ "$uri" == boot\(\):/* && "$uri/" != *'/../'* && "$uri/" != *'/./'* ]] || die "Recovery entry has an unsupported resource: $uri" + relative="${uri#boot():/}"; source="$TX/boot/$relative" + [ -f "$source" ] || die "Recovery resource is missing: $relative" + resource="drmcru-recovery/$resource_index-${source##*/}" + cp -a -- "$source" "$BOOT_ROOT/$resource" + hash="$(b2sum "$BOOT_ROOT/$resource")"; RESOURCE_HASHES[$resource]="${hash%% *}" + printf '%sboot():/%s#%s\n' "$prefix" "$resource" "${hash%% *}" >> "$TX/recovery-menu" + resource_index=$((resource_index+1)) + else printf '%s\n' "$line" >> "$TX/recovery-menu"; fi +done < "$RECOVERY_RECORD" +[ "$resource_index" -gt 0 ] || die "Recovery entry has no boot resources" + +for ((i=0; i<${#IMAGES[@]}; i++)); do + key="${IMAGE_KEYS[$i]}"; name="${IMAGE_NAMES[$i]}" + if [ "$IMAGE_KIND" = uki ]; then + "$ENTRY_TOOL_BIN" --add-uki "$key" "${IMAGES[$i]}" --no-mutex --no-hooks + else + version=""; for ((k=0; k<${#KERNEL_NAMES[@]}; k++)); do [ "${KERNEL_NAMES[$k]}" != "$name" ] || version="${KERNEL_VERSIONS[$k]}"; done + args=(--add-kernel "$name" "$MODULES_ROOT/$version/vmlinuz" "${IMAGES[$i]}") + [ "$name" = "$key" ] || args+=(-fallback) + "$ENTRY_TOOL_BIN" "${args[@]}" --no-mutex --no-hooks + cmp -s -- "$MODULES_ROOT/$version/vmlinuz" "$BOOT_ROOT/$MACHINE_ID/$name/vmlinuz" || die "Installed kernel differs for $key" + hash="$(b2sum "$BOOT_ROOT/$MACHINE_ID/$name/vmlinuz")" + RESOURCE_HASHES[$MACHINE_ID/$name/vmlinuz]="${hash%% *}" + fi + cmp -s -- "${IMAGES[$i]}" "$BOOT_ROOT/${DESTINATIONS[$i]}" || die "Installed image differs for $key" + hash="$(b2sum "$BOOT_ROOT/${DESTINATIONS[$i]}")" + RESOURCE_HASHES[${DESTINATIONS[$i]}]="${hash%% *}" + check_installed_entry "$key" "${DESTINATIONS[$i]}" +done +# Match the supported backend's format migration only after all new images +# are verified. The preserved recovery entry has independent resource copies. +for name in "${KERNEL_NAMES[@]}"; do + if [ "$IMAGE_KIND" = uki ]; then + if [ -d "$BOOT_ROOT/$MACHINE_ID/$name" ]; then + "$ENTRY_TOOL_BIN" --remove-kernel "$name" --no-mutex --no-hooks --quiet + fi + else + for key in "$name" "$name-fallback"; do + if [ -f "$BOOT_ROOT/EFI/Linux/${UKI_PREFIX}_${key}.efi" ]; then + "$ENTRY_TOOL_BIN" --remove-uki "$key" --no-mutex --no-hooks --quiet + fi + done + fi +done +# Replace only the previous managed recovery stanza. +awk ' + /^# BEGIN drmcru recovery$/ { inside=1; next } + /^# END drmcru recovery$/ { inside=0; next } + !inside { print } + END { if(inside) exit 1 } +' "$LIMINE" > "$TX/menu" +{ cat "$TX/menu"; echo '# BEGIN drmcru recovery'; cat "$TX/recovery-menu"; echo '# END drmcru recovery'; } > "$LIMINE" +refresh_hashes > "$TX/hashed-menu"; cat "$TX/hashed-menu" > "$LIMINE" +strict_hooks post +for ((i=0; i<${#IMAGES[@]}; i++)); do + cmp -s -- "${IMAGES[$i]}" "$BOOT_ROOT/${DESTINATIONS[$i]}" || die "Boot hook changed the verified image for ${IMAGE_KEYS[$i]}" + check_installed_entry "${IMAGE_KEYS[$i]}" "${DESTINATIONS[$i]}" +done +for relative in "${!RESOURCE_HASHES[@]}"; do + hash="$(b2sum "$BOOT_ROOT/$relative")" + [ "${hash%% *}" = "${RESOURCE_HASHES[$relative]}" ] || die "Boot hook changed a verified boot resource: $relative" +done +awk '/^# BEGIN drmcru recovery$/ { inside=1; next } /^# END drmcru recovery$/ { inside=0; next } inside { print }' "$LIMINE" > "$TX/recovery-after-hooks" +cmp -s -- "$TX/recovery-menu" "$TX/recovery-after-hooks" || die "Boot hook changed the recovery entry" +refresh_hashes > "$TX/hashed-menu" +cmp -s -- "$TX/hashed-menu" "$LIMINE" || die "A boot hook changed verified resource hashes" +grep -q '^# BEGIN drmcru recovery$' "$LIMINE" || die "A boot hook removed the recovery entry" +for key in "${KEYS[@]}"; do + current="$(cmdline "$key")" + [ "$(canonical "$current")" = "${EXPECTED_CMDLINES[$key]}" ] || die "A boot hook changed kernel arguments for $key" +done +if [ "$OPERATION" = add ]; then check_mapping "$CONNECTOR:edid/$EDID_NAME"; fi +sync -f "$BOOT_ROOT" +COMMITTED=1 +echo "[OK] All kernel images, firmware and command lines verified. Recovery entry retained." +echo "Reboot to activate the EDID changes." diff --git a/src/edid.rs b/src/edid.rs index 03a339b..d83c291 100644 --- a/src/edid.rs +++ b/src/edid.rs @@ -33,6 +33,8 @@ pub enum EdidError { NoVrrRange, #[error("VRR limits must be whole Hz between 1 and 510, with minimum <= maximum")] InvalidVrrRange, + #[error("{0}")] + InvalidInterlacedTiming(&'static str), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -468,7 +470,17 @@ pub fn patch_detailed_timing( pub fn delete_detailed_timing(raw: &[u8], location: DtdLocation) -> Result, EdidError> { let mut patched = raw.to_vec(); let (offset, block_start) = dtd_offset(raw, location)?; - patched[offset..offset + DTD_LEN].fill(0); + if let DtdLocation::Cta { slot, .. } = location { + let native = patched[block_start + 3] & 0x0f; + if (patched[offset] != 0 || patched[offset + 1] != 0) && slot < usize::from(native) { + patched[block_start + 3] = (patched[block_start + 3] & 0xf0) | (native - 1); + } + let end = block_start + BLOCK_CHECKSUM_INDEX; + patched.copy_within(offset + DTD_LEN..end, offset); + patched[end - DTD_LEN..end].fill(0); + } else { + patched[offset..offset + DTD_LEN].fill(0); + } repair_block_checksum(&mut patched[block_start..block_start + EDID_BLOCK_LEN]); Ok(patched) } @@ -606,14 +618,17 @@ pub fn cta_dtd_slots(raw: &[u8]) -> Result, EdidError> { } pub fn encode_detailed_timing(timing: &TimingDescriptor) -> Result<[u8; DTD_LEN], EdidError> { + let [v_active, v_blanking, v_front_porch, v_sync_width, _] = timing + .edid_vertical_fields() + .map_err(EdidError::InvalidInterlacedTiming)?; validate_12_bit("h_active", timing.h_active)?; validate_12_bit("h_blanking", timing.h_blanking)?; - validate_12_bit("v_active", timing.v_active)?; - validate_12_bit("v_blanking", timing.v_blanking)?; + validate_12_bit("v_active", v_active)?; + validate_12_bit("v_blanking", v_blanking)?; validate_10_bit("h_front_porch", timing.h_front_porch)?; validate_10_bit("h_sync_width", timing.h_sync_width)?; - validate_6_bit("v_front_porch", timing.v_front_porch)?; - validate_6_bit("v_sync_width", timing.v_sync_width)?; + validate_6_bit("v_front_porch", v_front_porch)?; + validate_6_bit("v_sync_width", v_sync_width)?; let pixel_clock_10khz = timing.pixel_clock_khz / 10; if pixel_clock_10khz == 0 { @@ -629,16 +644,16 @@ pub fn encode_detailed_timing(timing: &TimingDescriptor) -> Result<[u8; DTD_LEN] descriptor[2] = low_byte(timing.h_active); descriptor[3] = low_byte(timing.h_blanking); descriptor[4] = high_nibble(timing.h_active) << 4 | high_nibble(timing.h_blanking); - descriptor[5] = low_byte(timing.v_active); - descriptor[6] = low_byte(timing.v_blanking); - descriptor[7] = high_nibble(timing.v_active) << 4 | high_nibble(timing.v_blanking); + descriptor[5] = low_byte(v_active); + descriptor[6] = low_byte(v_blanking); + descriptor[7] = high_nibble(v_active) << 4 | high_nibble(v_blanking); descriptor[8] = low_byte(timing.h_front_porch); descriptor[9] = low_byte(timing.h_sync_width); - descriptor[10] = low_nibble(timing.v_front_porch) << 4 | low_nibble(timing.v_sync_width); + descriptor[10] = low_nibble(v_front_porch) << 4 | low_nibble(v_sync_width); descriptor[11] = ((timing.h_front_porch >> 8) as u8 & 0x03) << 6 | ((timing.h_sync_width >> 8) as u8 & 0x03) << 4 - | ((timing.v_front_porch >> 4) as u8 & 0x03) << 2 - | ((timing.v_sync_width >> 4) as u8 & 0x03); + | ((v_front_porch >> 4) as u8 & 0x03) << 2 + | ((v_sync_width >> 4) as u8 & 0x03); descriptor[17] = 0x18 | if timing.interlaced { 0x80 } else { 0 } | if timing.v_sync_positive { 0x04 } else { 0 } @@ -1337,6 +1352,24 @@ fn parse_detailed_timing(descriptor: &[u8]) -> Option { let h_back_porch = h_blanking.saturating_sub(h_front_porch + h_sync_width); let v_back_porch = v_blanking.saturating_sub(v_front_porch + v_sync_width); let flags = descriptor[17]; + let interlaced = flags & 0x80 != 0; + let (v_active, v_blanking, v_front_porch, v_sync_width, v_back_porch) = if interlaced { + ( + v_active * 2, + v_blanking * 2 + 1, + v_front_porch * 2, + v_sync_width * 2, + v_back_porch * 2 + 1, + ) + } else { + ( + v_active, + v_blanking, + v_front_porch, + v_sync_width, + v_back_porch, + ) + }; Some(TimingDescriptor { pixel_clock_khz: u32::from(pixel_clock_10khz) * 10, @@ -1352,10 +1385,55 @@ fn parse_detailed_timing(descriptor: &[u8]) -> Option { v_back_porch, h_sync_positive: flags & 0x02 != 0, v_sync_positive: flags & 0x04 != 0, - interlaced: flags & 0x80 != 0, + interlaced, }) } +pub fn cta_layout_issues(raw: &[u8]) -> Vec { + let mut issues = Vec::new(); + for (index, block) in raw.as_chunks::<128>().0.iter().enumerate().skip(1) { + if index > usize::from(raw[126]) || block[0] != CTA_TAG { + continue; + } + let native = usize::from(block[3] & 0x0f); + if block[2] == 0 { + if native != 0 { + issues.push(format!( + "CTA extension {index} has native DTDs but no DTD region" + )); + } + continue; + } + let Some(range) = cta_dtd_range(block) else { + issues.push(format!("CTA extension {index} has an invalid DTD offset")); + continue; + }; + let mut count = 0; + let mut end = range.start; + for descriptor in block[range.clone()].as_chunks::().0 { + if descriptor[0] == 0 && descriptor[1] == 0 { + break; + } + count += 1; + end += DTD_LEN; + } + if block[end..BLOCK_CHECKSUM_INDEX] + .iter() + .any(|byte| *byte != 0) + { + issues.push(format!( + "CTA extension {index} contains nonzero DTD padding" + )); + } + if native > count { + issues.push(format!( + "CTA extension {index} native DTD count exceeds its {count} timings" + )); + } + } + issues +} + #[cfg(test)] mod tests { use super::*; @@ -1856,6 +1934,108 @@ mod tests { assert_eq!(parsed, timing); } + #[test] + fn interlaced_dtd_uses_frame_geometry_and_round_trips_field_bytes() { + let bytes = [ + 0x01, 0x1d, 0x80, 0x18, 0x71, 0x1c, 0x16, 0x20, 0x58, 0x2c, 0x25, 0, 0, 0, 0, 0, 0, + 0x9e, + ]; + let timing = parse_detailed_timing(&bytes).unwrap(); + assert_eq!((timing.v_active, timing.v_blanking), (1080, 45)); + assert_eq!( + ( + timing.v_front_porch, + timing.v_sync_width, + timing.v_back_porch + ), + (4, 10, 31) + ); + assert_eq!(timing.hyprland_mode(), "1920x1080@60.00"); + assert_eq!(encode_detailed_timing(&timing).unwrap(), bytes); + assert!( + crate::validation::validate_timing(&timing) + .iter() + .all(|warning| warning.label() != "Error") + ); + let mut invalid = timing; + invalid.v_active = 1081; + assert!(matches!( + encode_detailed_timing(&invalid), + Err(EdidError::InvalidInterlacedTiming(_)) + )); + } + + #[test] + fn interlaced_sd_timings_preserve_the_half_line_and_field_rate() { + for (height, blanking, hblank, front, back, rate) in [ + (480, 45, 138, 8, 31, 59.94005994), + (576, 49, 144, 8, 35, 50.0), + ] { + let timing = TimingDescriptor { + pixel_clock_khz: 13_500, + h_active: 720, + h_blanking: hblank, + h_front_porch: 16, + h_sync_width: 62, + h_back_porch: hblank - 78, + v_active: height, + v_blanking: blanking, + v_front_porch: front, + v_sync_width: 6, + v_back_porch: back, + interlaced: true, + ..sample_timing() + }; + let encoded = encode_detailed_timing(&timing).unwrap(); + let parsed = parse_detailed_timing(&encoded).unwrap(); + assert_eq!(parsed, timing); + assert!((parsed.refresh_hz().unwrap() - rate).abs() < 0.00001); + assert_eq!(encoded[5], (height / 2) as u8); + } + } + + #[test] + fn cta_deletion_compacts_dtds_and_updates_only_the_native_count() { + let mut raw = crate::demo::monitors().unwrap().remove(0).edid.unwrap().raw; + raw[131] = 0xa2; + repair_block_checksum(&mut raw[128..256]); + let second = raw[155..173].to_vec(); + let patched = delete_detailed_timing( + &raw, + DtdLocation::Cta { + extension_index: 1, + slot: 0, + }, + ) + .unwrap(); + assert_eq!(&patched[..128], &raw[..128]); + assert_eq!(patched[131], 0xa1); + assert_eq!(&patched[137..155], second.as_slice()); + assert!(patched[155..255].iter().all(|byte| *byte == 0)); + assert!(cta_layout_issues(&patched).is_empty()); + assert_eq!( + parse_edid(patched.clone()).unwrap().cta_blocks[0] + .detailed_timings + .len(), + 1 + ); + assert!(block_checksum_valid(&patched[128..256])); + let mut gap = raw; + gap[137..155].fill(0); + repair_block_checksum(&mut gap[128..256]); + assert!( + cta_layout_issues(&gap) + .iter() + .any(|issue| issue.contains("nonzero DTD padding")) + ); + assert!( + !crate::workspace::EdidWorkspace::new(gap) + .unwrap() + .validate() + .is_empty() + ); + } + #[test] fn rejects_pixel_clocks_below_dtd_resolution() { let mut timing = sample_timing(); diff --git a/src/export.rs b/src/export.rs index 933b92d..624c819 100644 --- a/src/export.rs +++ b/src/export.rs @@ -65,6 +65,7 @@ pub fn export_instructions(edid_path: &Path, plan: &ExportPlan) -> String { String::new(), "3. Add this kernel parameter to your bootloader:".to_string(), format!(" {}", plan.drm_kernel_parameter()), + " Check connector names first: Linux prefix matching makes DP-1 also match DP-10 and DP-1-1. Do not install an ambiguous mapping.".to_string(), String::new(), "4. Add or update this Hyprland monitor rule:".to_string(), format!(" {}", plan.hyprland_monitor_rule()), diff --git a/src/install.rs b/src/install.rs index 4e50f52..95472a2 100644 --- a/src/install.rs +++ b/src/install.rs @@ -147,14 +147,12 @@ impl SystemSupportReport { } pub fn has_rebuild_backend(&self) -> bool { - self.limine_mkinitcpio_available || self.mkinitcpio_presets_present + self.limine_mkinitcpio_available } pub fn rebuild_backend_label(&self) -> &'static str { if self.limine_mkinitcpio_available { - "limine-mkinitcpio" - } else if self.mkinitcpio_presets_present { - "mkinitcpio -P" + "verified per-kernel mkinitcpio builds" } else { "missing" } @@ -173,7 +171,7 @@ impl SystemSupportReport { } if !self.has_rebuild_backend() { issues.push( - "no initramfs rebuild backend found (expected limine-mkinitcpio or /etc/mkinitcpio.d/*.preset)" + "verified rebuilds require the Limine/mkinitcpio integration; use Export for custom preset-only systems" .to_string(), ); } @@ -234,7 +232,7 @@ impl SystemSupportReport { self.summary_lines().join("\n") } else { std::iter::once( - "Automatic Apply currently supports Limine systems with mkinitcpio presets or limine-mkinitcpio.".to_string(), + "Automatic Apply requires Limine entry-tool and its mkinitcpio integration; custom preset-only systems should use Export.".to_string(), ) .chain( self.blocking_issues() @@ -309,8 +307,10 @@ impl UninstallPreview { "Patch: {} (remove persistent Limine entry-tool param)", self.limine_entry_tool_dropin ), + "Patch: /etc/default/limine (managed effective kernel command lines)".to_string(), format!("Parameter: {}", self.kernel_parameter), - "Run: limine-mkinitcpio when present, otherwise mkinitcpio -P".to_string(), + "Run: Build and verify kernel images before updating boot entries".to_string(), + "Recovery: /boot/drmcru-recovery (preserve the previous boot entry)".to_string(), ] } } @@ -348,8 +348,10 @@ impl InstallPreview { "Patch: {} (add persistent Limine entry-tool param)", self.limine_entry_tool_dropin ), + "Patch: /etc/default/limine (managed effective kernel command lines)".to_string(), format!("Parameter: {}", self.kernel_parameter), - "Run: limine-mkinitcpio when present, otherwise mkinitcpio -P".to_string(), + "Run: Build and verify kernel images before updating boot entries".to_string(), + "Recovery: /boot/drmcru-recovery (preserve the previous boot entry)".to_string(), ] } } @@ -381,14 +383,35 @@ pub enum InstallError { } pub fn inspect_system_support() -> SystemSupportReport { - inspect_system_support_with_paths( + let mut report = inspect_system_support_with_paths( Path::new("/etc/mkinitcpio.conf"), Path::new("/etc/mkinitcpio.d"), Path::new("/boot/limine.conf"), command_exists("pkexec"), command_exists("mkinitcpio"), command_exists("limine-mkinitcpio"), - ) + ); + for command in [ + "limine-entry-tool", + "lsinitcpio", + "objcopy", + "pacman", + "flock", + "b2sum", + ] { + if !command_exists(command) { + report.read_warnings.push(format!("{command} is required for verified automatic installation; manual Export remains available")); + } + } + if !Path::new("/usr/lib/limine/limine-common-functions").is_file() { + report + .read_warnings + .push("Limine entry-tool integration was not found".into()); + } + if !report.limine_mkinitcpio_available { + report.read_warnings.push("Automatic installation requires the Limine/mkinitcpio integration; use Export for custom preset-only setups".into()); + } + report } fn inspect_system_support_with_paths( @@ -637,7 +660,18 @@ fn limine_cmdline_reference_stats( Ok(contents) => { let mut cmdlines = 0; let mut matching = 0; + let mut recovery = false; for line in contents.lines() { + if line.trim() == "# BEGIN drmcru recovery" { + recovery = true; + } + if line.trim() == "# END drmcru recovery" { + recovery = false; + continue; + } + if recovery { + continue; + } if line.trim_start().starts_with("cmdline:") { cmdlines += 1; if text_contains_kernel_mapping(line, needle) { @@ -736,507 +770,99 @@ fn yes_no(value: bool) -> &'static str { if value { "ok" } else { "missing" } } -/// Build the idempotent bash install script. +/// Generate the shared, verified boot transaction for either operation. pub fn build_install_script(plan: &InstallPlan) -> String { - let files_awk = shell_quote(include_str!("mkinitcpio_files.awk")); - let preset_config_awk = shell_quote(include_str!("mkinitcpio_preset_config.awk")); - let mkinitcpio_helpers = include_str!("mkinitcpio_dropin.sh"); - let edid_source = shell_quote(&plan.edid_source.display().to_string()); - let firmware_target = shell_quote(&plan.firmware_target().display().to_string()); - let kernel_param = shell_quote(&plan.kernel_parameter); - let connector = shell_quote(&plan.connector); - - // The script is idempotent and validates the supported stack before mutating files. - format!( - r##"#!/bin/bash -set -Eeuo pipefail - -echo "=== drmcru: installing custom EDID ===" - -if [ "$(id -u)" -ne 0 ]; then - echo "[ERR] This installer must run as root." >&2 - exit 1 -fi - -EDID_SOURCE={edid_source} -FIRMWARE_TARGET={firmware_target} -KERNEL_PARAM={kernel_param} -CONNECTOR={connector} -MKINIT="/etc/mkinitcpio.conf" -MKINIT_DROPIN_DIR="$MKINIT.d" -MKINIT_DROPIN="$MKINIT_DROPIN_DIR/20-drmcru.conf" -FILES_AWK={files_awk} -PRESET_CONFIG_AWK={preset_config_awk} -LIMINE="/boot/limine.conf" -LIMINE_DROPIN_DIR="/etc/limine-entry-tool.d" -LIMINE_DROPIN="$LIMINE_DROPIN_DIR/drmcru-edid.conf" -BACKUP_SUFFIX=".drmcru.$(date +%Y%m%d-%H%M%S-%N)-$$.bak" -declare -a BACKUP_ORIGINALS=() -declare -a BACKUP_PATHS=() -FIRMWARE_WAS_PRESENT=0 -MKINIT_DROPIN_WAS_PRESENT=0 -MKINIT_DROPIN_DIR_WAS_PRESENT=0 -LIMINE_DROPIN_WAS_PRESENT=0 -LIMINE_DROPIN_DIR_WAS_PRESENT=0 - -backup_file() {{ - local file="$1" - local backup="${{file}}${{BACKUP_SUFFIX}}" - cp -a -- "$file" "$backup" - BACKUP_ORIGINALS+=("$file") - BACKUP_PATHS+=("$backup") - echo "[OK] Backup: $backup" -}} - -rollback() {{ - local status="$?" - trap - ERR - echo "[ERR] Apply failed; restoring files changed by this run." >&2 - local i - for ((i=${{#BACKUP_ORIGINALS[@]}} - 1; i >= 0; i--)); do - cp -a -- "${{BACKUP_PATHS[$i]}}" "${{BACKUP_ORIGINALS[$i]}}" || true - done - if [ "$FIRMWARE_WAS_PRESENT" -eq 0 ]; then - rm -f -- "$FIRMWARE_TARGET" || true - fi - if [ "$MKINIT_DROPIN_WAS_PRESENT" -eq 0 ]; then - rm -f -- "$MKINIT_DROPIN" || true - fi - if [ "$MKINIT_DROPIN_DIR_WAS_PRESENT" -eq 0 ]; then - rmdir -- "$MKINIT_DROPIN_DIR" 2>/dev/null || true - fi - if [ "$LIMINE_DROPIN_WAS_PRESENT" -eq 0 ]; then - rm -f -- "$LIMINE_DROPIN" || true - fi - if [ "$LIMINE_DROPIN_DIR_WAS_PRESENT" -eq 0 ]; then - rmdir -- "$LIMINE_DROPIN_DIR" 2>/dev/null || true - fi - exit "$status" -}} - -{mkinitcpio_helpers} - -if [ ! -f "$EDID_SOURCE" ]; then - echo "[ERR] EDID source does not exist: $EDID_SOURCE" >&2 - exit 1 -fi - -if [ ! -f "$MKINIT" ]; then - echo "[ERR] /etc/mkinitcpio.conf not found — automatic Apply supports mkinitcpio only" >&2 - exit 1 -fi - -if [ ! -f "$LIMINE" ]; then - echo "[ERR] /boot/limine.conf not found — automatic Apply supports Limine only" >&2 - exit 1 -fi - -if ! grep -qE '^[[:space:]]*cmdline:' "$LIMINE"; then - echo "[ERR] /boot/limine.conf has no cmdline entries" >&2 - exit 1 -fi - -if ! command -v mkinitcpio >/dev/null 2>&1; then - echo "[ERR] mkinitcpio was not found" >&2 - exit 1 -fi - -if ! command -v limine-mkinitcpio >/dev/null 2>&1 && ! compgen -G "/etc/mkinitcpio.d/*.preset" >/dev/null; then - echo "[ERR] No initramfs rebuild backend found (expected limine-mkinitcpio or mkinitcpio presets)" >&2 - exit 1 -fi - -check_mkinitcpio_dropins - -if [ -e "$FIRMWARE_TARGET" ]; then - FIRMWARE_WAS_PRESENT=1 - backup_file "$FIRMWARE_TARGET" -fi -if [ -e "$MKINIT_DROPIN" ]; then - MKINIT_DROPIN_WAS_PRESENT=1 -fi -if [ -d "$MKINIT_DROPIN_DIR" ]; then - MKINIT_DROPIN_DIR_WAS_PRESENT=1 -fi -if [ -e "$LIMINE_DROPIN" ]; then - LIMINE_DROPIN_WAS_PRESENT=1 -fi -if [ -d "$LIMINE_DROPIN_DIR" ]; then - LIMINE_DROPIN_DIR_WAS_PRESENT=1 -fi -trap rollback ERR - -# 1. Copy EDID to firmware directory -install -D -m 0644 -- "$EDID_SOURCE" "$FIRMWARE_TARGET" -echo "[OK] Installed EDID to $FIRMWARE_TARGET" - -# 2. Append our EDID through a dedicated drop-in and migrate legacy installs. -update_mkinitcpio_dropin add -remove_legacy_mkinitcpio_entry -echo "[OK] Ensured EDID is in mkinitcpio drop-in FILES" - -# 3. Patch Limine entry-tool drop-in when available. limine-mkinitcpio uses this -# to embed the same kernel parameter into regenerated Limine entries/UKIs. -if command -v limine-mkinitcpio >/dev/null 2>&1; then - mkdir -p "$LIMINE_DROPIN_DIR" - if [ -f "$LIMINE_DROPIN" ]; then - backup_file "$LIMINE_DROPIN" - TMP="$(mktemp /tmp/drmcru-limine-entry.XXXXXX)" - awk -v connector="$CONNECTOR" -v param="$KERNEL_PARAM" ' - function add_mapping(mapping) {{ - if (mapping == "" || index(mapping, connector ":") == 1) - return - if (!seen[mapping]++) - mappings[++mapping_count] = mapping - }} - /^[[:space:]]*KERNEL_CMDLINE\[default\]\+=/ && index($0, "drm.edid_firmware=") > 0 {{ - line = $0 - while (match(line, /drm.edid_firmware=[^\"\047[:space:]]*/)) {{ - value = substr(line, RSTART + length("drm.edid_firmware="), RLENGTH - length("drm.edid_firmware=")) - line = substr(line, 1, RSTART - 1) substr(line, RSTART + RLENGTH) - count = split(value, values, ",") - for (i = 1; i <= count; i++) - add_mapping(values[i]) - }} - if (line !~ /^[[:space:]]*KERNEL_CMDLINE\[default\]\+=[\"\047][[:space:]]*[\"\047][[:space:]]*$/) - print line - next - }} - {{ print }} - END {{ - desired = substr(param, length("drm.edid_firmware=") + 1) - combined = "" - for (i = 1; i <= mapping_count; i++) - combined = combined (combined == "" ? "" : ",") mappings[i] - combined = combined (combined == "" ? "" : ",") desired - print "KERNEL_CMDLINE[default]+=\" drm.edid_firmware=" combined "\"" - }} - ' "$LIMINE_DROPIN" > "$TMP" - cat "$TMP" > "$LIMINE_DROPIN" - rm -f "$TMP" - else - {{ - echo "# Managed by drmcru. Edit through drmcru when possible." - printf 'KERNEL_CMDLINE[default]+=" %s"\n' "$KERNEL_PARAM" - }} > "$LIMINE_DROPIN" - fi - echo "[OK] Consolidated persistent Limine entry-tool EDID mappings" -else - echo "[OK] limine-mkinitcpio not present; Limine entry-tool drop-in skipped" -fi - -# 4. Patch /boot/limine.conf. The kernel accepts one drm.edid_firmware value; -# connector mappings inside that value are comma-separated. Consolidate any -# older repeated parameters while replacing this connector's mapping. -if [ -f "$LIMINE" ]; then - if grep -qE '^[[:space:]]*cmdline:' "$LIMINE"; then - backup_file "$LIMINE" - TMP="$(mktemp /tmp/drmcru-limine.XXXXXX)" - awk -v connector="$CONNECTOR" -v param="$KERNEL_PARAM" ' - function add_mapping(mapping) {{ - if (mapping == "" || index(mapping, connector ":") == 1) - return - if (!seen[mapping]++) - mappings[++mapping_count] = mapping - }} - /^[[:space:]]*cmdline:/ {{ - delete seen - delete mappings - mapping_count = 0 - prefix = substr($0, 1, index($0, ":")) - other = "" - token_count = split(substr($0, index($0, ":") + 1), tokens, /[[:space:]]+/) - for (i = 1; i <= token_count; i++) {{ - if (tokens[i] == "") - continue - if (index(tokens[i], "drm.edid_firmware=") == 1) {{ - value = substr(tokens[i], length("drm.edid_firmware=") + 1) - count = split(value, values, ",") - for (j = 1; j <= count; j++) - add_mapping(values[j]) - }} else {{ - other = other (other == "" ? "" : " ") tokens[i] - }} - }} - desired = substr(param, length("drm.edid_firmware=") + 1) - combined = "" - for (i = 1; i <= mapping_count; i++) - combined = combined (combined == "" ? "" : ",") mappings[i] - combined = combined (combined == "" ? "" : ",") desired - print prefix (other == "" ? "" : " " other) " drm.edid_firmware=" combined - next - }} - {{ print }} - ' "$LIMINE" > "$TMP" - cat "$TMP" > "$LIMINE" - rm -f "$TMP" - echo "[OK] Consolidated EDID mappings in all Limine cmdline entries" - else - echo "[ERR] /boot/limine.conf has no cmdline entries" >&2 - exit 1 - fi -else - echo "[ERR] /boot/limine.conf not found — automatic Apply supports Limine only" >&2 - exit 1 -fi - -# 5. Rebuild initramfs/UKIs. -if command -v limine-mkinitcpio >/dev/null 2>&1; then - echo "[..] Rebuilding Limine initramfs/UKI entries (limine-mkinitcpio)..." - limine-mkinitcpio - echo "[OK] Limine initramfs/UKI entries rebuilt" -elif compgen -G "/etc/mkinitcpio.d/*.preset" >/dev/null; then - echo "[..] Rebuilding initramfs (mkinitcpio -P)..." - mkinitcpio -P - echo "[OK] Initramfs rebuilt" -else - echo "[ERR] No initramfs rebuild backend found" >&2 - exit 1 -fi - -trap - ERR - -echo "" -echo "=== Done! Reboot to activate the custom resolution. ===" -"## + build_override_script( + &plan.connector, + &plan.edid_file_name, + Some(&plan.edid_source), ) } -fn shell_quote(value: &str) -> String { - format!("'{}'", value.replace('\'', "'\\''")) +pub fn build_uninstall_script(plan: &UninstallPlan) -> String { + build_override_script(&plan.connector, &plan.edid_file_name, None) } -/// Build the idempotent bash uninstall script. -pub fn build_uninstall_script(plan: &UninstallPlan) -> String { +fn build_override_script(connector: &str, name: &str, source: Option<&Path>) -> String { + let connector = shell_quote(connector); + let name = shell_quote(name); + let operation = if source.is_some() { "add" } else { "remove" }; + let source = shell_quote( + &source + .map(|path| path.display().to_string()) + .unwrap_or_default(), + ); let files_awk = shell_quote(include_str!("mkinitcpio_files.awk")); - let preset_config_awk = shell_quote(include_str!("mkinitcpio_preset_config.awk")); - let mkinitcpio_helpers = include_str!("mkinitcpio_dropin.sh"); - let firmware_target = shell_quote(&plan.firmware_target().display().to_string()); - let kernel_param = shell_quote(&plan.kernel_parameter); - let connector = shell_quote(&plan.connector); - + let preset_awk = shell_quote(include_str!("mkinitcpio_preset_config.awk")); + let cmdline_awk = shell_quote(include_str!("kernel_cmdline.awk")); + let entry_awk = shell_quote(include_str!("limine_entry.awk")); + let mkinit_helpers = include_str!("mkinitcpio_dropin.sh"); + let transaction = include_str!("boot_transaction.sh"); format!( r##"#!/bin/bash -set -Eeuo pipefail - -echo "=== drmcru: uninstalling custom EDID ===" - -if [ "$(id -u)" -ne 0 ]; then - echo "[ERR] This uninstaller must run as root." >&2 - exit 1 -fi - -FIRMWARE_TARGET={firmware_target} -KERNEL_PARAM={kernel_param} +OPERATION={operation} CONNECTOR={connector} +EDID_NAME={name} +EDID_SOURCE={source} +MKINITCPIO_BIN="/usr/bin/mkinitcpio" +LSINITCPIO_BIN="/usr/bin/lsinitcpio" +ENTRY_TOOL_BIN="/usr/bin/limine-entry-tool" +OBJCOPY_BIN="/usr/bin/objcopy" +FIRMWARE_ROOT="/lib/firmware" +FIRMWARE_TARGET="$FIRMWARE_ROOT/edid/$EDID_NAME" +BOOT_ROOT="/boot" +LIMINE="$BOOT_ROOT/limine.conf" MKINIT="/etc/mkinitcpio.conf" MKINIT_DROPIN_DIR="$MKINIT.d" MKINIT_DROPIN="$MKINIT_DROPIN_DIR/20-drmcru.conf" -FILES_AWK={files_awk} -PRESET_CONFIG_AWK={preset_config_awk} -LIMINE="/boot/limine.conf" LIMINE_DROPIN_DIR="/etc/limine-entry-tool.d" LIMINE_DROPIN="$LIMINE_DROPIN_DIR/drmcru-edid.conf" -BACKUP_SUFFIX=".drmcru.$(date +%Y%m%d-%H%M%S-%N)-$$.bak" -declare -a BACKUP_ORIGINALS=() -declare -a BACKUP_PATHS=() -FIRMWARE_WAS_PRESENT=0 - -backup_file() {{ - local file="$1" - local backup="${{file}}${{BACKUP_SUFFIX}}" - cp -a -- "$file" "$backup" - BACKUP_ORIGINALS+=("$file") - BACKUP_PATHS+=("$backup") - echo "[OK] Backup: $backup" -}} - -rollback() {{ - local status="$?" - trap - ERR - echo "[ERR] Uninstall failed; restoring files changed by this run." >&2 - local i - for ((i=${{#BACKUP_ORIGINALS[@]}} - 1; i >= 0; i--)); do - cp -a -- "${{BACKUP_PATHS[$i]}}" "${{BACKUP_ORIGINALS[$i]}}" || true - done - exit "$status" -}} - -{mkinitcpio_helpers} - -if [ ! -f "$MKINIT" ]; then - echo "[ERR] /etc/mkinitcpio.conf not found — automatic uninstall supports mkinitcpio only" >&2 - exit 1 -fi - -if [ ! -f "$LIMINE" ]; then - echo "[ERR] /boot/limine.conf not found — automatic uninstall supports Limine only" >&2 - exit 1 -fi - -if ! grep -qE '^[[:space:]]*cmdline:' "$LIMINE"; then - echo "[ERR] /boot/limine.conf has no cmdline entries" >&2 - exit 1 -fi - -if ! command -v mkinitcpio >/dev/null 2>&1; then - echo "[ERR] mkinitcpio was not found" >&2 - exit 1 -fi - -if ! command -v limine-mkinitcpio >/dev/null 2>&1 && ! compgen -G "/etc/mkinitcpio.d/*.preset" >/dev/null; then - echo "[ERR] No initramfs rebuild backend found (expected limine-mkinitcpio or mkinitcpio presets)" >&2 - exit 1 -fi - -check_mkinitcpio_dropins - -if [ -e "$FIRMWARE_TARGET" ]; then - FIRMWARE_WAS_PRESENT=1 - backup_file "$FIRMWARE_TARGET" -fi -trap rollback ERR - -# 1. Remove EDID from firmware directory -if [ -e "$FIRMWARE_TARGET" ]; then - rm -f -- "$FIRMWARE_TARGET" - echo "[OK] Removed $FIRMWARE_TARGET" -else - echo "[OK] Firmware file not present (skipped)" -fi - -# 2. Remove this connector from our drop-in and any legacy FILES entry. -update_mkinitcpio_dropin remove -remove_legacy_mkinitcpio_entry -echo "[OK] Removed EDID from mkinitcpio FILES" - -# 3. Patch Limine entry-tool drop-in when present -if [ -f "$LIMINE_DROPIN" ]; then - if grep -qF -- "drm.edid_firmware=" "$LIMINE_DROPIN" 2>/dev/null; then - backup_file "$LIMINE_DROPIN" - TMP="$(mktemp /tmp/drmcru-limine-entry.XXXXXX)" - awk -v connector="$CONNECTOR" ' - function add_mapping(mapping) {{ - if (mapping == "" || index(mapping, connector ":") == 1) - return - if (!seen[mapping]++) - mappings[++mapping_count] = mapping - }} - /^[[:space:]]*KERNEL_CMDLINE\[default\]\+=/ && index($0, "drm.edid_firmware=") > 0 {{ - line = $0 - while (match(line, /drm.edid_firmware=[^\"\047[:space:]]*/)) {{ - value = substr(line, RSTART + length("drm.edid_firmware="), RLENGTH - length("drm.edid_firmware=")) - line = substr(line, 1, RSTART - 1) substr(line, RSTART + RLENGTH) - count = split(value, values, ",") - for (i = 1; i <= count; i++) - add_mapping(values[i]) - }} - if (line !~ /^[[:space:]]*KERNEL_CMDLINE\[default\]\+=[\"\047][[:space:]]*[\"\047][[:space:]]*$/) - print line - next - }} - {{ print }} - END {{ - if (mapping_count > 0) {{ - combined = "" - for (i = 1; i <= mapping_count; i++) - combined = combined (combined == "" ? "" : ",") mappings[i] - print "KERNEL_CMDLINE[default]+=\" drm.edid_firmware=" combined "\"" - }} - }} - ' "$LIMINE_DROPIN" > "$TMP" - cat "$TMP" > "$LIMINE_DROPIN" - rm -f "$TMP" - if ! grep -qE '^[[:space:]]*KERNEL_CMDLINE\[default\]\+=' "$LIMINE_DROPIN"; then - rm -f -- "$LIMINE_DROPIN" - echo "[OK] Removed empty Limine entry-tool drop-in" - else - echo "[OK] Removed persistent Limine entry-tool kernel parameter" - fi - else - echo "[OK] Limine entry-tool drop-in has no matching kernel parameter (skipped)" - fi -else - echo "[OK] Limine entry-tool drop-in not present (skipped)" -fi - -# 4. Patch /boot/limine.conf — remove this connector mapping and consolidate -# any remaining mappings into a single drm.edid_firmware parameter. -if [ -f "$LIMINE" ]; then - if grep -qF -- "drm.edid_firmware=" "$LIMINE" 2>/dev/null; then - backup_file "$LIMINE" - TMP="$(mktemp /tmp/drmcru-limine.XXXXXX)" - awk -v connector="$CONNECTOR" ' - function add_mapping(mapping) {{ - if (mapping == "" || index(mapping, connector ":") == 1) - return - if (!seen[mapping]++) - mappings[++mapping_count] = mapping - }} - /^[[:space:]]*cmdline:/ {{ - delete seen - delete mappings - mapping_count = 0 - prefix = substr($0, 1, index($0, ":")) - other = "" - token_count = split(substr($0, index($0, ":") + 1), tokens, /[[:space:]]+/) - for (i = 1; i <= token_count; i++) {{ - if (tokens[i] == "") - continue - if (index(tokens[i], "drm.edid_firmware=") == 1) {{ - value = substr(tokens[i], length("drm.edid_firmware=") + 1) - count = split(value, values, ",") - for (j = 1; j <= count; j++) - add_mapping(values[j]) - }} else {{ - other = other (other == "" ? "" : " ") tokens[i] - }} - }} - combined = "" - for (i = 1; i <= mapping_count; i++) - combined = combined (combined == "" ? "" : ",") mappings[i] - print prefix (other == "" ? "" : " " other) \ - (combined == "" ? "" : " drm.edid_firmware=" combined) - next - }} - {{ print }} - ' "$LIMINE" > "$TMP" - cat "$TMP" > "$LIMINE" - rm -f "$TMP" - echo "[OK] Removed connector mapping from Limine cmdline entries" - else - echo "[OK] Kernel parameter not present in Limine config (skipped)" - fi -else - echo "[ERR] /boot/limine.conf not found — automatic uninstall supports Limine only" >&2 - exit 1 -fi - -# 5. Rebuild initramfs/UKIs. -if command -v limine-mkinitcpio >/dev/null 2>&1; then - echo "[..] Rebuilding Limine initramfs/UKI entries (limine-mkinitcpio)..." - limine-mkinitcpio - echo "[OK] Limine initramfs/UKI entries rebuilt" -elif compgen -G "/etc/mkinitcpio.d/*.preset" >/dev/null; then - echo "[..] Rebuilding initramfs (mkinitcpio -P)..." - mkinitcpio -P - echo "[OK] Initramfs rebuilt" -else - echo "[ERR] No initramfs rebuild backend found" >&2 - exit 1 -fi - -trap - ERR - -echo "" -echo "=== Done! Reboot to return to the monitor's normal EDID. ===" +LIMINE_CONFIG="/etc/limine-entry-tool.conf" +LIMINE_DEFAULT_CONFIG="/etc/default/limine" +LIMINE_VENDOR_DIR="/usr/share/limine-entry-tool.d" +LIMINE_FUNCTIONS="/usr/lib/limine/limine-common-functions" +BOOT_HOOKS="/etc/boot/hooks" +BOOT_LOCK="/run/lock/boot-partition.lock" +PACKAGE_LOCK="/var/lib/pacman/db.lck" +TRANSACTION_ROOT="/var/tmp" +MODULES_ROOT="/usr/lib/modules" +MACHINE_ID_FILE="/etc/machine-id" +DRM_ROOT="/sys/class/drm" +FILES_AWK={files_awk} +PRESET_CONFIG_AWK={preset_awk} +CMDLINE_AWK={cmdline_awk} +ENTRY_AWK={entry_awk} +{mkinit_helpers} +{transaction} "## ) } +fn shell_quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\\''")) +} + /// Run the install. Returns a report on success, or an error. pub fn install(plan: &InstallPlan) -> Result { validate_firmware_file_name(&plan.edid_file_name)?; + let names = fs::read_dir("/sys/class/drm") + .map_err(|error| { + InstallError::UnsupportedSystem(format!("Could not inspect DRM connectors: {error}")) + })? + .map(|entry| entry.map(|entry| entry.path())) + .collect::>>() + .map_err(|error| InstallError::UnsupportedSystem(error.to_string()))?; + let connectors = names + .iter() + .filter(|path| path.join("status").exists()) + .filter_map(|path| { + path.file_name()? + .to_str()? + .split_once('-') + .map(|(_, name)| name) + }); + validate_connector_mapping(&plan.connector, connectors) + .map_err(InstallError::UnsupportedSystem)?; // Validate source exists if !plan.edid_source.exists() { @@ -1308,13 +934,40 @@ fn run_privileged_script(script: &str) -> Result { } fn validate_firmware_file_name(edid_file_name: &str) -> Result<(), InstallError> { - if edid_file_name.is_empty() || edid_file_name.contains('/') || edid_file_name.contains('\\') { + if edid_file_name.is_empty() + || matches!(edid_file_name, "." | "..") + || !edid_file_name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte)) + { return Err(InstallError::UnsafeFirmwareName(edid_file_name.to_string())); } Ok(()) } +pub(crate) fn validate_connector_mapping<'a>( + connector: &str, + names: impl IntoIterator, +) -> Result<(), String> { + let mut exact = 0; + for name in names { + if name == connector { + exact += 1; + } else if name.starts_with(connector) { + return Err(format!( + "Linux also applies connector mapping {connector} to {name}; use an unambiguous connector" + )); + } + } + if exact != 1 { + return Err(format!( + "Connector {connector} is absent or occurs on multiple DRM devices" + )); + } + Ok(()) +} + fn write_temp_install_script(script: &str) -> Result { let now = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -1352,1128 +1005,5 @@ fn write_temp_install_script(script: &str) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - fn sample_plan() -> InstallPlan { - InstallPlan { - connector: "DP-1".to_string(), - edid_source: PathBuf::from("/tmp/drmcru_custom_DP-1.bin"), - edid_file_name: "drmcru_custom_DP-1.bin".to_string(), - kernel_parameter: "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin".to_string(), - } - } - - fn sample_uninstall_plan() -> UninstallPlan { - UninstallPlan { - connector: "DP-1".to_string(), - edid_file_name: "drmcru_custom_DP-1.bin".to_string(), - kernel_parameter: "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin".to_string(), - } - } - - fn unique_test_dir() -> PathBuf { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_nanos(); - std::env::temp_dir().join(format!("drmcru-install-test-{}-{now}", std::process::id())) - } - - struct ScriptFixture { - dir: PathBuf, - } - - impl ScriptFixture { - fn new() -> Self { - let dir = unique_test_dir(); - fs::create_dir_all(dir.join("bin")).unwrap(); - fs::create_dir_all(dir.join("firmware")).unwrap(); - fs::create_dir_all(dir.join("entry-tool")).unwrap(); - fs::write(dir.join("source.bin"), b"new-edid").unwrap(); - fs::write(dir.join("mkinitcpio.conf"), "FILES=()\n").unwrap(); - fs::write(dir.join("limine.conf"), "cmdline: quiet\n").unwrap(); - let fixture = Self { dir }; - fixture.command("id", "printf '0\\n'"); - fixture.command("mkinitcpio", "exit 0"); - fixture.command("limine-mkinitcpio", "exit 0"); - fixture - } - - fn command(&self, name: &str, body: &str) { - let path = self.dir.join("bin").join(name); - fs::write(&path, format!("#!/bin/bash\n{body}\n")).unwrap(); - fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); - } - - fn run(&self, uninstall: bool) -> std::process::Output { - self.run_for_connector(uninstall, "DP-1") - } - - fn run_for_connector(&self, uninstall: bool, connector: &str) -> std::process::Output { - let mut plan = sample_plan(); - plan.connector = connector.to_string(); - plan.edid_source = self.dir.join("source.bin"); - plan.edid_file_name = format!("drmcru_custom_{connector}.bin"); - plan.kernel_parameter = - format!("drm.edid_firmware={connector}:edid/{}", plan.edid_file_name); - let script = if uninstall { - build_uninstall_script(&UninstallPlan { - connector: plan.connector, - edid_file_name: plan.edid_file_name, - kernel_parameter: plan.kernel_parameter, - }) - } else { - build_install_script(&plan) - }; - let script = script - .replace( - "/lib/firmware/edid", - &self.dir.join("firmware").display().to_string(), - ) - .replace( - "/etc/mkinitcpio.conf", - &self.dir.join("mkinitcpio.conf").display().to_string(), - ) - .replace( - "/boot/limine.conf", - &self.dir.join("limine.conf").display().to_string(), - ) - .replace( - "/etc/limine-entry-tool.d", - &self.dir.join("entry-tool").display().to_string(), - ) - .replace( - "/etc/mkinitcpio.d", - &self.dir.join("presets").display().to_string(), - ); - // Simulate the preset backend without discovering the host's real - // limine-mkinitcpio through the inherited utility PATH. - let script = if self.dir.join("without-limine").exists() { - format!( - "command() {{ if [ \"$1\" = -v ] && [ \"$2\" = limine-mkinitcpio ]; then return 1; fi; builtin command \"$@\"; }}\n{script}" - ) - } else { - script - }; - Command::new("bash") - .args(["-c", &script]) - .env( - "PATH", - format!( - "{}:{}", - self.dir.join("bin").display(), - std::env::var("PATH").unwrap() - ), - ) - .output() - .unwrap() - } - - fn firmware(&self) -> PathBuf { - self.dir.join("firmware/drmcru_custom_DP-1.bin") - } - - fn mkinitcpio_dropin(&self) -> PathBuf { - self.dir.join("mkinitcpio.conf.d/20-drmcru.conf") - } - } - - impl Drop for ScriptFixture { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.dir); - } - } - - #[test] - fn install_updates_mapping_and_preserves_other_connectors_on_repeated_runs() { - let fixture = ScriptFixture::new(); - let other = "HDMI-A-1:edid/other.bin"; - fs::write( - fixture.dir.join("limine.conf"), - format!("cmdline: quiet drm.edid_firmware=DP-1:edid/old.bin,{other}\ncmdline: debug\n"), - ) - .unwrap(); - fs::write( - fixture.dir.join("entry-tool/drmcru-edid.conf"), - format!("KERNEL_CMDLINE[default]+=\" drm.edid_firmware=DP-1:edid/old.bin,{other}\"\n"), - ) - .unwrap(); - for _ in 0..2 { - let output = fixture.run(false); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - let limine = fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(); - for line in limine.lines() { - assert!( - text_contains_kernel_mapping(line, &sample_plan().kernel_parameter), - "{line}" - ); - assert_eq!(line.matches("drm.edid_firmware=").count(), 1); - assert!(!line.contains("old.bin")); - } - assert!(limine.lines().next().unwrap().contains(other)); - let dropin = - fs::read_to_string(fixture.dir.join("entry-tool/drmcru-edid.conf")).unwrap(); - assert!( - text_contains_kernel_mapping(&dropin, &sample_plan().kernel_parameter), - "{dropin}" - ); - assert!(dropin.contains(other)); - } - } - - #[test] - fn install_rolls_back_when_a_backup_helper_fails() { - let fixture = ScriptFixture::new(); - fs::write(fixture.firmware(), b"old-edid").unwrap(); - let mkinit = fixture.mkinitcpio_dropin(); - fs::create_dir_all(mkinit.parent().unwrap()).unwrap(); - fs::write(&mkinit, "FILES+=(\"/keep.bin\")\n").unwrap(); - fixture.command( - "cp", - &format!( - "if [ \"$3\" = {} ]; then exit 42; fi\nexec /usr/bin/cp \"$@\"", - shell_quote(&mkinit.display().to_string()) - ), - ); - let output = fixture.run(false); - assert!(!output.status.success()); - assert_eq!(fs::read(fixture.firmware()).unwrap(), b"old-edid"); - assert_eq!( - fs::read_to_string(mkinit).unwrap(), - "FILES+=(\"/keep.bin\")\n" - ); - } - - #[test] - fn rebuild_failure_restores_install_and_uninstall_files() { - for uninstall in [false, true] { - let fixture = ScriptFixture::new(); - fs::write(fixture.firmware(), b"old-edid").unwrap(); - let mkinit = format!("FILES=(\"{}\")\n", fixture.firmware().display()); - let limine = format!("cmdline: quiet {}\n", sample_plan().kernel_parameter); - let dropin = format!( - "KERNEL_CMDLINE[default]+=\" {}\"\n", - sample_plan().kernel_parameter - ); - fs::write(fixture.dir.join("mkinitcpio.conf"), &mkinit).unwrap(); - fs::create_dir_all(fixture.mkinitcpio_dropin().parent().unwrap()).unwrap(); - let mkinit_dropin = format!( - "FILES+=(\"{}\"{})\n", - fixture.firmware().display(), - if uninstall { "" } else { " \"/keep.bin\"" } - ); - fs::write(fixture.mkinitcpio_dropin(), &mkinit_dropin).unwrap(); - fs::write(fixture.dir.join("limine.conf"), &limine).unwrap(); - fs::write(fixture.dir.join("entry-tool/drmcru-edid.conf"), &dropin).unwrap(); - fixture.command("limine-mkinitcpio", "exit 42"); - assert!(!fixture.run(uninstall).status.success()); - assert_eq!(fs::read(fixture.firmware()).unwrap(), b"old-edid"); - assert_eq!( - fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(), - mkinit - ); - assert_eq!( - fs::read_to_string(fixture.mkinitcpio_dropin()).unwrap(), - mkinit_dropin - ); - assert_eq!( - fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(), - limine - ); - assert_eq!( - fs::read_to_string(fixture.dir.join("entry-tool/drmcru-edid.conf")).unwrap(), - dropin - ); - } - } - - #[test] - fn install_and_uninstall_preserve_compact_cmdlines_and_dropin_options() { - let fixture = ScriptFixture::new(); - let other = "HDMI-A-1:edid/other.bin"; - fs::write( - fixture.dir.join("limine.conf"), - format!("cmdline:quiet drm.edid_firmware=DP-1:edid/old.bin,{other} root=/dev/test\n"), - ) - .unwrap(); - fs::write(fixture.dir.join("entry-tool/drmcru-edid.conf"), format!("KERNEL_CMDLINE[default]+=\" quiet drm.edid_firmware=DP-1:edid/old.bin,{other} loglevel=3\"\n")).unwrap(); - for uninstall in [false, true] { - let output = fixture.run(uninstall); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - let limine = fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(); - assert!(limine.contains("quiet"), "{limine}"); - assert!(limine.contains("root=/dev/test")); - assert!(limine.contains(other)); - let dropin = - fs::read_to_string(fixture.dir.join("entry-tool/drmcru-edid.conf")).unwrap(); - assert!(dropin.contains("quiet"), "{dropin}"); - assert!(dropin.contains("loglevel=3"), "{dropin}"); - assert!(dropin.contains(other)); - } - } - - #[test] - fn install_does_not_mistake_comments_for_files_entries() { - let fixture = ScriptFixture::new(); - let path = fixture.firmware().display().to_string(); - let original = format!("# FILES=({path})\nFILES=(\n /keep.bin # ) is a comment\n)\n"); - fs::write(fixture.dir.join("mkinitcpio.conf"), &original).unwrap(); - for _ in 0..2 { - let output = fixture.run(false); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - } - let config = fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(); - assert_eq!(config, original); - let dropin = fs::read_to_string(fixture.mkinitcpio_dropin()).unwrap(); - assert_eq!(dropin.matches(&format!("\"{path}\"")).count(), 1); - } - - #[test] - fn new_install_preserves_dynamic_files_and_appends_through_the_dropin() { - let fixture = ScriptFixture::new(); - let original = "FILES=($(printf /keep.bin))\n"; - fs::write(fixture.dir.join("mkinitcpio.conf"), original).unwrap(); - let output = fixture.run(false); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - assert_eq!( - fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(), - original - ); - let output = Command::new("bash") - .args([ - "-c", - ". \"$1\"; . \"$2\"; printf '%s\\n' \"${FILES[@]}\"", - "bash", - ]) - .arg(fixture.dir.join("mkinitcpio.conf")) - .arg(fixture.mkinitcpio_dropin()) - .output() - .unwrap(); - assert!(output.status.success()); - assert_eq!( - String::from_utf8(output.stdout).unwrap(), - format!("/keep.bin\n{}\n", fixture.firmware().display()) - ); - } - - #[test] - fn uninstall_removes_only_exact_firmware_entries_from_multiline_files() { - let fixture = ScriptFixture::new(); - let path = fixture.firmware().display().to_string(); - fs::write(fixture.firmware(), b"old-edid").unwrap(); - fs::write(fixture.dir.join("mkinitcpio.conf"), format!("# Keep this comment: {path}\nFILES=(\n \"{path}\"\n '{path}.other'\n /keep.bin\n)\nOTHER='{path}'\n")).unwrap(); - let output = fixture.run(true); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - let config = fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(); - assert!(!config.contains(&format!("\"{path}\"")), "{config}"); - assert!(config.contains(&format!("'{path}.other'")), "{config}"); - assert!(config.contains(&format!("OTHER='{path}'"))); - assert!(config.contains(&format!("# Keep this comment: {path}"))); - } - - #[test] - fn install_migrates_legacy_entries_without_removing_other_files() { - let fixture = ScriptFixture::new(); - let path = fixture.firmware().display().to_string(); - fs::write(fixture.dir.join("mkinitcpio.conf"), format!( - "# Keep this comment: {path}\nFILES=(\n \"{path}\"\n /other-monitor.bin\n '{path}.other'\n)\nFILES+=(\"{path}\")\n" - )).unwrap(); - for _ in 0..2 { - let output = fixture.run(false); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - } - let config = fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(); - assert!(!config.contains(&format!("\"{path}\""))); - assert!(config.contains("/other-monitor.bin")); - assert!(config.contains(&format!("'{path}.other'"))); - assert!(config.contains(&format!("# Keep this comment: {path}"))); - let dropin = fs::read_to_string(fixture.mkinitcpio_dropin()).unwrap(); - assert_eq!(dropin.matches(&format!("\"{path}\"")).count(), 1); - assert!(dropin.contains("FILES+=")); - } - - #[test] - fn dropin_retains_other_monitors_and_is_removed_after_the_last_uninstall() { - let fixture = ScriptFixture::new(); - let original = "FILES=(/keep.bin)\n"; - fs::write(fixture.dir.join("mkinitcpio.conf"), original).unwrap(); - for connector in ["DP-1", "HDMI-A-1", "DP-1"] { - let output = fixture.run_for_connector(false, connector); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - } - let dropin = fs::read_to_string(fixture.mkinitcpio_dropin()).unwrap(); - assert_eq!(dropin.matches("drmcru_custom_DP-1.bin").count(), 1); - assert_eq!(dropin.matches("drmcru_custom_HDMI-A-1.bin").count(), 1); - let output = fixture.run(true); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - let dropin = fs::read_to_string(fixture.mkinitcpio_dropin()).unwrap(); - assert!(!dropin.contains("drmcru_custom_DP-1.bin")); - assert!(dropin.contains("drmcru_custom_HDMI-A-1.bin")); - assert!(!fixture.firmware().exists()); - assert!( - fixture - .dir - .join("firmware/drmcru_custom_HDMI-A-1.bin") - .exists() - ); - let output = fixture.run_for_connector(true, "HDMI-A-1"); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - assert!(!fixture.mkinitcpio_dropin().exists()); - assert_eq!( - fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(), - original - ); - } - - #[test] - fn existing_dropin_assignments_are_converted_to_appends_and_settings_retained() { - let fixture = ScriptFixture::new(); - fs::create_dir_all(fixture.mkinitcpio_dropin().parent().unwrap()).unwrap(); - fs::write( - fixture.mkinitcpio_dropin(), - "# Keep this comment\nFILES=(/other-monitor.bin)\nCOMPRESSION=zstd\n", - ) - .unwrap(); - let output = fixture.run(false); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - let dropin = fs::read_to_string(fixture.mkinitcpio_dropin()).unwrap(); - assert!(dropin.contains("FILES+=(/other-monitor.bin")); - assert!(dropin.contains("COMPRESSION=zstd")); - let output = fixture.run(true); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - let dropin = fs::read_to_string(fixture.mkinitcpio_dropin()).unwrap(); - assert!(dropin.contains("/other-monitor.bin")); - assert!(dropin.contains("COMPRESSION=zstd")); - assert!(dropin.contains("# Keep this comment")); - } - - #[test] - fn multiple_dropin_arrays_keep_one_entry_per_installed_connector() { - let fixture = ScriptFixture::new(); - fs::create_dir_all(fixture.mkinitcpio_dropin().parent().unwrap()).unwrap(); - let path = fixture.firmware().display().to_string(); - fs::write( - fixture.mkinitcpio_dropin(), - format!("FILES+=(/keep-a.bin \"{path}\")\nFILES+=(/keep-b.bin \"{path}\")\n"), - ) - .unwrap(); - for connector in ["DP-1", "HDMI-A-1", "DP-1", "HDMI-A-1"] { - let output = fixture.run_for_connector(false, connector); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - } - let dropin = fs::read_to_string(fixture.mkinitcpio_dropin()).unwrap(); - assert_eq!(dropin.matches("drmcru_custom_DP-1.bin").count(), 1); - assert_eq!(dropin.matches("drmcru_custom_HDMI-A-1.bin").count(), 1); - assert!(dropin.contains("/keep-a.bin")); - assert!(dropin.contains("/keep-b.bin")); - } - - #[test] - fn failed_new_install_removes_new_dropin_and_restores_boot_configuration() { - let fixture = ScriptFixture::new(); - fixture.command("limine-mkinitcpio", "exit 42"); - let output = fixture.run(false); - assert!(!output.status.success()); - assert!(!fixture.firmware().exists()); - assert!(!fixture.mkinitcpio_dropin().exists()); - assert!(!fixture.mkinitcpio_dropin().parent().unwrap().exists()); - assert_eq!( - fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(), - "FILES=()\n" - ); - assert_eq!( - fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(), - "cmdline: quiet\n" - ); - assert!(!fixture.dir.join("entry-tool/drmcru-edid.conf").exists()); - } - - #[test] - fn unsupported_legacy_syntax_rolls_back_the_new_dropin_and_firmware() { - let fixture = ScriptFixture::new(); - let original = format!( - "FILES=(\"{}\" $(printf /keep.bin))\n", - fixture.firmware().display() - ); - fs::write(fixture.dir.join("mkinitcpio.conf"), &original).unwrap(); - let output = fixture.run(false); - assert!(!output.status.success()); - assert!( - String::from_utf8_lossy(&output.stderr) - .contains("command substitutions are unsupported") - ); - assert_eq!( - fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(), - original - ); - assert!(!fixture.firmware().exists()); - assert!(!fixture.mkinitcpio_dropin().exists()); - } - - #[test] - fn preset_backend_rejects_explicit_configs_before_install_or_uninstall_changes() { - for uninstall in [false, true] { - let fixture = ScriptFixture::new(); - fs::write(fixture.dir.join("without-limine"), "").unwrap(); - fs::create_dir_all(fixture.dir.join("presets")).unwrap(); - fs::write( - fixture.dir.join("presets/linux.preset"), - "ALL_config='/etc/mkinitcpio.conf'\n", - ) - .unwrap(); - fs::write(fixture.firmware(), b"old-edid").unwrap(); - let output = fixture.run(uninstall); - assert!(!output.status.success()); - assert!( - String::from_utf8_lossy(&output.stdout) - .contains("explicit mkinitcpio config disables") - ); - assert_eq!(fs::read(fixture.firmware()).unwrap(), b"old-edid"); - assert!(!fixture.mkinitcpio_dropin().exists()); - assert_eq!( - fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(), - "cmdline: quiet\n" - ); - } - } - - #[test] - fn invalid_dropin_path_is_rejected_before_any_system_files_change() { - let fixture = ScriptFixture::new(); - fs::create_dir_all(fixture.mkinitcpio_dropin()).unwrap(); - fs::write(fixture.firmware(), b"old-edid").unwrap(); - for uninstall in [false, true] { - let output = fixture.run(uninstall); - assert!(!output.status.success()); - assert!( - String::from_utf8_lossy(&output.stderr) - .contains("must be a regular configuration file") - ); - assert_eq!(fs::read(fixture.firmware()).unwrap(), b"old-edid"); - assert_eq!( - fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(), - "cmdline: quiet\n" - ); - } - } - - #[test] - fn preset_backend_accepts_default_configs_and_rebuilds_with_the_dropin() { - let fixture = ScriptFixture::new(); - fs::write(fixture.dir.join("without-limine"), "").unwrap(); - fs::create_dir_all(fixture.dir.join("presets")).unwrap(); - fs::write(fixture.dir.join("presets/linux.preset"), "#ALL_config='/etc/mkinitcpio.conf'\nALL_config=''\ndefault_config=\"\" # use default\n").unwrap(); - // Read the effective FILES just as mkinitcpio does; do not rebuild any - // real image or run the host's Limine helpers. - fixture.command( - "mkinitcpio", - &format!( - ". {}\n. {}\nprintf '%s\\n' \"${{FILES[@]}}\" > {}", - shell_quote(&fixture.dir.join("mkinitcpio.conf").display().to_string()), - shell_quote(&fixture.mkinitcpio_dropin().display().to_string()), - shell_quote(&fixture.dir.join("rebuild-files").display().to_string()) - ), - ); - let output = fixture.run(false); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - assert_eq!( - fs::read_to_string(fixture.dir.join("rebuild-files")).unwrap(), - format!("{}\n", fixture.firmware().display()) - ); - } - - #[test] - fn support_report_detects_explicit_preset_configs_without_executing_them() { - let fixture = ScriptFixture::new(); - let presets = fixture.dir.join("presets"); - fs::create_dir_all(&presets).unwrap(); - let marker = fixture.dir.join("must-not-execute"); - for assignment in [ - "ALL_config='/etc/mkinitcpio.conf'".to_string(), - "export default_config=\"/custom.conf\"".to_string(), - format!( - "ALL_config=$(touch {})", - shell_quote(&marker.display().to_string()) - ), - ] { - fs::write(presets.join("linux.preset"), assignment).unwrap(); - let report = inspect_system_support_with_paths( - &fixture.dir.join("mkinitcpio.conf"), - &presets, - &fixture.dir.join("limine.conf"), - true, - true, - false, - ); - assert!(!report.is_supported()); - assert!( - report - .report_text() - .contains("explicit mkinitcpio config disables") - ); - assert!(!marker.exists()); - // The Limine backend does not build through these presets. - let report = inspect_system_support_with_paths( - &fixture.dir.join("mkinitcpio.conf"), - &presets, - &fixture.dir.join("limine.conf"), - true, - true, - true, - ); - assert!(report.is_supported()); - } - } - - #[test] - fn installed_override_status_finds_dropin_without_a_legacy_reference() { - let fixture = ScriptFixture::new(); - let output = fixture.run(false); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - let status = inspect_override_with_paths( - "DP-1", - "drmcru_custom_DP-1.bin", - &sample_plan().kernel_parameter, - OverrideInspectionPaths { - firmware_target: &fixture.firmware(), - mkinitcpio_conf: &fixture.dir.join("mkinitcpio.conf"), - mkinitcpio_dropin: &fixture.mkinitcpio_dropin(), - bootloader_conf: &fixture.dir.join("limine.conf"), - limine_entry_tool_dropin: &fixture.dir.join("entry-tool/drmcru-edid.conf"), - active_cmdline: &fixture.dir.join("no-active-cmdline"), - }, - ); - assert!(status.mkinitcpio_references_firmware); - assert_eq!(status.short_label(), "installed, reboot pending"); - assert!(status.read_warnings.is_empty()); - } - - #[test] - fn system_support_accepts_limine_mkinitcpio_stack() { - let dir = unique_test_dir(); - let mkinit_dir = dir.join("mkinitcpio.d"); - fs::create_dir_all(&mkinit_dir).unwrap(); - let mkinit = dir.join("mkinitcpio.conf"); - let limine = dir.join("limine.conf"); - fs::write(&mkinit, "FILES=()\n").unwrap(); - fs::write(mkinit_dir.join("linux.preset"), "preset\n").unwrap(); - fs::write(&limine, "cmdline: quiet\n").unwrap(); - - let report = - inspect_system_support_with_paths(&mkinit, &mkinit_dir, &limine, true, true, false); - - assert!(report.is_supported()); - assert!(report.blocking_issues().is_empty()); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn system_support_accepts_limine_mkinitcpio_without_presets() { - let dir = unique_test_dir(); - let mkinit_dir = dir.join("mkinitcpio.d"); - fs::create_dir_all(&mkinit_dir).unwrap(); - let mkinit = dir.join("mkinitcpio.conf"); - let limine = dir.join("limine.conf"); - fs::write(&mkinit, "FILES=()\n").unwrap(); - fs::write(&limine, "cmdline: quiet\n").unwrap(); - - let report = - inspect_system_support_with_paths(&mkinit, &mkinit_dir, &limine, true, true, true); - - assert!(report.is_supported()); - assert!(report.blocking_issues().is_empty()); - assert_eq!(report.rebuild_backend_label(), "limine-mkinitcpio"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn system_support_defers_protected_limine_config_to_privileged_installer() { - let limine = Path::new("/boot/limine.conf"); - - let mut warnings = Vec::new(); - let result = inspect_limine_config_read( - Err(io::Error::from(io::ErrorKind::PermissionDenied)), - limine, - &mut warnings, - ); - assert_eq!(result, (true, false, true)); - assert!(warnings.is_empty()); - - let report = SystemSupportReport { - pkexec_available: true, - mkinitcpio_available: true, - mkinitcpio_conf_present: true, - mkinitcpio_presets_present: false, - limine_mkinitcpio_available: true, - limine_conf_present: result.0, - limine_has_cmdline: result.1, - limine_validation_deferred: result.2, - read_warnings: warnings, - }; - assert!(report.is_supported()); - assert!( - report - .summary_lines() - .iter() - .any(|line| line.contains("will verify after authentication")) - ); - } - - #[test] - fn system_support_blocks_missing_limine_cmdline() { - let dir = unique_test_dir(); - let mkinit_dir = dir.join("mkinitcpio.d"); - fs::create_dir_all(&mkinit_dir).unwrap(); - let mkinit = dir.join("mkinitcpio.conf"); - let limine = dir.join("limine.conf"); - fs::write(&mkinit, "FILES=()\n").unwrap(); - fs::write(mkinit_dir.join("linux.preset"), "preset\n").unwrap(); - fs::write(&limine, "timeout: 3\n").unwrap(); - - let report = - inspect_system_support_with_paths(&mkinit, &mkinit_dir, &limine, true, true, false); - - assert!(!report.is_supported()); - assert!( - report - .blocking_issues() - .iter() - .any(|issue| issue.contains("no cmdline")) - ); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn script_contains_all_steps() { - let script = build_install_script(&sample_plan()); - assert!(script.contains("install -D -m 0644")); - assert!(script.contains("/lib/firmware/edid/drmcru_custom_DP-1.bin")); - assert!(script.contains("mkinitcpio.conf")); - assert!(script.contains("drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin")); - assert!(script.contains("limine.conf")); - assert!(script.contains("limine-entry-tool.d")); - assert!(script.contains("drmcru-edid.conf")); - assert!(script.contains("limine-mkinitcpio")); - assert!(script.contains("mkinitcpio -P")); - } - - #[test] - fn script_is_idempotent() { - let script = build_install_script(&sample_plan()); - // Repeated installs retain one FILES entry and de-duplicate mappings. - assert!(script.contains("operation=add")); - assert!(script.contains("if (!seen[mapping]++)")); - assert!(script.contains("index(mapping, connector \":\") == 1")); - } - - #[test] - fn script_creates_backups_before_config_edits() { - let script = build_install_script(&sample_plan()); - assert!(script.contains("BACKUP_SUFFIX")); - assert!(script.contains("backup_file \"$MKINIT_DROPIN\"")); - assert!(script.contains("backup_file \"$MKINIT\"")); - assert!(script.contains("backup_file \"$LIMINE\"")); - assert!(script.contains("backup_file \"$LIMINE_DROPIN\"")); - } - - #[test] - fn install_rollback_removes_new_limine_dropin() { - let script = build_install_script(&sample_plan()); - - assert!(script.contains("LIMINE_DROPIN_WAS_PRESENT=0")); - assert!(script.contains("rm -f -- \"$LIMINE_DROPIN\" || true")); - assert!(script.contains("rmdir -- \"$LIMINE_DROPIN_DIR\"")); - } - - #[test] - fn script_shell_quotes_interpolated_values() { - let plan = InstallPlan { - connector: "DP-1".to_string(), - edid_source: PathBuf::from("/tmp/hypr cru's.bin"), - edid_file_name: "hypr cru's.bin".to_string(), - kernel_parameter: "drm.edid_firmware=DP-1:edid/hypr cru's.bin".to_string(), - }; - let script = build_install_script(&plan); - - assert!(script.contains("EDID_SOURCE='/tmp/hypr cru'\\''s.bin'")); - assert!(script.contains("FIRMWARE_TARGET='/lib/firmware/edid/hypr cru'\\''s.bin'")); - assert!(script.contains("KERNEL_PARAM='drm.edid_firmware=DP-1:edid/hypr cru'\\''s.bin'")); - } - - #[test] - fn validation_rejects_firmware_names_with_path_separators() { - assert!(matches!( - validate_firmware_file_name("../escape.bin"), - Err(InstallError::UnsafeFirmwareName(_)) - )); - } - - #[test] - fn uninstall_script_removes_edid_references() { - let script = build_uninstall_script(&sample_uninstall_plan()); - assert!(script.contains("rm -f -- \"$FIRMWARE_TARGET\"")); - assert!(script.contains("Removed EDID from mkinitcpio FILES")); - assert!(script.contains("Removed persistent Limine entry-tool kernel parameter")); - assert!(script.contains("Removed connector mapping from Limine cmdline entries")); - assert!(script.contains("limine-mkinitcpio")); - assert!(script.contains("mkinitcpio -P")); - } - - #[test] - fn install_script_preflights_supported_stack_before_mutating() { - let script = build_install_script(&sample_plan()); - let mkinit_check = script - .find("[ERR] /etc/mkinitcpio.conf not found") - .expect("mkinitcpio config preflight"); - let limine_check = script - .find("[ERR] /boot/limine.conf not found") - .expect("Limine config preflight"); - let cmdline_check = script - .find("[ERR] /boot/limine.conf has no cmdline entries") - .expect("Limine cmdline preflight"); - let rebuild_backend_check = script - .find("[ERR] No initramfs rebuild backend found") - .expect("initramfs backend preflight"); - let command_check = script - .find("[ERR] mkinitcpio was not found") - .expect("mkinitcpio command preflight"); - let first_mutation = script - .find("install -D -m 0644") - .expect("firmware install mutation"); - - assert!(mkinit_check < first_mutation); - assert!(limine_check < first_mutation); - assert!(cmdline_check < first_mutation); - assert!(rebuild_backend_check < first_mutation); - assert!(command_check < first_mutation); - } - - #[test] - fn install_script_updates_missing_limine_cmdlines_instead_of_global_skip() { - let script = build_install_script(&sample_plan()); - - assert!(script.contains("Consolidated EDID mappings in all Limine cmdline entries")); - assert!(script.contains("combined == \"\" ? \"\" : \",\"")); - assert!(!script.contains("Kernel parameter already in Limine config (skipped)")); - } - - #[test] - fn mapping_detection_handles_consolidated_kernel_parameter() { - let dp1 = "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin"; - let cmdline = "quiet drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin,eDP-1:edid/drmcru_custom_eDP-1.bin splash"; - - assert!(text_contains_kernel_mapping(cmdline, dp1)); - assert!(text_contains_kernel_mapping( - cmdline, - "drm.edid_firmware=eDP-1:edid/drmcru_custom_eDP-1.bin" - )); - assert!(!text_contains_kernel_mapping( - cmdline, - "drm.edid_firmware=DP-2:edid/drmcru_custom_DP-2.bin" - )); - } - - #[test] - fn generated_privileged_scripts_are_bash_parseable() { - assert_bash_n(&build_install_script(&sample_plan())); - assert_bash_n(&build_uninstall_script(&sample_uninstall_plan())); - } - - fn assert_bash_n(script: &str) { - let dir = unique_test_dir(); - fs::create_dir_all(&dir).unwrap(); - let script_path = dir.join("script.sh"); - fs::write(&script_path, script).unwrap(); - - let output = std::process::Command::new("bash") - .arg("-n") - .arg(&script_path) - .output() - .unwrap(); - - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn uninstall_script_preflights_supported_stack_before_mutating() { - let script = build_uninstall_script(&sample_uninstall_plan()); - let mkinit_check = script - .find("[ERR] /etc/mkinitcpio.conf not found") - .expect("mkinitcpio config preflight"); - let limine_check = script - .find("[ERR] /boot/limine.conf not found") - .expect("Limine config preflight"); - let cmdline_check = script - .find("[ERR] /boot/limine.conf has no cmdline entries") - .expect("Limine cmdline preflight"); - let rebuild_backend_check = script - .find("[ERR] No initramfs rebuild backend found") - .expect("initramfs backend preflight"); - let command_check = script - .find("[ERR] mkinitcpio was not found") - .expect("mkinitcpio command preflight"); - let first_mutation = script - .find("rm -f -- \"$FIRMWARE_TARGET\"") - .expect("firmware removal mutation"); - - assert!(mkinit_check < first_mutation); - assert!(limine_check < first_mutation); - assert!(cmdline_check < first_mutation); - assert!(rebuild_backend_check < first_mutation); - assert!(command_check < first_mutation); - assert!(!script.contains("[WARN]")); - } - - #[test] - fn uninstall_preview_has_all_targets() { - let preview = UninstallPreview::from_plan(&sample_uninstall_plan()); - let lines = preview.summary_lines(); - assert_eq!(lines.len(), 8); - assert!(lines[0].contains("DP-1")); - assert!(lines[1].contains("Remove")); - assert!(lines[2].contains("mkinitcpio")); - assert!(lines[3].contains("legacy")); - assert!(lines[4].contains("limine")); - assert!(lines[5].contains("limine-entry-tool")); - assert!(lines[6].contains("drm.edid_firmware")); - assert!(lines[7].contains("limine-mkinitcpio")); - } - - #[test] - fn installed_override_status_detects_active_install() { - let dir = unique_test_dir(); - fs::create_dir_all(&dir).unwrap(); - - let firmware = dir.join("drmcru_custom_DP-1.bin"); - let mkinit = dir.join("mkinitcpio.conf"); - let limine = dir.join("limine.conf"); - let limine_dropin = dir.join("drmcru-edid.conf"); - let cmdline = dir.join("cmdline"); - let param = "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin"; - fs::write(&firmware, b"edid").unwrap(); - fs::write(&mkinit, format!("FILES=({})\n", firmware.display())).unwrap(); - fs::write(&limine, format!("cmdline: quiet {param}\n")).unwrap(); - fs::write( - &limine_dropin, - format!("KERNEL_CMDLINE[default]+=\" {param}\"\n"), - ) - .unwrap(); - fs::write(&cmdline, format!("root=/dev/sda1 {param}\n")).unwrap(); - - let status = inspect_override_with_paths( - "DP-1", - "drmcru_custom_DP-1.bin", - param, - OverrideInspectionPaths { - firmware_target: &firmware, - mkinitcpio_conf: &mkinit, - mkinitcpio_dropin: &dir.join("20-drmcru.conf"), - bootloader_conf: &limine, - limine_entry_tool_dropin: &limine_dropin, - active_cmdline: &cmdline, - }, - ); - - assert!(status.firmware_present); - assert!(status.mkinitcpio_references_firmware); - assert!(status.bootloader_references_kernel_parameter); - assert!(status.limine_entry_tool_references_kernel_parameter); - assert_eq!(status.bootloader_cmdline_entries, 1); - assert_eq!(status.bootloader_cmdline_entries_with_kernel_parameter, 1); - assert!(status.active_kernel_references_kernel_parameter); - assert_eq!(status.short_label(), "active"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn installed_override_status_detects_missing_override() { - let dir = unique_test_dir(); - fs::create_dir_all(&dir).unwrap(); - - let firmware = dir.join("drmcru_custom_DP-1.bin"); - let mkinit = dir.join("mkinitcpio.conf"); - let limine = dir.join("limine.conf"); - let limine_dropin = dir.join("drmcru-edid.conf"); - let cmdline = dir.join("cmdline"); - let param = "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin"; - fs::write(&mkinit, "FILES=()\n").unwrap(); - fs::write(&limine, "cmdline: quiet\n").unwrap(); - fs::write(&cmdline, "root=/dev/sda1\n").unwrap(); - - let status = inspect_override_with_paths( - "DP-1", - "drmcru_custom_DP-1.bin", - param, - OverrideInspectionPaths { - firmware_target: &firmware, - mkinitcpio_conf: &mkinit, - mkinitcpio_dropin: &dir.join("20-drmcru.conf"), - bootloader_conf: &limine, - limine_entry_tool_dropin: &limine_dropin, - active_cmdline: &cmdline, - }, - ); - - assert!(!status.has_any_override()); - assert_eq!(status.short_label(), "not installed"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn installed_override_status_detects_partial_limine_cmdline_install() { - let dir = unique_test_dir(); - fs::create_dir_all(&dir).unwrap(); - - let firmware = dir.join("drmcru_custom_DP-1.bin"); - let mkinit = dir.join("mkinitcpio.conf"); - let limine = dir.join("limine.conf"); - let limine_dropin = dir.join("drmcru-edid.conf"); - let cmdline = dir.join("cmdline"); - let param = "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin"; - fs::write(&firmware, b"edid").unwrap(); - fs::write(&mkinit, format!("FILES=({})\n", firmware.display())).unwrap(); - fs::write(&limine, format!("cmdline: quiet\ncmdline: quiet {param}\n")).unwrap(); - fs::write(&cmdline, "root=/dev/sda1\n").unwrap(); - - let status = inspect_override_with_paths( - "DP-1", - "drmcru_custom_DP-1.bin", - param, - OverrideInspectionPaths { - firmware_target: &firmware, - mkinitcpio_conf: &mkinit, - mkinitcpio_dropin: &dir.join("20-drmcru.conf"), - bootloader_conf: &limine, - limine_entry_tool_dropin: &limine_dropin, - active_cmdline: &cmdline, - }, - ); - - assert!(status.bootloader_references_kernel_parameter); - assert_eq!(status.bootloader_cmdline_entries, 2); - assert_eq!(status.bootloader_cmdline_entries_with_kernel_parameter, 1); - assert!(!status.is_configured_for_next_boot()); - assert_eq!(status.short_label(), "partial install"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn firmware_comparison_detects_matching_live_edid() { - let dir = unique_test_dir(); - fs::create_dir_all(&dir).unwrap(); - let firmware = dir.join("drmcru_custom_DP-1.bin"); - fs::write(&firmware, b"edid-bytes").unwrap(); - - let comparison = compare_firmware_to_live_edid(&firmware, Some(b"edid-bytes")); - - assert_eq!(comparison, FirmwareEdidComparison::Matches { bytes: 10 }); - assert_eq!(comparison.short_label(), "matches"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn firmware_comparison_detects_different_live_edid() { - let dir = unique_test_dir(); - fs::create_dir_all(&dir).unwrap(); - let firmware = dir.join("drmcru_custom_DP-1.bin"); - fs::write(&firmware, b"firmware").unwrap(); - - let comparison = compare_firmware_to_live_edid(&firmware, Some(b"live")); - - assert_eq!( - comparison, - FirmwareEdidComparison::Differs { - firmware_bytes: 8, - live_bytes: 4, - } - ); - assert!(comparison.detail().contains("differs")); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn preview_summary_has_all_targets() { - let preview = InstallPreview::from_plan(&sample_plan()); - let lines = preview.summary_lines(); - assert_eq!(lines.len(), 8); - assert!(lines[0].contains("DP-1")); - assert!(lines[1].contains("firmware")); - assert!(lines[2].contains("mkinitcpio")); - assert!(lines[3].contains("legacy")); - assert!(lines[4].contains("limine")); - assert!(lines[5].contains("limine-entry-tool")); - assert!(lines[6].contains("drm.edid_firmware")); - assert!(lines[7].contains("limine-mkinitcpio")); - } -} +#[path = "install_tests.rs"] +mod tests; diff --git a/src/install_tests.rs b/src/install_tests.rs new file mode 100644 index 0000000..4d81fff --- /dev/null +++ b/src/install_tests.rs @@ -0,0 +1,1095 @@ +use super::*; +use std::collections::BTreeMap; +use std::os::unix::fs::symlink; + +const MACHINE: &str = "00000000000000000000000000000000"; +const BASE_ARGS: &str = "root=UUID=test cryptdevice=UUID=crypt:root quiet"; +fn sample_plan() -> InstallPlan { + InstallPlan { + connector: "DP-1".into(), + edid_source: "/tmp/source.bin".into(), + edid_file_name: "drmcru_custom_DP-1.bin".into(), + kernel_parameter: "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin".into(), + } +} +fn sample_uninstall_plan() -> UninstallPlan { + let plan = sample_plan(); + UninstallPlan { + connector: plan.connector, + edid_file_name: plan.edid_file_name, + kernel_parameter: plan.kernel_parameter, + } +} +fn unique_test_dir() -> PathBuf { + std::env::temp_dir().join(format!( + "drmcru-transaction-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )) +} +struct ScriptFixture { + dir: PathBuf, +} +impl ScriptFixture { + fn new() -> Self { + let fixture = Self { + dir: unique_test_dir(), + }; + for path in [ + "bin", + "boot", + "firmware-root/edid", + "entry-tool", + "tmp", + "locks", + "modules/test-6.0", + "drm/card0-DP-1", + "hooks/pre.d", + "hooks/post.d", + ] { + fs::create_dir_all(fixture.dir.join(path)).unwrap(); + } + fs::write(fixture.dir.join("source.bin"), b"new-edid").unwrap(); + fs::write(fixture.dir.join("mkinitcpio.conf"), "FILES=()\n").unwrap(); + fs::write(fixture.dir.join("machine-id"), MACHINE).unwrap(); + fs::write(fixture.dir.join("kernel-cmdline"), BASE_ARGS).unwrap(); + fs::write(fixture.dir.join("modules/test-6.0/modules.builtin"), "").unwrap(); + fs::write(fixture.dir.join("modules/test-6.0/pkgbase"), "linux-test").unwrap(); + fs::write(fixture.dir.join("modules/test-6.0/vmlinuz"), b"new-kernel").unwrap(); + fs::write(fixture.dir.join("drm/card0-DP-1/status"), "connected").unwrap(); + fs::write(fixture.dir.join("entry-base.conf"), "").unwrap(); + fixture.kernel_entry("linux-test", BASE_ARGS); + symlink( + fixture.dir.join("boot/limine.conf"), + fixture.dir.join("limine.conf"), + ) + .unwrap(); + fs::write( + fixture.dir.join("common-functions"), + r#" +load_config() { + ESP_PATH="$TEST_ROOT/boot" + ENABLE_UKI="$TEST_UKI" + MKINITCPIO_FALLBACK="$TEST_FALLBACK" +} +check_boot_partition() { return 0; } +is_uefi() { [ "$TEST_UKI" = yes ]; } +is_sb_installed() { [ "$TEST_NO_EMBED" = yes ]; } +is_snapper_installed() { [ "$TEST_NO_EMBED" = yes ]; } +"#, + ) + .unwrap(); + fixture.command("id", "printf '0\\n'"); + fixture.command( + "limine-mkinitcpio", + "echo wrapper-must-not-run >&2; exit 99", + ); + fixture.command("pacman", "cat \"$(dirname \"$2\")/pkgbase\""); + fixture.command("findmnt", "printf '%s\\n' \"$TEST_ROOT/boot\""); + fixture.command("lsinitcpio", "tar -xf \"$2\""); + fixture.command( + "objcopy", + r#" +previous=""; source="" +for argument in "$@"; do source="$previous"; previous="$argument"; done +target="$previous" +if tar -tf "$source" | grep -qx './.cmdline'; then + tar -xOf "$source" ./.cmdline > "$target" +else : > "$target"; fi +"#, + ); + fixture.write_executable( + "limine-entry-tool", + include_str!("../tests/fixtures/limine-entry-tool.py"), + ); + fixture.write_executable( + "mkinitcpio", + include_str!("../tests/fixtures/mkinitcpio.sh"), + ); + fixture + } + fn kernel_entry(&self, name: &str, arguments: &str) { + let folder = self.dir.join(format!("boot/{MACHINE}/{name}")); + fs::create_dir_all(&folder).unwrap(); + fs::write(folder.join("vmlinuz"), b"old-kernel").unwrap(); + fs::write(folder.join("initramfs"), b"old-image").unwrap(); + let path = self.dir.join("boot/limine.conf"); + let mut contents = fs::read_to_string(&path).unwrap_or_default(); + contents.push_str(&format!("/{name}\n protocol: linux\n path: boot():/{MACHINE}/{name}/vmlinuz\n module_path: boot():/{MACHINE}/{name}/initramfs\n cmdline: {arguments}\n")); + fs::write(path, contents).unwrap(); + } + fn write_executable(&self, name: &str, body: &str) { + let path = self.dir.join("bin").join(name); + fs::write(&path, body).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); + } + fn command(&self, name: &str, body: &str) { + self.write_executable(name, &format!("#!/bin/bash\nset -euo pipefail\n{body}\n")); + } + fn run(&self, uninstall: bool) -> std::process::Output { + self.run_options(uninstall, "DP-1", &[]) + } + fn run_options( + &self, + uninstall: bool, + connector: &str, + environment: &[(&str, &str)], + ) -> std::process::Output { + let mut plan = sample_plan(); + plan.connector = connector.into(); + plan.edid_file_name = format!("drmcru_custom_{connector}.bin"); + plan.edid_source = self.dir.join("source.bin"); + let mut script = if uninstall { + build_uninstall_script(&UninstallPlan { + connector: plan.connector, + edid_file_name: plan.edid_file_name, + kernel_parameter: plan.kernel_parameter, + }) + } else { + build_install_script(&plan) + }; + for (variable, original, relative) in [ + ("MKINITCPIO_BIN", "/usr/bin/mkinitcpio", "bin/mkinitcpio"), + ("LSINITCPIO_BIN", "/usr/bin/lsinitcpio", "bin/lsinitcpio"), + ( + "ENTRY_TOOL_BIN", + "/usr/bin/limine-entry-tool", + "bin/limine-entry-tool", + ), + ("OBJCOPY_BIN", "/usr/bin/objcopy", "bin/objcopy"), + ("FIRMWARE_ROOT", "/lib/firmware", "firmware-root"), + ("BOOT_ROOT", "/boot", "boot"), + ("MKINIT", "/etc/mkinitcpio.conf", "mkinitcpio.conf"), + ( + "LIMINE_DROPIN_DIR", + "/etc/limine-entry-tool.d", + "entry-tool", + ), + ( + "LIMINE_CONFIG", + "/etc/limine-entry-tool.conf", + "entry-base.conf", + ), + ( + "LIMINE_DEFAULT_CONFIG", + "/etc/default/limine", + "default.conf", + ), + ( + "LIMINE_VENDOR_DIR", + "/usr/share/limine-entry-tool.d", + "vendor", + ), + ( + "LIMINE_FUNCTIONS", + "/usr/lib/limine/limine-common-functions", + "common-functions", + ), + ("BOOT_HOOKS", "/etc/boot/hooks", "hooks"), + ( + "BOOT_LOCK", + "/run/lock/boot-partition.lock", + "locks/boot.lock", + ), + ( + "PACKAGE_LOCK", + "/var/lib/pacman/db.lck", + "locks/package.lock", + ), + ("TRANSACTION_ROOT", "/var/tmp", "tmp"), + ("MODULES_ROOT", "/usr/lib/modules", "modules"), + ("MACHINE_ID_FILE", "/etc/machine-id", "machine-id"), + ("DRM_ROOT", "/sys/class/drm", "drm"), + ] { + script = script.replace( + &format!("{variable}=\"{original}\""), + &format!( + "{variable}={}", + shell_quote(&self.dir.join(relative).display().to_string()) + ), + ); + } + Command::new("bash") + .args(["-c", &script]) + .env("TEST_ROOT", &self.dir) + .env("TEST_UKI", "no") + .env("TEST_FALLBACK", "no") + .env("TEST_NO_EMBED", "no") + .envs(environment.iter().copied()) + .env( + "PATH", + format!( + "{}:{}", + self.dir.join("bin").display(), + std::env::var("PATH").unwrap() + ), + ) + .output() + .unwrap() + } + fn firmware(&self) -> PathBuf { + self.dir.join("firmware-root/edid/drmcru_custom_DP-1.bin") + } + fn mkinitcpio_dropin(&self) -> PathBuf { + self.dir.join("mkinitcpio.conf.d/20-drmcru.conf") + } + fn boot(&self) -> BTreeMap> { + fn collect(root: &Path, base: &Path, files: &mut BTreeMap>) { + for entry in fs::read_dir(root).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + collect(&path, base, files); + } else { + files.insert( + path.strip_prefix(base).unwrap().to_path_buf(), + fs::read(&path).unwrap(), + ); + } + } + } + let mut files = BTreeMap::new(); + collect(&self.dir.join("boot"), &self.dir.join("boot"), &mut files); + files + } +} +impl Drop for ScriptFixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.dir); + } +} +fn success(output: &std::process::Output) { + assert!( + output.status.success(), + "stdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn staged_install_preserves_fallback_arguments_and_keeps_recovery() { + let fixture = ScriptFixture::new(); + success(&fixture.run(false)); + let menu = fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(); + assert!(menu.contains(BASE_ARGS)); + assert!(menu.contains("drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin")); + assert!(menu.contains("# BEGIN drmcru recovery")); + assert_eq!( + fs::read(fixture.dir.join("boot/drmcru-recovery/0-vmlinuz")).unwrap(), + b"old-kernel" + ); + assert_eq!(fs::read(fixture.firmware()).unwrap(), b"new-edid"); + assert!(!fixture.dir.join("locks/package.lock").exists()); +} +#[test] +fn zero_exit_without_a_built_image_is_rejected_and_rolled_back() { + let fixture = ScriptFixture::new(); + let before = fixture.boot(); + fs::write(fixture.dir.join("skip-build"), "").unwrap(); + let output = fixture.run(false); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Image was not produced"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(fixture.boot(), before); + assert!(!fixture.firmware().exists()); +} +#[test] +fn outdated_firmware_in_an_image_is_rejected() { + let fixture = ScriptFixture::new(); + let before = fixture.boot(); + fs::write(fixture.dir.join("wrong-firmware"), "").unwrap(); + assert!(!fixture.run(false).status.success()); + assert_eq!(fixture.boot(), before); + assert!(!fixture.firmware().exists()); +} +#[test] +fn failure_after_install_restores_boot_images_metadata_and_firmware() { + for uninstall in [false, true] { + let fixture = ScriptFixture::new(); + if uninstall { + success(&fixture.run(false)); + } + let before = fixture.boot(); + let firmware = fs::read(fixture.firmware()).ok(); + let config = fs::read(fixture.mkinitcpio_dropin()).ok(); + fs::write(fixture.dir.join("fail-after-install"), "").unwrap(); + let output = fixture.run(uninstall); + assert!(!output.status.success()); + assert_eq!(fixture.boot(), before); + assert_eq!(fs::read(fixture.firmware()).ok(), firmware); + assert_eq!(fs::read(fixture.mkinitcpio_dropin()).ok(), config); + assert!(!fixture.dir.join("locks/package.lock").exists()); + } +} +#[test] +fn a_post_hook_failure_restores_even_unrelated_boot_files() { + let fixture = ScriptFixture::new(); + let before = fixture.boot(); + let hook = fixture.dir.join("hooks/post.d/fail"); + fs::write( + &hook, + "#!/bin/bash\nprintf changed > \"$TEST_ROOT/boot/extra-image\"\nexit 42\n", + ) + .unwrap(); + fs::set_permissions(hook, fs::Permissions::from_mode(0o755)).unwrap(); + assert!(!fixture.run(false).status.success()); + assert_eq!(fixture.boot(), before); +} +#[test] +fn external_and_per_kernel_overrides_are_consolidated_without_losing_arguments() { + let fixture = ScriptFixture::new(); + fs::write( + fixture.dir.join("firmware-root/edid/other.bin"), + b"other-edid", + ) + .unwrap(); + fs::write(fixture.dir.join("entry-base.conf"), + "KERNEL_CMDLINE[default]=root=UUID=test quiet drm.edid_firmware=HDMI-A-1:edid/other.bin\nKERNEL_CMDLINE[linux-test]=root=UUID=special rootflags=\"subvol=/with space\" drm.edid_firmware=HDMI-A-1:edid/other.bin\n").unwrap(); + success(&fixture.run(false)); + let own = fs::read_to_string(fixture.dir.join("default.conf")).unwrap(); + let line = own + .lines() + .find(|line| line.starts_with("KERNEL_CMDLINE[linux-test]=")) + .unwrap(); + assert!(line.contains("root=UUID=special rootflags=\"subvol=/with space\"")); + assert!(line.contains("HDMI-A-1:edid/other.bin")); + assert!(line.contains("DP-1:edid/drmcru_custom_DP-1.bin")); + assert_eq!(line.matches("drm.edid_firmware=").count(), 1); +} +#[test] +fn legacy_edid_only_default_is_repaired_before_regeneration() { + let fixture = ScriptFixture::new(); + fs::write( + fixture.dir.join("entry-tool/drmcru-edid.conf"), + "KERNEL_CMDLINE[default]+=\" drm.edid_firmware=DP-1:edid/old.bin\"\n", + ) + .unwrap(); + success(&fixture.run(false)); + let own = fs::read_to_string(fixture.dir.join("default.conf")).unwrap(); + assert!(own.contains(BASE_ARGS)); + assert!(!own.contains("old.bin")); +} +#[test] +fn prefix_collision_is_rejected_before_any_file_changes() { + let fixture = ScriptFixture::new(); + fs::create_dir_all(fixture.dir.join("drm/card0-DP-10")).unwrap(); + fs::write(fixture.dir.join("drm/card0-DP-10/status"), "disconnected").unwrap(); + let before = fixture.boot(); + let output = fixture.run(false); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("also matches DP-10")); + assert_eq!(fixture.boot(), before); + assert!(!fixture.firmware().exists()); +} +#[test] +fn uki_and_fallback_images_are_verified_before_commit() { + let fixture = ScriptFixture::new(); + success(&fixture.run_options( + false, + "DP-1", + &[("TEST_UKI", "yes"), ("TEST_FALLBACK", "yes")], + )); + assert!( + fixture + .dir + .join(format!("boot/EFI/Linux/{MACHINE}_linux-test.efi")) + .is_file() + ); + assert!( + fixture + .dir + .join(format!("boot/EFI/Linux/{MACHINE}_linux-test-fallback.efi")) + .is_file() + ); +} +#[test] +fn repeated_updates_and_uninstall_keep_other_monitor_firmware() { + let fixture = ScriptFixture::new(); + fs::create_dir_all(fixture.dir.join("drm/card0-HDMI-A-1")).unwrap(); + fs::write(fixture.dir.join("drm/card0-HDMI-A-1/status"), "connected").unwrap(); + success(&fixture.run(false)); + success(&fixture.run_options(false, "HDMI-A-1", &[])); + success(&fixture.run(false)); + success(&fixture.run(true)); + let own = fs::read_to_string(fixture.dir.join("entry-tool/drmcru-edid.conf")).unwrap(); + assert!(!own.contains("DP-1:edid/drmcru_custom_DP-1.bin")); + assert!(own.contains("HDMI-A-1:edid/drmcru_custom_HDMI-A-1.bin")); + assert!(!fixture.firmware().exists()); + assert!( + fixture + .dir + .join("firmware-root/edid/drmcru_custom_HDMI-A-1.bin") + .exists() + ); +} + +#[test] +fn highest_priority_appends_remain_once_and_user_lines_survive_uninstall() { + let fixture = ScriptFixture::new(); + let user = "# user settings\nKERNEL_CMDLINE[default]+=root=UUID=encrypted\nKERNEL_CMDLINE[default]+=cryptdevice=UUID=disk:root\nKERNEL_CMDLINE[default]+=rootflags=\"subvol=/with space\"\n"; + fs::write(fixture.dir.join("default.conf"), user).unwrap(); + for _ in 0..2 { + success(&fixture.run(false)); + let config = fs::read_to_string(fixture.dir.join("default.conf")).unwrap(); + assert!(config.starts_with(user)); + let line = config + .lines() + .find(|line| line.starts_with("KERNEL_CMDLINE[linux-test]=")) + .unwrap(); + assert_eq!(line.matches("root=UUID=encrypted").count(), 1); + assert_eq!(line.matches("cryptdevice=UUID=disk:root").count(), 1); + assert_eq!(line.matches("rootflags=").count(), 1); + } + success(&fixture.run(true)); + assert_eq!( + fs::read_to_string(fixture.dir.join("default.conf")).unwrap(), + user + ); +} + +#[test] +fn update_picks_up_changes_to_the_underlying_kernel_command_line() { + let fixture = ScriptFixture::new(); + success(&fixture.run(false)); + let updated = "root=UUID=new cryptdevice=UUID=newdisk:root rw"; + fs::write(fixture.dir.join("kernel-cmdline"), updated).unwrap(); + success(&fixture.run(false)); + let config = fs::read_to_string(fixture.dir.join("default.conf")).unwrap(); + assert!(config.contains(updated)); + assert!(!config.contains(BASE_ARGS)); +} + +#[test] +fn a_new_kernel_inherits_all_previously_managed_monitor_overrides() { + let fixture = ScriptFixture::new(); + fs::create_dir_all(fixture.dir.join("drm/card0-HDMI-A-1")).unwrap(); + fs::write(fixture.dir.join("drm/card0-HDMI-A-1/status"), "connected").unwrap(); + success(&fixture.run(false)); + success(&fixture.run_options(false, "HDMI-A-1", &[])); + fs::create_dir_all(fixture.dir.join("modules/test-6.1")).unwrap(); + for (file, contents) in [ + ("modules.builtin", ""), + ("pkgbase", "linux-other"), + ("vmlinuz", "second-kernel"), + ] { + fs::write(fixture.dir.join("modules/test-6.1").join(file), contents).unwrap(); + } + success(&fixture.run(false)); + let config = fs::read_to_string(fixture.dir.join("default.conf")).unwrap(); + let line = config + .lines() + .find(|line| line.starts_with("KERNEL_CMDLINE[linux-other]=")) + .unwrap(); + assert!(line.contains("HDMI-A-1:edid/drmcru_custom_HDMI-A-1.bin")); + assert!(line.contains("DP-1:edid/drmcru_custom_DP-1.bin")); +} + +#[test] +fn consolidation_keeps_linux_first_connector_match_and_last_global_fallback() { + let fixture = ScriptFixture::new(); + for file in ["first.bin", "fallback2.bin"] { + fs::write(fixture.dir.join("firmware-root/edid").join(file), file).unwrap(); + } + fs::write(fixture.dir.join("entry-base.conf"), "KERNEL_CMDLINE[default]=root=UUID=test drm.edid_firmware=HDMI-A-1:edid/first.bin,HDMI-A-1:edid/second.bin,edid/fallback1.bin,edid/fallback2.bin\n").unwrap(); + success(&fixture.run(false)); + let config = fs::read_to_string(fixture.dir.join("default.conf")).unwrap(); + assert!(config.contains("HDMI-A-1:edid/first.bin")); + assert!(config.contains("edid/fallback2.bin")); + assert!(!config.contains("second.bin")); + assert!(!config.contains("fallback1.bin")); +} + +#[test] +fn incomplete_rollback_keeps_recovery_files_and_does_not_recommend_reboot() { + let fixture = ScriptFixture::new(); + fs::write(fixture.firmware(), b"old-edid").unwrap(); + fixture.command("cp", "for arg in \"$@\"; do if [ \"$arg\" = --remove-destination ]; then exit 42; fi; done\nexec /usr/bin/cp \"$@\""); + fs::write(fixture.dir.join("fail-after-install"), "").unwrap(); + let output = fixture.run(false); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("Recovery was incomplete. Do not reboot") + ); + assert!(!String::from_utf8_lossy(&output.stdout).contains("Reboot to activate")); + assert!( + fs::read_dir(fixture.dir.join("tmp")) + .unwrap() + .any(|entry| entry.unwrap().path().join("boot/limine.conf").exists()) + ); +} + +#[test] +fn a_later_kernel_or_fallback_failure_restores_the_whole_boot_partition() { + for marker in ["fail-second-build", "fail-second-install"] { + for second_kernel in [false, true] { + let fixture = ScriptFixture::new(); + if second_kernel { + fs::create_dir_all(fixture.dir.join("modules/test-6.1")).unwrap(); + for (file, contents) in [ + ("modules.builtin", ""), + ("pkgbase", "linux-other"), + ("vmlinuz", "second-kernel"), + ] { + fs::write(fixture.dir.join("modules/test-6.1").join(file), contents).unwrap(); + } + fixture.kernel_entry("linux-other", BASE_ARGS); + } + let before = fixture.boot(); + fs::write(fixture.dir.join(marker), "").unwrap(); + let env = if second_kernel { + vec![] + } else { + vec![("TEST_FALLBACK", "yes")] + }; + assert!(!fixture.run_options(false, "DP-1", &env).status.success()); + assert_eq!(fixture.boot(), before); + assert!(!fixture.firmware().exists()); + } + } +} + +#[test] +fn successful_hooks_cannot_change_verified_kernels_arguments_or_recovery() { + for change in [ + format!("printf changed > \"$TEST_ROOT/boot/{MACHINE}/linux-test/vmlinuz\""), + "sed -i 's/root=UUID=test/root=UUID=wrong/g' \"$TEST_ROOT/boot/limine.conf\"".into(), + "printf changed > \"$TEST_ROOT/boot/drmcru-recovery/0-vmlinuz\"".into(), + "sed -i 's/drmcru recovery (before last change)/changed recovery/' \"$TEST_ROOT/boot/limine.conf\"".into(), + ] { + let fixture = ScriptFixture::new(); + let before = fixture.boot(); + let hook = fixture.dir.join("hooks/post.d/change"); + fs::write(&hook, format!("#!/bin/bash\n{change}\n")).unwrap(); + fs::set_permissions(hook, fs::Permissions::from_mode(0o755)).unwrap(); + assert!(!fixture.run(false).status.success(), "{change}"); + assert_eq!(fixture.boot(), before); + } +} + +#[test] +fn corrupt_archives_and_wrong_uki_arguments_roll_back() { + for marker in ["bad-archive", "wrong-cmdline"] { + let fixture = ScriptFixture::new(); + let before = fixture.boot(); + fs::write(fixture.dir.join(marker), "").unwrap(); + assert!( + !fixture + .run_options(false, "DP-1", &[("TEST_UKI", "yes")]) + .status + .success() + ); + assert_eq!(fixture.boot(), before); + } +} + +#[test] +fn secure_boot_snapshot_ukis_can_omit_embedded_arguments() { + let fixture = ScriptFixture::new(); + success(&fixture.run_options( + false, + "DP-1", + &[("TEST_UKI", "yes"), ("TEST_NO_EMBED", "yes")], + )); +} + +#[test] +fn switching_boot_image_formats_keeps_recovery_and_replaces_stale_entries() { + let fixture = ScriptFixture::new(); + success(&fixture.run_options(false, "DP-1", &[("TEST_UKI", "yes")])); + assert!( + !fixture + .dir + .join(format!("boot/{MACHINE}/linux-test")) + .exists() + ); + assert!(fixture.dir.join("boot/drmcru-recovery/0-vmlinuz").exists()); + success(&fixture.run(false)); + assert!( + !fixture + .dir + .join(format!("boot/EFI/Linux/{MACHINE}_linux-test.efi")) + .exists() + ); + assert!( + fixture + .dir + .join(format!("boot/{MACHINE}/linux-test/initramfs")) + .exists() + ); + let menu = fs::read_to_string(fixture.dir.join("limine.conf")).unwrap(); + assert!(menu.contains("drmcru recovery (before last change)")); +} + +#[test] +fn failed_command_line_queries_stop_before_changes() { + let fixture = ScriptFixture::new(); + let before = fixture.boot(); + fs::write(fixture.dir.join("fail-query"), "").unwrap(); + assert!(!fixture.run(false).status.success()); + assert_eq!(fixture.boot(), before); + assert!(!fixture.firmware().exists()); + assert!(!fixture.dir.join("default.conf").exists()); +} + +#[test] +fn missing_or_duplicate_connectors_cannot_be_installed() { + for duplicate in [false, true] { + let fixture = ScriptFixture::new(); + if duplicate { + fs::create_dir_all(fixture.dir.join("drm/card1-DP-1")).unwrap(); + fs::write(fixture.dir.join("drm/card1-DP-1/status"), "connected").unwrap(); + } else { + fs::remove_file(fixture.dir.join("drm/card0-DP-1/status")).unwrap(); + } + let before = fixture.boot(); + assert!(!fixture.run(false).status.success()); + assert_eq!(fixture.boot(), before); + assert!(!fixture.firmware().exists()); + } +} + +#[test] +fn uninstall_works_after_the_monitor_is_unplugged() { + let fixture = ScriptFixture::new(); + success(&fixture.run(false)); + fs::remove_file(fixture.dir.join("drm/card0-DP-1/status")).unwrap(); + success(&fixture.run(true)); + assert!(!fixture.firmware().exists()); +} + +#[test] +fn legacy_firmware_migration_preserves_dynamic_config_and_other_monitors() { + let fixture = ScriptFixture::new(); + let user = format!( + "FILES=(\"{}\" /keep/other.bin)\nHOOKS=(base udev)\nCOMPRESSION=\"${{USER_COMPRESSION:-zstd}}\"\n", + fixture.firmware().display() + ); + fs::write(fixture.dir.join("mkinitcpio.conf"), user).unwrap(); + success(&fixture.run(false)); + let config = fs::read_to_string(fixture.dir.join("mkinitcpio.conf")).unwrap(); + assert!(config.contains("/keep/other.bin")); + assert!(config.contains("HOOKS=(base udev)")); + assert!(config.contains("${USER_COMPRESSION:-zstd}")); + assert!(!config.contains(&fixture.firmware().display().to_string())); +} + +#[test] +fn support_report_detects_explicit_preset_configs_without_executing_them() { + let fixture = ScriptFixture::new(); + let presets = fixture.dir.join("presets"); + fs::create_dir_all(&presets).unwrap(); + let marker = fixture.dir.join("must-not-execute"); + for assignment in [ + "ALL_config='/etc/mkinitcpio.conf'".to_string(), + "export default_config=\"/custom.conf\"".to_string(), + format!( + "ALL_config=$(touch {})", + shell_quote(&marker.display().to_string()) + ), + ] { + fs::write(presets.join("linux.preset"), assignment).unwrap(); + let report = inspect_system_support_with_paths( + &fixture.dir.join("mkinitcpio.conf"), + &presets, + &fixture.dir.join("limine.conf"), + true, + true, + false, + ); + assert!(!report.is_supported()); + assert!( + report + .report_text() + .contains("explicit mkinitcpio config disables") + ); + assert!(!marker.exists()); + // The Limine backend does not build through these presets. + let report = inspect_system_support_with_paths( + &fixture.dir.join("mkinitcpio.conf"), + &presets, + &fixture.dir.join("limine.conf"), + true, + true, + true, + ); + assert!(report.is_supported()); + } +} + +#[test] +fn installed_override_status_finds_dropin_without_a_legacy_reference() { + let fixture = ScriptFixture::new(); + let output = fixture.run(false); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let status = inspect_override_with_paths( + "DP-1", + "drmcru_custom_DP-1.bin", + &sample_plan().kernel_parameter, + OverrideInspectionPaths { + firmware_target: &fixture.firmware(), + mkinitcpio_conf: &fixture.dir.join("mkinitcpio.conf"), + mkinitcpio_dropin: &fixture.mkinitcpio_dropin(), + bootloader_conf: &fixture.dir.join("limine.conf"), + limine_entry_tool_dropin: &fixture.dir.join("entry-tool/drmcru-edid.conf"), + active_cmdline: &fixture.dir.join("no-active-cmdline"), + }, + ); + assert!(status.mkinitcpio_references_firmware); + assert_eq!(status.short_label(), "installed, reboot pending"); + assert!(status.read_warnings.is_empty()); +} + +#[test] +fn system_support_rejects_preset_only_setups() { + let dir = unique_test_dir(); + let mkinit_dir = dir.join("mkinitcpio.d"); + fs::create_dir_all(&mkinit_dir).unwrap(); + let mkinit = dir.join("mkinitcpio.conf"); + let limine = dir.join("limine.conf"); + fs::write(&mkinit, "FILES=()\n").unwrap(); + fs::write(mkinit_dir.join("linux.preset"), "preset\n").unwrap(); + fs::write(&limine, "cmdline: quiet\n").unwrap(); + + let report = + inspect_system_support_with_paths(&mkinit, &mkinit_dir, &limine, true, true, false); + + assert!(!report.is_supported()); + assert!( + report + .blocking_issues() + .iter() + .any(|issue| issue.contains("preset-only")) + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn system_support_accepts_limine_mkinitcpio_without_presets() { + let dir = unique_test_dir(); + let mkinit_dir = dir.join("mkinitcpio.d"); + fs::create_dir_all(&mkinit_dir).unwrap(); + let mkinit = dir.join("mkinitcpio.conf"); + let limine = dir.join("limine.conf"); + fs::write(&mkinit, "FILES=()\n").unwrap(); + fs::write(&limine, "cmdline: quiet\n").unwrap(); + + let report = inspect_system_support_with_paths(&mkinit, &mkinit_dir, &limine, true, true, true); + + assert!(report.is_supported()); + assert!(report.blocking_issues().is_empty()); + assert_eq!( + report.rebuild_backend_label(), + "verified per-kernel mkinitcpio builds" + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn system_support_defers_protected_limine_config_to_privileged_installer() { + let limine = Path::new("/boot/limine.conf"); + + let mut warnings = Vec::new(); + let result = inspect_limine_config_read( + Err(io::Error::from(io::ErrorKind::PermissionDenied)), + limine, + &mut warnings, + ); + assert_eq!(result, (true, false, true)); + assert!(warnings.is_empty()); + + let report = SystemSupportReport { + pkexec_available: true, + mkinitcpio_available: true, + mkinitcpio_conf_present: true, + mkinitcpio_presets_present: false, + limine_mkinitcpio_available: true, + limine_conf_present: result.0, + limine_has_cmdline: result.1, + limine_validation_deferred: result.2, + read_warnings: warnings, + }; + assert!(report.is_supported()); + assert!( + report + .summary_lines() + .iter() + .any(|line| line.contains("will verify after authentication")) + ); +} + +#[test] +fn system_support_blocks_missing_limine_cmdline() { + let dir = unique_test_dir(); + let mkinit_dir = dir.join("mkinitcpio.d"); + fs::create_dir_all(&mkinit_dir).unwrap(); + let mkinit = dir.join("mkinitcpio.conf"); + let limine = dir.join("limine.conf"); + fs::write(&mkinit, "FILES=()\n").unwrap(); + fs::write(mkinit_dir.join("linux.preset"), "preset\n").unwrap(); + fs::write(&limine, "timeout: 3\n").unwrap(); + + let report = + inspect_system_support_with_paths(&mkinit, &mkinit_dir, &limine, true, true, false); + + assert!(!report.is_supported()); + assert!( + report + .blocking_issues() + .iter() + .any(|issue| issue.contains("no cmdline")) + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn validation_rejects_firmware_names_with_path_separators() { + assert!(matches!( + validate_firmware_file_name("../escape.bin"), + Err(InstallError::UnsafeFirmwareName(_)) + )); +} + +#[test] +fn mapping_detection_handles_consolidated_kernel_parameter() { + let dp1 = "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin"; + let cmdline = "quiet drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin,eDP-1:edid/drmcru_custom_eDP-1.bin splash"; + + assert!(text_contains_kernel_mapping(cmdline, dp1)); + assert!(text_contains_kernel_mapping( + cmdline, + "drm.edid_firmware=eDP-1:edid/drmcru_custom_eDP-1.bin" + )); + assert!(!text_contains_kernel_mapping( + cmdline, + "drm.edid_firmware=DP-2:edid/drmcru_custom_DP-2.bin" + )); +} + +#[test] +fn generated_privileged_scripts_are_bash_parseable() { + assert_bash_n(&build_install_script(&sample_plan())); + assert_bash_n(&build_uninstall_script(&sample_uninstall_plan())); +} + +fn assert_bash_n(script: &str) { + let dir = unique_test_dir(); + fs::create_dir_all(&dir).unwrap(); + let script_path = dir.join("script.sh"); + fs::write(&script_path, script).unwrap(); + + let output = std::process::Command::new("bash") + .arg("-n") + .arg(&script_path) + .output() + .unwrap(); + + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn uninstall_preview_has_all_targets() { + let preview = UninstallPreview::from_plan(&sample_uninstall_plan()); + let lines = preview.summary_lines(); + assert_eq!(lines.len(), 10); + assert!(lines[0].contains("DP-1")); + assert!(lines[1].contains("Remove")); + assert!(lines[2].contains("mkinitcpio")); + assert!(lines[3].contains("legacy")); + assert!(lines[4].contains("limine")); + assert!(lines[5].contains("limine-entry-tool")); + assert!(lines[6].contains("/etc/default/limine")); + assert!(lines[7].contains("drm.edid_firmware")); + assert!(lines[8].contains("verify")); +} + +#[test] +fn installed_override_status_detects_active_install() { + let dir = unique_test_dir(); + fs::create_dir_all(&dir).unwrap(); + + let firmware = dir.join("drmcru_custom_DP-1.bin"); + let mkinit = dir.join("mkinitcpio.conf"); + let limine = dir.join("limine.conf"); + let limine_dropin = dir.join("drmcru-edid.conf"); + let cmdline = dir.join("cmdline"); + let param = "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin"; + fs::write(&firmware, b"edid").unwrap(); + fs::write(&mkinit, format!("FILES=({})\n", firmware.display())).unwrap(); + fs::write(&limine, format!("cmdline: quiet {param}\n")).unwrap(); + fs::write( + &limine_dropin, + format!("KERNEL_CMDLINE[default]+=\" {param}\"\n"), + ) + .unwrap(); + fs::write(&cmdline, format!("root=/dev/sda1 {param}\n")).unwrap(); + + let status = inspect_override_with_paths( + "DP-1", + "drmcru_custom_DP-1.bin", + param, + OverrideInspectionPaths { + firmware_target: &firmware, + mkinitcpio_conf: &mkinit, + mkinitcpio_dropin: &dir.join("20-drmcru.conf"), + bootloader_conf: &limine, + limine_entry_tool_dropin: &limine_dropin, + active_cmdline: &cmdline, + }, + ); + + assert!(status.firmware_present); + assert!(status.mkinitcpio_references_firmware); + assert!(status.bootloader_references_kernel_parameter); + assert!(status.limine_entry_tool_references_kernel_parameter); + assert_eq!(status.bootloader_cmdline_entries, 1); + assert_eq!(status.bootloader_cmdline_entries_with_kernel_parameter, 1); + assert!(status.active_kernel_references_kernel_parameter); + assert_eq!(status.short_label(), "active"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn installed_override_status_detects_missing_override() { + let dir = unique_test_dir(); + fs::create_dir_all(&dir).unwrap(); + + let firmware = dir.join("drmcru_custom_DP-1.bin"); + let mkinit = dir.join("mkinitcpio.conf"); + let limine = dir.join("limine.conf"); + let limine_dropin = dir.join("drmcru-edid.conf"); + let cmdline = dir.join("cmdline"); + let param = "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin"; + fs::write(&mkinit, "FILES=()\n").unwrap(); + fs::write(&limine, "cmdline: quiet\n").unwrap(); + fs::write(&cmdline, "root=/dev/sda1\n").unwrap(); + + let status = inspect_override_with_paths( + "DP-1", + "drmcru_custom_DP-1.bin", + param, + OverrideInspectionPaths { + firmware_target: &firmware, + mkinitcpio_conf: &mkinit, + mkinitcpio_dropin: &dir.join("20-drmcru.conf"), + bootloader_conf: &limine, + limine_entry_tool_dropin: &limine_dropin, + active_cmdline: &cmdline, + }, + ); + + assert!(!status.has_any_override()); + assert_eq!(status.short_label(), "not installed"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn installed_override_status_detects_partial_limine_cmdline_install() { + let dir = unique_test_dir(); + fs::create_dir_all(&dir).unwrap(); + + let firmware = dir.join("drmcru_custom_DP-1.bin"); + let mkinit = dir.join("mkinitcpio.conf"); + let limine = dir.join("limine.conf"); + let limine_dropin = dir.join("drmcru-edid.conf"); + let cmdline = dir.join("cmdline"); + let param = "drm.edid_firmware=DP-1:edid/drmcru_custom_DP-1.bin"; + fs::write(&firmware, b"edid").unwrap(); + fs::write(&mkinit, format!("FILES=({})\n", firmware.display())).unwrap(); + fs::write(&limine, format!("cmdline: quiet\ncmdline: quiet {param}\n")).unwrap(); + fs::write(&cmdline, "root=/dev/sda1\n").unwrap(); + + let status = inspect_override_with_paths( + "DP-1", + "drmcru_custom_DP-1.bin", + param, + OverrideInspectionPaths { + firmware_target: &firmware, + mkinitcpio_conf: &mkinit, + mkinitcpio_dropin: &dir.join("20-drmcru.conf"), + bootloader_conf: &limine, + limine_entry_tool_dropin: &limine_dropin, + active_cmdline: &cmdline, + }, + ); + + assert!(status.bootloader_references_kernel_parameter); + assert_eq!(status.bootloader_cmdline_entries, 2); + assert_eq!(status.bootloader_cmdline_entries_with_kernel_parameter, 1); + assert!(!status.is_configured_for_next_boot()); + assert_eq!(status.short_label(), "partial install"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn firmware_comparison_detects_matching_live_edid() { + let dir = unique_test_dir(); + fs::create_dir_all(&dir).unwrap(); + let firmware = dir.join("drmcru_custom_DP-1.bin"); + fs::write(&firmware, b"edid-bytes").unwrap(); + + let comparison = compare_firmware_to_live_edid(&firmware, Some(b"edid-bytes")); + + assert_eq!(comparison, FirmwareEdidComparison::Matches { bytes: 10 }); + assert_eq!(comparison.short_label(), "matches"); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn firmware_comparison_detects_different_live_edid() { + let dir = unique_test_dir(); + fs::create_dir_all(&dir).unwrap(); + let firmware = dir.join("drmcru_custom_DP-1.bin"); + fs::write(&firmware, b"firmware").unwrap(); + + let comparison = compare_firmware_to_live_edid(&firmware, Some(b"live")); + + assert_eq!( + comparison, + FirmwareEdidComparison::Differs { + firmware_bytes: 8, + live_bytes: 4, + } + ); + assert!(comparison.detail().contains("differs")); + + let _ = fs::remove_dir_all(&dir); +} + +#[test] +fn preview_summary_has_all_targets() { + let preview = InstallPreview::from_plan(&sample_plan()); + let lines = preview.summary_lines(); + assert_eq!(lines.len(), 10); + assert!(lines[0].contains("DP-1")); + assert!(lines[1].contains("firmware")); + assert!(lines[2].contains("mkinitcpio")); + assert!(lines[3].contains("legacy")); + assert!(lines[4].contains("limine")); + assert!(lines[5].contains("limine-entry-tool")); + assert!(lines[6].contains("/etc/default/limine")); + assert!(lines[7].contains("drm.edid_firmware")); + assert!(lines[8].contains("verify")); +} diff --git a/src/kernel_cmdline.awk b/src/kernel_cmdline.awk new file mode 100644 index 0000000..a7481f0 --- /dev/null +++ b/src/kernel_cmdline.awk @@ -0,0 +1,66 @@ +# Tokenize without eval. Keep quoting/escaping in non-EDID arguments intact. +function mapping(value, inherited, colon,key) { + if (value == "") return + colon = index(value, ":") + key = colon ? substr(value, 1, colon - 1) : "" + n_removed = split(suppressed, removed, ",") + for (r = 1; r <= n_removed; r++) + if (removed[r] == value && !(operation == "add" && key == connector)) return + if (inherited && operation == "remove" && key == connector) return + if (operation == "remove" && key == connector && substr(value, colon + 1) == firmware) return + if (!(key in present)) { order[++count] = key; present[key] = 1 } + values[key] = value +} +function token(raw, inherited, normalized,value,n,parts,i,key,seen) { + normalized = raw + if (normalized ~ /^".*"$/ || normalized ~ /^\047.*\047$/) + normalized = substr(normalized, 2, length(normalized) - 2) + if (index(normalized, "drm.edid_firmware=") == 1) { + value = substr(normalized, 19) + if (value ~ /^".*"$/ || value ~ /^\047.*\047$/) + value = substr(value, 2, length(value) - 2) + n = split(value, parts, ",") + # Linux uses the first matching connector within one comma list. + for (i = 1; i <= n; i++) { + key = parts[i]; sub(/:.*/, "", key) + if (index(parts[i], ":") == 0) key = "" + if (key == "" || !(key in seen)) mapping(parts[i], inherited) + seen[key] = 1 + } + } else if (!inherited) { + others = others (others == "" ? "" : " ") raw + } +} +{ + word = ""; quote = ""; escaped = 0 + for (i = 1; i <= length($0); i++) { + c = substr($0, i, 1) + if (!escaped && quote == "" && c ~ /[[:space:]]/) { + if (word != "") token(word, NR > 1) + word = "" + continue + } + word = word c + if (escaped) escaped = 0 + else if (c == "\\" && quote != "\047") escaped = 1 + else if (quote != "" && c == quote) quote = "" + else if (quote == "" && (c == "\047" || c == "\"")) quote = c + } + if (quote != "" || escaped) { print "[ERR] Unclosed kernel command-line quoting" > "/dev/stderr"; failed = 1; exit 1 } + if (word != "") token(word, NR > 1) +} +END { + if (failed) exit 1 + if (operation == "add") mapping(connector ":" firmware, 0) + combined = "" + for (j = 1; j <= count; j++) { + value = values[order[j]] + if (operation == "mappings") print value + combined = combined (combined == "" ? "" : ",") value + } + if (operation != "mappings") { + if (replace_others) others = retained_others + if (operation == "strip") print others + else print others (combined == "" ? "" : (others == "" ? "" : " ") "drm.edid_firmware=" combined) + } +} diff --git a/src/limine_entry.awk b/src/limine_entry.awk new file mode 100644 index 0000000..3b8936b --- /dev/null +++ b/src/limine_entry.awk @@ -0,0 +1,18 @@ +# Select an existing menu entry by its boot-relative kernel/UKI path. +function emit() { + if (selected && !done) { print heading; printf "%s", body; done = 1 } +} +/^# (BEGIN|END) drmcru recovery$/ { next } +/^[[:space:]]*\// { emit(); heading = $0; body = ""; selected = 0; next } +{ + body = body $0 "\n" + line = $0 + sub(/^[[:space:]]*/, "", line) + if (line ~ /^(path|kernel_path|module_path):/) { + sub(/^[^:]*:[[:space:]]*/, "", line) + sub(/#.*/, "", line) + sub(/[[:space:]]*$/, "", line) + if (line == "boot():/" wanted) selected = 1 + } +} +END { emit(); exit done ? 0 : 1 } diff --git a/src/models.rs b/src/models.rs index 6f5b9e5..1cf360b 100644 --- a/src/models.rs +++ b/src/models.rs @@ -261,6 +261,7 @@ pub struct TimingDescriptor { pub h_front_porch: u16, pub h_sync_width: u16, pub h_back_porch: u16, + /// Vertical geometry is in full-frame lines, including for interlaced modes. pub v_active: u16, pub v_blanking: u16, pub v_front_porch: u16, @@ -272,6 +273,31 @@ pub struct TimingDescriptor { } impl TimingDescriptor { + /// Convert full-frame geometry to the per-field values stored in EDID DTDs. + pub fn edid_vertical_fields(&self) -> Result<[u16; 5], &'static str> { + let values = [ + self.v_active, + self.v_blanking, + self.v_front_porch, + self.v_sync_width, + self.v_back_porch, + ]; + if !self.interlaced { + return Ok(values); + } + if !self.v_active.is_multiple_of(2) + || !self.v_front_porch.is_multiple_of(2) + || !self.v_sync_width.is_multiple_of(2) + || self.v_blanking % 2 != 1 + || self.v_back_porch % 2 != 1 + { + return Err( + "interlaced DTDs require even frame height, front porch and sync width, and odd blanking/back porch for the half-line", + ); + } + Ok(values.map(|value| value / 2)) + } + pub fn h_total(&self) -> u16 { self.h_active.saturating_add(self.h_blanking) } @@ -296,7 +322,8 @@ impl TimingDescriptor { return None; } - Some((f64::from(self.pixel_clock_khz) * 1000.0) / f64::from(h_total * v_total)) + let scan = if self.interlaced { 2.0 } else { 1.0 }; + Some((f64::from(self.pixel_clock_khz) * 1000.0 * scan) / f64::from(h_total * v_total)) } pub fn hyprland_mode(&self) -> String { diff --git a/src/timings.rs b/src/timings.rs index 02b4872..f78cf65 100644 --- a/src/timings.rs +++ b/src/timings.rs @@ -207,7 +207,7 @@ fn exact_timing(request: CvtRequest, current: Option<&TimingDescriptor>) -> Timi timing.pixel_clock_khz = exact_pixel_clock_khz( u32::from(timing.h_total()), u32::from(timing.v_total()), - request.refresh_hz, + request.refresh_hz / if timing.interlaced { 2.0 } else { 1.0 }, ); timing } diff --git a/src/tui/actions.rs b/src/tui/actions.rs index 872fea2..23aa61f 100644 --- a/src/tui/actions.rs +++ b/src/tui/actions.rs @@ -634,7 +634,7 @@ impl App { self.status = "No detailed timings to delete.".to_string(); return; } - for location in locations { + for location in locations.into_iter().rev() { if let Some(workspace) = self.selected_workspace_mut() { let _ = workspace.delete_dtd(location); } @@ -659,7 +659,7 @@ impl App { } let mut deleted = 0usize; - for location in locations { + for location in locations.into_iter().rev() { if let Some(workspace) = self.selected_workspace_mut() && workspace.delete_dtd(location).is_ok() { @@ -1463,6 +1463,15 @@ impl App { return; }; let monitor = monitor.clone(); + if let Err(error) = install::validate_connector_mapping( + &monitor.connector, + self.monitors + .iter() + .map(|monitor| monitor.connector.as_str()), + ) { + self.status = error; + return; + } let override_status = self.selected_override_status().cloned(); let operation = if override_status .as_ref() diff --git a/src/tui/mod.rs b/src/tui/mod.rs index c561fb4..ec9e14a 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -648,6 +648,25 @@ fn push_mode_source(map: &mut BTreeMap>, key: ModeKey, sour #[cfg(test)] mod tests { use super::*; + + #[test] + fn deleting_all_cta_dtds_handles_compacted_slot_indices() { + let mut app = App::new(crate::demo::monitors().unwrap()); + app.delete_all_extension_dtds(); + let workspace = app.selected_workspace().unwrap(); + assert!( + workspace + .cta_dtd_slots() + .unwrap() + .iter() + .all(|slot| slot.timing.is_none()) + ); + assert_eq!(workspace.dtds().unwrap().len(), 2); + assert!(workspace.validate().is_empty()); + let mut app = App::new(crate::demo::monitors().unwrap()); + app.delete_all_detailed(); + assert!(app.selected_workspace().unwrap().dtds().unwrap().is_empty()); + } use crate::edid::{DtdLocation, encode_detailed_timing, parse_edid}; use crate::models::ConnectorStatus; diff --git a/src/tui/state.rs b/src/tui/state.rs index 9f5a453..7f69290 100644 --- a/src/tui/state.rs +++ b/src/tui/state.rs @@ -616,6 +616,7 @@ impl DetailedResolutionEditor { EditorField::Interlaced => { self.preset = TimingPreset::Manual; self.interlaced = !self.interlaced; + self.update_rate_fields_from_pixel_clock(EditorField::Interlaced); } _ => return false, } @@ -730,8 +731,9 @@ impl DetailedResolutionEditor { return; } - let pixel_clock_khz = - (f64::from(h_total) * f64::from(v_total) * refresh_hz / 1000.0).round() as u32; + let pixel_clock_khz = (f64::from(h_total) * f64::from(v_total) * refresh_hz + / if self.interlaced { 2000.0 } else { 1000.0 }) + .round() as u32; self.pixel_clock.set(pixel_clock_khz.to_string()); self.h_rate.set(format!( "{:.3}", @@ -821,7 +823,8 @@ impl DetailedResolutionEditor { self.pixel_clock.set(pixel_clock_khz.to_string()); self.refresh_hint.set(format!( "{:.3}", - f64::from(pixel_clock_khz) * 1000.0 / (f64::from(h_total) * f64::from(v_total)) + f64::from(pixel_clock_khz) * if self.interlaced { 2000.0 } else { 1000.0 } + / (f64::from(h_total) * f64::from(v_total)) )); } @@ -845,7 +848,8 @@ impl DetailedResolutionEditor { if edited_field != EditorField::Refresh { self.refresh_hint.set(format!( "{:.3}", - f64::from(pixel_clock_khz) * 1000.0 / (f64::from(h_total) * f64::from(v_total)) + f64::from(pixel_clock_khz) * if self.interlaced { 2000.0 } else { 1000.0 } + / (f64::from(h_total) * f64::from(v_total)) )); } } @@ -1229,6 +1233,54 @@ fn next_char_boundary(value: &str, cursor: usize) -> Option { mod tests { use super::*; + #[test] + fn interlaced_editor_and_exact_preset_use_frame_height_and_field_rate() { + let timing = TimingDescriptor { + pixel_clock_khz: 74_250, + h_active: 1920, + h_blanking: 280, + h_front_porch: 88, + h_sync_width: 44, + h_back_porch: 148, + v_active: 1080, + v_blanking: 45, + v_front_porch: 4, + v_sync_width: 10, + v_back_porch: 31, + h_sync_positive: true, + v_sync_positive: true, + interlaced: true, + }; + let mut editor = DetailedResolutionEditor::from_timing(timing.clone(), EditorMode::Add); + assert_eq!(editor.input(EditorField::Height).buffer, "1080"); + assert_eq!(editor.input(EditorField::Refresh).buffer, "60.00"); + editor.set_pixel_clock_from_refresh(); + assert_eq!(editor.timing().unwrap(), timing); + editor.input_mut(EditorField::Refresh).set("50.00".into()); + editor.set_pixel_clock_from_refresh(); + assert_eq!(editor.timing().unwrap().pixel_clock_khz, 61_875); + editor.preset = TimingPreset::Exact; + assert!((editor.timing().unwrap().refresh_hz().unwrap() - 50.0).abs() < 0.001); + editor.toggle_field(EditorField::Interlaced); + assert_eq!( + editor + .input(EditorField::Refresh) + .buffer + .parse::() + .unwrap(), + 25.0 + ); + editor.toggle_field(EditorField::Interlaced); + assert_eq!( + editor + .input(EditorField::Refresh) + .buffer + .parse::() + .unwrap(), + 50.0 + ); + } + #[test] fn text_paths_preserve_commas_while_refresh_accepts_decimal_commas() { let mut input = TextInput::new("/tmp/display".to_string()); diff --git a/src/validation.rs b/src/validation.rs index 45edeb1..05f00d6 100644 --- a/src/validation.rs +++ b/src/validation.rs @@ -66,16 +66,22 @@ pub fn validate_timing(timing: &TimingDescriptor) -> Vec { validate_12_bit(&mut warnings, "horizontal active", timing.h_active); validate_12_bit(&mut warnings, "horizontal blanking", timing.h_blanking); - validate_12_bit(&mut warnings, "vertical active", timing.v_active); - validate_12_bit(&mut warnings, "vertical blanking", timing.v_blanking); + if let Ok([active, blanking, front, sync, _]) = timing.edid_vertical_fields() { + validate_12_bit(&mut warnings, "vertical active field", active); + validate_12_bit(&mut warnings, "vertical blanking field", blanking); + validate_6_bit(&mut warnings, "vertical front porch field", front); + validate_6_bit(&mut warnings, "vertical sync width field", sync); + } else { + warnings.push(TimingWarning::error( + timing.edid_vertical_fields().unwrap_err(), + )); + } validate_10_bit( &mut warnings, "horizontal front porch", timing.h_front_porch, ); validate_10_bit(&mut warnings, "horizontal sync width", timing.h_sync_width); - validate_6_bit(&mut warnings, "vertical front porch", timing.v_front_porch); - validate_6_bit(&mut warnings, "vertical sync width", timing.v_sync_width); let h_parts = u32::from(timing.h_front_porch) + u32::from(timing.h_sync_width) diff --git a/src/workspace.rs b/src/workspace.rs index 4ce6273..09ad34b 100644 --- a/src/workspace.rs +++ b/src/workspace.rs @@ -279,6 +279,11 @@ impl EdidWorkspace { pub fn validate(&self) -> Vec { let mut issues = Vec::new(); + issues.extend( + crate::edid::cta_layout_issues(&self.working.raw) + .into_iter() + .map(|message| ValidationIssue { message }), + ); let expected_len = (usize::from(self.working.extension_blocks) + 1) * 128; if self.working.raw.len() != expected_len { issues.push(ValidationIssue { diff --git a/tests/fixtures/limine-entry-tool.py b/tests/fixtures/limine-entry-tool.py new file mode 100644 index 0000000..b5345e8 --- /dev/null +++ b/tests/fixtures/limine-entry-tool.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Temporary-root test double for the supported Limine command interface.""" +import glob +import os +from pathlib import Path +import re +import shutil +import sys + +root = Path(os.environ['TEST_ROOT']) +machine = '0' * 32 +args = sys.argv[1:] + +def resolve(key): + values = {} + paths = [root / 'entry-base.conf', *map(Path, sorted(glob.glob(str(root / 'entry-tool/*.conf')))), root / 'default.conf'] + for path in paths: + if not path.is_file(): + continue + for line in path.read_text().splitlines(): + match = re.match(r'^\s*KERNEL_CMDLINE\[([^]]+)\]\s*(\+?=)\s*(.*)$', line) + if match: + name, operator, value = match.groups() + if value.startswith('"') and value.endswith('"'): + value = value[1:-1] + values[name] = (values.get(name, '') + ' ' + value) if operator == '+=' else value + if key in values: + return values[key].strip() + if 'fallback' in key and 'fallback' in values: + return values['fallback'].strip() + return values.get('default', (root / 'kernel-cmdline').read_text()).strip() + +if args[0] == '--get-cmdline': + if (root / 'fail-query').exists(): + raise SystemExit(42) + print(resolve(args[1])) + sys.exit(0) + +boot = root / 'boot' +if args[0] in ('--remove-kernel', '--remove-uki'): + name = args[1] + configuration = boot / 'limine.conf' + records = re.split(r'(?=^/)', configuration.read_text(), flags=re.M) + kept = [] + for record in records: + heading = record.splitlines()[0].lstrip('/+').strip() if record else '' + if args[0] == '--remove-kernel': + discard = heading in (name, name + '-fallback') and 'protocol: linux' in record + else: + discard = heading == name and 'protocol: efi' in record + if not discard: + kept.append(record) + configuration.write_text(''.join(kept)) + if args[0] == '--remove-kernel': + shutil.rmtree(boot / machine / name) + else: + (boot / 'EFI/Linux' / f'{machine}_{name}.efi').unlink() + sys.exit(0) +if args[0] == '--add-kernel': + name, kernel, image = args[1:4] + fallback = len(args) > 4 and args[4] == '-fallback' + key = name + ('-fallback' if fallback else '') + directory = boot / machine / name + directory.mkdir(parents=True, exist_ok=True) + shutil.copyfile(kernel, directory / 'vmlinuz') + target = directory / Path(image).name + shutil.copyfile(image, target) + lines = [f'/{key}', ' protocol: linux', f' path: boot():/{machine}/{name}/vmlinuz', + f' module_path: boot():/{target.relative_to(boot)}', f' cmdline: {resolve(key)}'] +elif args[0] == '--add-uki': + key, image = args[1:3] + target = boot / 'EFI/Linux' / f'{machine}_{key}.efi' + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(image, target) + lines = [f'/{key}', ' protocol: efi', f' path: boot():/{target.relative_to(boot)}', f' cmdline: {resolve(key)}'] +else: + raise SystemExit(f'Unexpected Limine command: {args}') + +configuration = boot / 'limine.conf' +kept = [] +discard = False +for line in configuration.read_text().splitlines(): + if line.startswith('/'): + discard = line.lstrip('/+').strip() == key + if not discard: + kept.append(line) +configuration.write_text('\n'.join(kept + lines) + '\n') +counter = root / 'install-count' +count = int(counter.read_text()) + 1 if counter.exists() else 1 +counter.write_text(str(count)) +if (root / 'fail-second-install').exists() and count == 2: + raise SystemExit(42) +if (root / 'fail-after-install').exists(): + raise SystemExit(42) diff --git a/tests/fixtures/mkinitcpio.sh b/tests/fixtures/mkinitcpio.sh new file mode 100644 index 0000000..801ffdd --- /dev/null +++ b/tests/fixtures/mkinitcpio.sh @@ -0,0 +1,40 @@ +#!/bin/bash +set -euo pipefail +version=""; output=""; cmdline="" +while [ "$#" -gt 0 ]; do + case "$1" in + --kernel) version="$2"; shift 2 ;; + --generate|--uki) output="$2"; shift 2 ;; + --cmdline) cmdline="$2"; shift 2 ;; + -S|--splash|--uefistub|--ukiconfig) shift 2 ;; + --no-cmdline|--no-ukify) shift ;; + *) echo "Unexpected mkinitcpio option: $1" >&2; exit 1 ;; + esac +done +[ ! -e "$TEST_ROOT/fail-build" ] || exit 42 +count=0 +[ ! -e "$TEST_ROOT/build-count" ] || count="$(cat "$TEST_ROOT/build-count")" +count=$((count+1)); printf '%s' "$count" > "$TEST_ROOT/build-count" +if [ -e "$TEST_ROOT/fail-second-build" ] && [ "$count" -eq 2 ]; then exit 42; fi +if [ -e "$TEST_ROOT/skip-build" ]; then exit 0; fi +payload="$(mktemp -d "$TEST_ROOT/payload.XXXXXX")" +trap 'rm -rf -- "$payload"' EXIT +FILES=() +source "$TEST_ROOT/mkinitcpio.conf" +shopt -s nullglob +for config in "$TEST_ROOT/mkinitcpio.conf.d/"*.conf; do source "$config"; done +for file in "${FILES[@]}"; do + if [[ "$file" == "$TEST_ROOT/firmware-root/"* ]]; then + relative="${file#"$TEST_ROOT/firmware-root/"}" + mkdir -p "$payload/usr/lib/firmware/${relative%/*}" + cp -- "$file" "$payload/usr/lib/firmware/$relative" + fi +done +[ -z "$cmdline" ] || cp -- "$cmdline" "$payload/.cmdline" +if [ -e "$TEST_ROOT/wrong-cmdline" ]; then printf 'root=wrong' > "$payload/.cmdline"; fi +printf '%s' "$version" > "$payload/.uname" +if [ -e "$TEST_ROOT/wrong-firmware" ]; then + find "$payload/usr/lib/firmware" -type f -exec sh -c 'printf stale > "$1"' sh {} \; +fi +tar -cf "$output" -C "$payload" . +if [ -e "$TEST_ROOT/bad-archive" ]; then printf 'invalid' > "$output"; fi From d28698a5baf8df83f63375266d9f6c954cd749fb Mon Sep 17 00:00:00 2001 From: Lorenzo Golluscio <149246609+ssupt@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:27:47 +0100 Subject: [PATCH 4/4] Prepare 0.1.6 and document verified Limine installation --- .github/ISSUE_TEMPLATE/bug_report.yml | 2 +- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 64 ++++++++++++++++++--------- packaging/aur/drmcru-bin/.SRCINFO | 11 ++--- packaging/aur/drmcru-bin/PKGBUILD | 7 +-- 6 files changed, 55 insertions(+), 33 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 6644ecb..937b46f 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -37,7 +37,7 @@ body: id: version attributes: label: drmcru version or commit - placeholder: "0.1.5 or commit hash" + placeholder: "0.1.6 or commit hash" validations: required: true - type: textarea diff --git a/Cargo.lock b/Cargo.lock index 9253825..37e25db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -179,7 +179,7 @@ dependencies = [ [[package]] name = "drmcru" -version = "0.1.5" +version = "0.1.6" dependencies = [ "anyhow", "crossterm", diff --git a/Cargo.toml b/Cargo.toml index bdf1259..190410c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "drmcru" -version = "0.1.5" +version = "0.1.6" edition = "2024" rust-version = "1.88" description = "Linux DRM/KMS custom resolution and EDID override utility" diff --git a/README.md b/README.md index a052d3c..db63ac1 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,8 @@ This release has been tested on: - Limine with `limine-mkinitcpio` Exported EDIDs can be installed manually on other setups. Automatic -Install/Update/Uninstall is currently limited to Limine systems that rebuild with -`limine-mkinitcpio` or mkinitcpio presets. +Install/Update/Uninstall requires Limine entry-tool with its `limine-mkinitcpio` +integration and a boot partition mounted at `/boot`. ## Install @@ -34,23 +34,24 @@ yay -S drmcru-bin ``` Download the portable x86-64 binary from the -[latest release](https://github.com/ssupt/drmcru/releases/tag/v0.1.5): +[latest release](https://github.com/ssupt/drmcru/releases/tag/v0.1.6): ```sh -curl -LO https://github.com/ssupt/drmcru/releases/download/v0.1.5/drmcru-0.1.5-x86_64-unknown-linux-musl -curl -LO https://github.com/ssupt/drmcru/releases/download/v0.1.5/SHA256SUMS +curl -LO https://github.com/ssupt/drmcru/releases/download/v0.1.6/drmcru-0.1.6-x86_64-unknown-linux-musl +curl -LO https://github.com/ssupt/drmcru/releases/download/v0.1.6/SHA256SUMS sha256sum -c --ignore-missing SHA256SUMS -chmod +x drmcru-0.1.5-x86_64-unknown-linux-musl -./drmcru-0.1.5-x86_64-unknown-linux-musl doctor -./drmcru-0.1.5-x86_64-unknown-linux-musl +chmod +x drmcru-0.1.6-x86_64-unknown-linux-musl +./drmcru-0.1.6-x86_64-unknown-linux-musl doctor +./drmcru-0.1.6-x86_64-unknown-linux-musl ``` The TUI and manual Export work on Linux systems that expose connectors through `/sys/class/drm`. Hyprland is optional, but `hyprctl` is required for live mode discovery, switching, and verification. -Automatic Install/Update/Uninstall currently requires `pkexec`, Limine, -mkinitcpio, and either `limine-mkinitcpio` or mkinitcpio presets. +Automatic Install/Update/Uninstall requires `pkexec`, Limine entry-tool, +`limine-mkinitcpio`, mkinitcpio, and binutils (`objcopy`). Custom preset-only +systems can use Export. Run `drmcru` as your normal desktop user, not with `sudo`. It requests only the privileged Apply/Uninstall step through `pkexec`; running the whole TUI as root @@ -143,35 +144,54 @@ On the supported Limine/mkinitcpio path, Install/Update modifies: - `/lib/firmware/edid/.bin` - `/etc/mkinitcpio.conf.d/20-drmcru.conf` - `/boot/limine.conf` -- `/etc/limine-entry-tool.d/drmcru-edid.conf` when `limine-mkinitcpio` is used - -It writes collision-resistant `.drmcru.*.bak` backups before editing config and -firmware files. Existing overrides for other connectors are retained in the same -kernel parameter. If an install or rebuild step fails, the script restores all -files changed by that run. +- `/etc/limine-entry-tool.d/drmcru-edid.conf` (managed mapping state) +- `/etc/default/limine` (a marked block of effective kernel command lines) +- `/boot/drmcru-recovery` (the previous boot entry's kernel and images) + +It backs up configuration, firmware and the entire boot partition before making +changes. Every installed kernel and configured or existing fallback image is +built in a private staging directory. Before updating boot entries, drmcru checks +the embedded firmware and UKI command lines. Failures restore the tracked +configuration, firmware and boot partition, including partially replaced images. +Configuration and firmware also have timestamped `.drmcru.*.bak` backups. + +Existing root, encryption and per-kernel arguments are preserved. Overrides from +other Limine files are consolidated into one EDID parameter per command line. +The managed block follows user settings in `/etc/default/limine` so later appends +cannot undo that consolidation. Update refreshes it after changes to the +underlying command-line sources; Uninstall removes it when no longer needed. +Connector mappings that would also match another connector are rejected. The mkinitcpio drop-in appends EDID paths with `FILES+=(...)`, preserving existing files and overrides for other monitors. Install/Update migrates this monitor's legacy entry from `/etc/mkinitcpio.conf` when present. Uninstall removes its entry and deletes the drmcru drop-in when no overrides remain. -Automatic Apply requires mkinitcpio to read its default configuration and -drop-ins. Presets with explicit `*_config` assignments disable drop-ins and are -rejected when using `mkinitcpio -P`. Custom Limine UKI options must also avoid -`-c`/`--config`. Export includes instructions for configuring those systems -manually. +Automatic Apply uses mkinitcpio's default configuration and drop-ins, building +each image directly rather than relying on the rebuild wrapper's exit status. +Custom UKI options that can override the verified output or command line are +rejected. Export includes instructions for configuring other systems manually. ## Recovery If a custom mode is unusable but the desktop remains accessible, switch back to a known-good mode, choose Uninstall in `drmcru`, and reboot. -If the graphical session is unusable, boot once without the +The Limine menu retains a **drmcru recovery (before last change)** entry with +copies of the previous kernel and images. Select it if the new override prevents +normal startup. It represents the state before the most recent successful Apply +or Uninstall, rather than a guaranteed known-good configuration. + +If the graphical session is unusable, you can also boot once without the `drm.edid_firmware=...` parameter using the Limine entry editor or another boot entry. Then run `drmcru`, choose Uninstall, and reboot. Changed configuration files have timestamped backups beside the originals, including the main `mkinitcpio.conf` when migrating a legacy installation. +If a failure reports incomplete recovery, keep the reported recovery directory +and repair the boot partition before rebooting. Automatic installation requires +space for staged images, a complete boot backup and the retained recovery entry. + ## First-run troubleshooting - Run `drmcru doctor` first and include its output when reporting a problem. It diff --git a/packaging/aur/drmcru-bin/.SRCINFO b/packaging/aur/drmcru-bin/.SRCINFO index b80bb35..e4c63b0 100644 --- a/packaging/aur/drmcru-bin/.SRCINFO +++ b/packaging/aur/drmcru-bin/.SRCINFO @@ -1,6 +1,6 @@ pkgbase = drmcru-bin pkgdesc = Linux DRM/KMS custom resolution and EDID override utility - pkgver = 0.1.5 + pkgver = 0.1.6 pkgrel = 1 url = https://github.com/ssupt/drmcru arch = x86_64 @@ -9,12 +9,13 @@ pkgbase = drmcru-bin optdepends = polkit: pkexec authentication for automatic Apply/Uninstall optdepends = mkinitcpio: initramfs integration for automatic Apply/Uninstall optdepends = limine: supported bootloader for automatic Apply/Uninstall - optdepends = limine-mkinitcpio: Limine entry regeneration on Omarchy-style systems - provides = drmcru=0.1.5 + optdepends = limine-mkinitcpio: supported Limine integration for automatic Apply/Uninstall + optdepends = binutils: inspect UKI command lines before automatic Apply/Uninstall + provides = drmcru=0.1.6 conflicts = drmcru options = !strip options = !debug - source_x86_64 = drmcru-0.1.5::https://github.com/ssupt/drmcru/releases/download/v0.1.5/drmcru-0.1.5-x86_64-unknown-linux-musl - sha256sums_x86_64 = 8975328c9f3da1d2e2f349dc893ea9f1261e6312e4d3d58e3de6078e8f7ab61f + source_x86_64 = drmcru-0.1.6::https://github.com/ssupt/drmcru/releases/download/v0.1.6/drmcru-0.1.6-x86_64-unknown-linux-musl + sha256sums_x86_64 = 29f9882ead6828e657b3b339eb5b14f148ddc88c659793e55e7a66f4b1145798 pkgname = drmcru-bin diff --git a/packaging/aur/drmcru-bin/PKGBUILD b/packaging/aur/drmcru-bin/PKGBUILD index a3e0ab5..2d76ab1 100644 --- a/packaging/aur/drmcru-bin/PKGBUILD +++ b/packaging/aur/drmcru-bin/PKGBUILD @@ -2,7 +2,7 @@ pkgname=drmcru-bin _pkgname=drmcru -pkgver=0.1.5 +pkgver=0.1.6 pkgrel=1 pkgdesc="Linux DRM/KMS custom resolution and EDID override utility" arch=('x86_64') @@ -15,11 +15,12 @@ optdepends=( 'polkit: pkexec authentication for automatic Apply/Uninstall' 'mkinitcpio: initramfs integration for automatic Apply/Uninstall' 'limine: supported bootloader for automatic Apply/Uninstall' - 'limine-mkinitcpio: Limine entry regeneration on Omarchy-style systems' + 'limine-mkinitcpio: supported Limine integration for automatic Apply/Uninstall' + 'binutils: inspect UKI command lines before automatic Apply/Uninstall' ) options=('!strip' '!debug') source_x86_64=("${_pkgname}-${pkgver}::${url}/releases/download/v${pkgver}/${_pkgname}-${pkgver}-x86_64-unknown-linux-musl") -sha256sums_x86_64=('8975328c9f3da1d2e2f349dc893ea9f1261e6312e4d3d58e3de6078e8f7ab61f') +sha256sums_x86_64=('29f9882ead6828e657b3b339eb5b14f148ddc88c659793e55e7a66f4b1145798') package() { install -Dm755 "${srcdir}/${_pkgname}-${pkgver}" "${pkgdir}/usr/bin/${_pkgname}"