← Back to Pull requests

mknod: replace nix::sys::stat with rustix #12321

Open
mattsu2020 opened this pull request with 73 lines diff across 5 files
View on GitHub
mattsu2020 mattsu2020 commented on May 16, 2026 11:29 UTC
Author

Replace nix::sys::stat in mknod with rustix::fs and remove the direct nix dependency.

Depends on https://github.com/bytecodealliance/rustix/pull/1625.

Additional FIFO tests are split into #16348.

Diff: 73 lines (+44 / -29) across 5 files Reviewer: oech3 Review duration: 290913m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.42) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.42 · 73 lines diff across 5 files
0.42
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.258
Real PR Conversation Timeline
29 items
github-actions[bot] github-actions[bot] commented on May 16, 2026 11:39 UTC
Bot

<!-- gnu-comment-bot -->
GNU testsuite comparison:

Congrats! The gnu test tests/shred/shred-remove is no longer failing!

oech3 oech3 commented on code on May 16, 2026 11:43 UTC
Code Review
src/uu/mknod/src/mknod.rs:1
@@ -27,19 +28,19 @@ mod options {
     pub const CONTEXT: &str = "context";
 }
 
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
 enum FileType {
     Block,
     Character,
     Fifo,
 }
 
 impl FileType {
-    fn as_sflag(&self) -> SFlag {
+    fn to_rustix(self) -> RustixFileType {

I don't like including crate name at here.

oech3 oech3 commented on code on May 16, 2026 11:44 UTC
Code Review
src/uu/mknod/src/mknod.rs:1
@@ -71,34 +72,56 @@ struct Config {
     context: Option<String>,
 }
 
+/// RAII guard to restore umask on drop, ensuring cleanup even on panic.
+struct UmaskGuard(Mode);
+
+impl UmaskGuard {
+    fn set(new_mask: Mode) -> Self {
+        let old_mask = umask(new_mask);
+        Self(old_mask)
+    }
+}
+
+impl Drop for UmaskGuard {
+    fn drop(&mut self) {
+        umask(self.0);
+    }
+}
+
+/// Create a special file using `mknod(2)`.
+///
+/// Uses `libc::mknod` directly since `rustix::fs::mknodat` is unavailable on
+/// Apple targets. Combines `file_type` (S_IF* bits) with `mode` (permission
+/// bits) into the raw `mode_t` argument expected by the syscall.
+fn do_mknod(path: &str, file_type: RustixFileType, mode: Mode, dev: u64) -> std::io::Result<()> {
+    let raw_mode = file_type.as_raw_mode() | mode.as_raw_mode();
+    let c_path = CString::new(path)?;
+    let result = unsafe { libc::mknod(c_path.as_ptr(), raw_mode as _, dev as _) };
+    if result == 0 {
+        Ok(())
+    } else {
+        Err(std::io::Error::last_os_error())
+    }
+}
+
 fn mknod(file_name: &str, config: Config) -> i32 {
-    // set umask to 0 and store previous umask
-    let have_prev_umask = if config.use_umask {
+    let _guard = if config.use_umask {
         None
     } else {
-        Some(nix_umask(Mode::empty()))
+        Some(UmaskGuard::set(Mode::empty()))
     };
 
-    let mknod_err = nix_mknod(
+    let mknod_err = do_mknod(
         file_name,
-        config.file_type.as_sflag(),
+        config.file_type.to_rustix(),
         config.mode,
-        config.dev as _,
+        config.dev,
     )
     .err();
     let errno = if mknod_err.is_some() { -1 } else { 0 };
 
-    // set umask back to original value
-    if let Some(prev_umask) = have_prev_umask {
-        nix_umask(prev_umask);
-    }
-
     if let Some(err) = mknod_err {
-        eprintln!(
-            "{}: {}",
-            uucore::execution_phrase(),
-            std::io::Error::from(err)
-        );
+        eprintln!("{}: {err}", uucore::execution_phrase());

Would you use let _ = writeln!(io::stderr(), *) to avoid SIGABRT with 2>/dev/full?

codspeed[bot] codspeed[bot] commented on May 16, 2026 11:45 UTC
Bot

<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

Merging this PR will not alter performance

<details>
<summary><b>1 warning, 1 note</b></summary>

:warning: 123 benchmarks are dominated by system calls

> System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

> Learn more about system calls

> See affected benchmarks

:information_source: 1 benchmark has no flamegraph

> The flamegraph wasn't generated: most of the time was spent in runtime internals, which would leave nothing useful to analyze.

> See affected benchmarks

</details>

✅ 405 untouched benchmarks
⏩ 70 skipped benchmarks[^skipped]

---

<sub>Comparing <code>mattsu2020:mknod_rustix</code> (85eb326) with <code>main</code> (630890c)[^unexpected-base]</sub>

<a href="https://app.codspeed.io/uutils/coreutils/branches/mattsu2020%3Amknod_rustix?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>

[^skipped]: 70 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
[^unexpected-base]: No successful run was found on <code>main</code> (108e87b) during the generation of this report, so 630890c was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

oech3 oech3 commented on code on May 16, 2026 11:45 UTC
Code Review
src/uu/mknod/Cargo.toml:1
@@ -24,7 +24,8 @@ doctest = false
 clap = { workspace = true }
 uucore = { workspace = true, features = ["mode", "fs"] }
 fluent = { workspace = true }
-nix = { workspace = true }
+rustix = { workspace = true, features = ["process", "fs"] }
+libc = { workspace = true }

We will introduce sort check of toml keys soon.

oech3 oech3 commented on May 16, 2026 11:54 UTC
Contributor

mkfifo is subset of mknod. So it should be able to remake existing mkfifo wrapper without unsafe by this one.

mattsu2020 mattsu2020 commented on code on May 16, 2026 12:00 UTC
Code Review
src/uu/mknod/src/mknod.rs:1
@@ -27,19 +28,19 @@ mod options {
     pub const CONTEXT: &str = "context";
 }
 
-#[derive(Clone, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
 enum FileType {
     Block,
     Character,
     Fifo,
 }
 
 impl FileType {
-    fn as_sflag(&self) -> SFlag {
+    fn to_rustix(self) -> RustixFileType {

fix it

mattsu2020 mattsu2020 commented on code on May 16, 2026 12:00 UTC
Code Review
src/uu/mknod/src/mknod.rs:1
@@ -71,34 +72,56 @@ struct Config {
     context: Option<String>,
 }
 
+/// RAII guard to restore umask on drop, ensuring cleanup even on panic.
+struct UmaskGuard(Mode);
+
+impl UmaskGuard {
+    fn set(new_mask: Mode) -> Self {
+        let old_mask = umask(new_mask);
+        Self(old_mask)
+    }
+}
+
+impl Drop for UmaskGuard {
+    fn drop(&mut self) {
+        umask(self.0);
+    }
+}
+
+/// Create a special file using `mknod(2)`.
+///
+/// Uses `libc::mknod` directly since `rustix::fs::mknodat` is unavailable on
+/// Apple targets. Combines `file_type` (S_IF* bits) with `mode` (permission
+/// bits) into the raw `mode_t` argument expected by the syscall.
+fn do_mknod(path: &str, file_type: RustixFileType, mode: Mode, dev: u64) -> std::io::Result<()> {
+    let raw_mode = file_type.as_raw_mode() | mode.as_raw_mode();
+    let c_path = CString::new(path)?;
+    let result = unsafe { libc::mknod(c_path.as_ptr(), raw_mode as _, dev as _) };
+    if result == 0 {
+        Ok(())
+    } else {
+        Err(std::io::Error::last_os_error())
+    }
+}
+
 fn mknod(file_name: &str, config: Config) -> i32 {
-    // set umask to 0 and store previous umask
-    let have_prev_umask = if config.use_umask {
+    let _guard = if config.use_umask {
         None
     } else {
-        Some(nix_umask(Mode::empty()))
+        Some(UmaskGuard::set(Mode::empty()))
     };
 
-    let mknod_err = nix_mknod(
+    let mknod_err = do_mknod(
         file_name,
-        config.file_type.as_sflag(),
+        config.file_type.to_rustix(),
         config.mode,
-        config.dev as _,
+        config.dev,
     )
     .err();
     let errno = if mknod_err.is_some() { -1 } else { 0 };
 
-    // set umask back to original value
-    if let Some(prev_umask) = have_prev_umask {
-        nix_umask(prev_umask);
-    }
-
     if let Some(err) = mknod_err {
-        eprintln!(
-            "{}: {}",
-            uucore::execution_phrase(),
-            std::io::Error::from(err)
-        );
+        eprintln!("{}: {err}", uucore::execution_phrase());

fix it

mattsu2020 mattsu2020 commented on May 16, 2026 12:01 UTC
Author

mkfifo is subset of mknod. So it should be able to remake existing mkfifo wrapper without unsafe by this one.

Thanks for the suggestion! You're right
mkfifo is essentially mknod with S_IFIFO and dev=0, so the do_mknod helper could be reused there to eliminate the nix dependency and unsafe as well.

oech3 oech3 commented on May 16, 2026 12:17 UTC
Contributor

Is it able to open a PR on rustix to support rustix::fs::mk*at on macOS?
I have no access on macOS now...

mattsu2020 mattsu2020 commented on May 16, 2026 13:06 UTC
Author

Is it able to open a PR on rustix to support rustix::fs::mk*at on macOS? I have no access on macOS now...

I created the PR, but there are some errors on the Rustix side during CI, so I'll review the code again once the fixes are complete.
https://github.com/bytecodealliance/rustix/pull/1625

oech3 oech3 commented on May 16, 2026 13:10 UTC
Contributor

Thankyou

xtqqczze xtqqczze commented on Sep 28, 2026 16:32 UTC
Contributor
xtqqczze xtqqczze commented on Sep 28, 2026 16:37 UTC
Contributor

Compiles successfully on Redox:

cargo check -q -p uu_mknod --target x86_64-unknown-redox

xtqqczze xtqqczze commented on Sep 28, 2026 16:41 UTC
Contributor

@mattsu2020 Please convert to draft and test with Cargo patch for upstream (will need to cargo update rustix):

[patch.crates-io]
rustix = { git = "https://github.com/mattsu2020/rustix.git", branch = "mknodat_macos" }

mattsu2020 mattsu2020 commented on Sep 29, 2026 09:57 UTC
Author

https://github.com/uutils/coreutils/issues/14908
Due to the issue above, testing cannot be performed on Windows.

xtqqczze xtqqczze commented on Oct 01, 2026 10:08 UTC
Contributor

@mattsu2020 https://github.com/uutils/coreutils/issues/14908 was resolved, please remove merge commits and rebase.

xtqqczze xtqqczze commented on Oct 01, 2026 11:06 UTC
Contributor

@mattsu2020 Please add Depends on https://github.com/bytecodealliance/rustix/pull/1625 to the PR description, and edit to include only important information.

oech3 oech3 commented on code on Nov 10, 2026 23:03 UTC
Code Review
src/uu/mknod/src/mknod.rs:1
@@ -3,11 +3,10 @@
 // For the full copyright and license information, please view the LICENSE
 // file that was distributed with this source code.
 
-// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror IFBLK IFCHR IFIFO sflag
+// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror mknodat
 
 use clap::{Arg, ArgAction, Command, value_parser};
-use nix::libc::{S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR, mode_t};
-use nix::sys::stat::{Mode, SFlag, dev_t, mknod as nix_mknod};
+use rustix::fs::{CWD, Dev, FileType as RustixFileType, Mode, mknodat};

If we drop nix, as RustixFileType is innecessary.

oech3 oech3 commented on code on Nov 10, 2026 23:05 UTC
Code Review
tests/by-util/test_mknod.rs:1
@@ -86,6 +86,34 @@ fn test_mknod_fifo_mnemonic_usage() {
     assert!(ts.fixtures.is_fifo("test_file"));
 }
 
+#[test]
+fn test_mknod_fifo_umask() {

- Add tests for mknod permissions and umask handling.

Unrelated change. Please split PR.

mattsu2020 mattsu2020 commented on code on Nov 11, 2026 10:53 UTC
Code Review
src/uu/mknod/src/mknod.rs:1
@@ -3,11 +3,10 @@
 // For the full copyright and license information, please view the LICENSE
 // file that was distributed with this source code.
 
-// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror IFBLK IFCHR IFIFO sflag
+// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror mknodat
 
 use clap::{Arg, ArgAction, Command, value_parser};
-use nix::libc::{S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR, mode_t};
-use nix::sys::stat::{Mode, SFlag, dev_t, mknod as nix_mknod};
+use rustix::fs::{CWD, Dev, FileType as RustixFileType, Mode, mknodat};

thanks.
The code is much cleaner now.

mattsu2020 mattsu2020 commented on code on Nov 11, 2026 11:01 UTC
Code Review
tests/by-util/test_mknod.rs:1
@@ -86,6 +86,34 @@ fn test_mknod_fifo_mnemonic_usage() {
     assert!(ts.fixtures.is_fifo("test_file"));
 }
 
+#[test]
+fn test_mknod_fifo_umask() {

I moved it to a separate PR.

xtqqczze xtqqczze commented on code on Nov 11, 2026 17:08 UTC
Code Review
src/uu/mknod/src/mknod.rs:1
@@ -3,11 +3,10 @@
 // For the full copyright and license information, please view the LICENSE
 // file that was distributed with this source code.
 
-// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror IFBLK IFCHR IFIFO sflag
+// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror mknodat
 
 use clap::{Arg, ArgAction, Command, value_parser};
-use nix::libc::{S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR, mode_t};
-use nix::sys::stat::{Mode, SFlag, dev_t, mknod as nix_mknod};
+use rustix::fs::{CWD, Dev, FileType as RustixFileType, Mode, mknodat};

rustix::fs::FileType has additional variants that we don't currently handle. This change could expose us to unexpected behavior when encountering those variants through the public API.

mattsu2020 mattsu2020 commented on code on Nov 11, 2026 22:31 UTC
Code Review
src/uu/mknod/src/mknod.rs:1
@@ -3,11 +3,10 @@
 // For the full copyright and license information, please view the LICENSE
 // file that was distributed with this source code.
 
-// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror IFBLK IFCHR IFIFO sflag
+// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror mknodat
 
 use clap::{Arg, ArgAction, Command, value_parser};
-use nix::libc::{S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR, mode_t};
-use nix::sys::stat::{Mode, SFlag, dev_t, mknod as nix_mknod};
+use rustix::fs::{CWD, Dev, FileType as RustixFileType, Mode, mknodat};

I see, so we need to set some restrictions.
I've added restrictions at the entry point.

xtqqczze xtqqczze commented on code on Nov 12, 2026 02:49 UTC
Code Review
src/uu/mknod/src/mknod.rs:1
@@ -3,11 +3,10 @@
 // For the full copyright and license information, please view the LICENSE
 // file that was distributed with this source code.
 
-// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror IFBLK IFCHR IFIFO sflag
+// spell-checker:ignore (ToDO) parsemode makedev sysmacros perror mknodat
 
 use clap::{Arg, ArgAction, Command, value_parser};
-use nix::libc::{S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR, mode_t};
-use nix::sys::stat::{Mode, SFlag, dev_t, mknod as nix_mknod};
+use rustix::fs::{CWD, Dev, FileType as RustixFileType, Mode, mknodat};

mknod isn't the entry point, so the change is still not correct.

sylvestre sylvestre commented on Nov 12, 2026 06:36 UTC
Contributor

thanks for working on this!
This can't land while it depends on a rustix git rev. Please keep it in draft until a rustix release ships the change and bump the version instead, which should also fix the red CI.
Please also rebase without the merge commit and squash everything into one commit.

oech3 oech3 commented on Nov 12, 2026 07:53 UTC
Contributor

Can we use cargo vendor? But it might difficult to audit copied src.

xtqqczze xtqqczze commented on Nov 12, 2026 09:47 UTC
Contributor

This can't land while it depends on a rustix git rev.

We should ensure git sources fail CI: https://github.com/uutils/coreutils/pull/16366.

Reviewers
Assignees
mattsu2020 mattsu2020
Labels
risk: low confidence: 88.6% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 41.6% (MEDIUM) · Higher = larger blast radius
41.6%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 88.6% · Lower = rushed or shallow review
88.6%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 4.7% · Safe to merge
4.7%