◐ Shell
reader mode source ↗
Skip to content

Attempt to automate posix consts#6117

Merged
youknowone merged 6 commits into
RustPython:mainfrom
ShaharNaveh:automate-posix-consts
Sep 3, 2025
Merged

Attempt to automate posix consts#6117
youknowone merged 6 commits into
RustPython:mainfrom
ShaharNaveh:automate-posix-consts

Conversation

@ShaharNaveh

@ShaharNaveh ShaharNaveh commented Aug 31, 2025

Copy link
Copy Markdown
Contributor

Attempt to automate the definition of posix consts. I'm sure that this will require the script to be more adjustable but IMO this is a good first step in automating something that we do manually. for example: #5795

I ain't so sure how we decide what goes into os directly and what into posix, if someone can share some knowledge it would be very appreciated:)

Summary by CodeRabbit

  • New Features
    • Greatly expands POSIX constants exposed to Python across platforms: spawn actions, process/wait codes, dynamic linker flags, file flags (incl. O_DIRECT, O_PATH, O_TMPFILE, O_NOATIME), advisory flags, timer/event/memfd descriptors, extended attributes, clone flags, seek constants, P_PIDFD, and more.
  • Removals
    • Removes several scheduler constants (SCHED_*) and one macOS-only constant; many constants are now OS-gated.
  • Chores
    • Adds a new tool to generate platform-specific constant bindings from upstream libc test data.

@coderabbitai

coderabbitai Bot commented Aug 31, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a new codegen script (scripts/libc_posix.py) that fetches and groups libc constants per OS and emits cfg-gated import blocks. Reworks vm/src/stdlib/posix.rs to reorganize OS-gated libc imports, exposing many new constants and removing several scheduling-related ones.

Changes

Cohort / File(s) Summary
Generator script (libc constants aggregation)
scripts/libc_posix.py
New script to fetch per-OS libc-test constants, detect/rename/filter items, group by OS sets (EXCLUDE/EXTRAS/RENAMES), and print cfg-gated use libc::{...} + #[pyattr] blocks. Adds helpers: build_url, get_consts, format_groups, main; constants: CONSTS_PAT, OS_CONSTS_PAT, LIBC_VERSION, EXCLUDE, EXTRAS, RENAMES, TARGET_OS.
POSIX module OS-gated constants
vm/src/stdlib/posix.rs
Reorganized libc imports and #[pyattr] exports with expanded OS gating. Adds many constants (e.g., POSIX_SPAWN_*, CLD_*, W*, P_*, XATTR_*, GRND_*, numerous O_*, RTLD_*, CLONE_*, EFD_*, TFD_*, MFD_*, POSIX_FADV_*, SEEK_*), removes several SCHED_* and macOS _COPYFILE_DATA, and reshapes platform guards across blocks.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Developer
  participant Script as scripts/libc_posix.py
  participant Remote as libc-test (github.com/rust-lang/libc-test)
  participant Formatter as format_groups
  participant Output as Stdout

  Dev->>Script: run script (main)
  Script->>Remote: fetch wanted consts (OS docs) using OS_CONSTS_PAT
  Script->>Remote: fetch per-OS constant lists (LIBC_VERSION, TARGET_OS)
  Script->>Script: parse constants via CONSTS_PAT, apply EXCLUDE/RENAMES/EXTRAS
  Script->>Script: build const -> OS-set map
  Script->>Formatter: group by OS-set and format cfg-gated blocks
  Formatter-->>Output: emit `#[cfg(...)]` + `use libc::{...}` + `#[pyattr]`
  Output-->>Dev: printed code blocks for posix.rs consumption
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • youknowone

Poem

I thump my paws in tidy rows,
I fetch the flags where header wind blows,
I hop and group by platform, neat and spry,
Emitting cfg-gates with a wink of my eye.
Hop-hop—constants bundled, ready to fly! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hide comment

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
vm/src/stdlib/posix.rs (4)

1646-1653: Won’t compile: libc::c_short::MAX does not exist; fix overflow check and cast

libc::c_short is an alias (i16); it has no MAX. Use i16::MAX and cast safely.

Apply this diff:

-            if flags > libc::c_short::MAX as i32 {
+            if flags > i16::MAX as i32 || flags < i16::MIN as i32 {
                 return Err(vm.new_value_error("Too many flags set for posix_spawn"));
             }
-            let ret =
-                unsafe { libc::posix_spawnattr_setflags(&mut attrp, flags as libc::c_short) };
+            let ret = unsafe {
+                libc::posix_spawnattr_setflags(&mut attrp, flags as libc::c_short)
+            };

1517-1567: Leak: posix_spawn_file_actions_init resources are never destroyed on error paths

If any add* call fails, we return without calling posix_spawn_file_actions_destroy, leaking resources.

Apply this diff inside the error branch:

-                    if ret != 0 {
-                        let err = std::io::Error::from_raw_os_error(ret);
-                        return Err(IOErrorBuilder::with_filename(&err, self.path, vm));
-                    }
+                    if ret != 0 {
+                        let err = std::io::Error::from_raw_os_error(ret);
+                        unsafe { libc::posix_spawn_file_actions_destroy(&mut file_actions) };
+                        return Err(IOErrorBuilder::with_filename(&err, self.path, vm));
+                    }

1570-1656: Leak: posix_spawnattr_init/file_actions not destroyed on all exit paths

Both posix_spawnattr_init and posix_spawn_file_actions_init require corresponding destroy calls. Add them for all paths after attrp is initialized, including intermediate failures.

Apply these diffs for the two intermediate error cases:

-                if ret != 0 {
-                    return Err(vm.new_os_error(format!("posix_spawnattr_setpgroup failed: {ret}")));
-                }
+                if ret != 0 {
+                    unsafe {
+                        libc::posix_spawn_file_actions_destroy(&mut file_actions);
+                        libc::posix_spawnattr_destroy(&mut attrp);
+                    }
+                    return Err(vm.new_os_error(format!("posix_spawnattr_setpgroup failed: {ret}")));
+                }
-                if ret != 0 {
-                    return Err(
-                        vm.new_os_error(format!("posix_spawnattr_setsigmask failed: {ret}"))
-                    );
-                }
+                if ret != 0 {
+                    unsafe {
+                        libc::posix_spawn_file_actions_destroy(&mut file_actions);
+                        libc::posix_spawnattr_destroy(&mut attrp);
+                    }
+                    return Err(
+                        vm.new_os_error(format!("posix_spawnattr_setsigmask failed: {ret}"))
+                    );
+                }

And ensure both are destroyed on the final return (success or error), see next comment.


1701-1706: Always destroy posix_spawn resources before returning

Ensure no leaks on success and error returns.

Apply this diff:

-            if ret == 0 {
-                Ok(pid)
-            } else {
-                let err = std::io::Error::from_raw_os_error(ret);
-                Err(IOErrorBuilder::with_filename(&err, self.path, vm))
-            }
+            if ret == 0 {
+                unsafe {
+                    libc::posix_spawn_file_actions_destroy(&mut file_actions);
+                    libc::posix_spawnattr_destroy(&mut attrp);
+                }
+                Ok(pid)
+            } else {
+                let err = std::io::Error::from_raw_os_error(ret);
+                unsafe {
+                    libc::posix_spawn_file_actions_destroy(&mut file_actions);
+                    libc::posix_spawnattr_destroy(&mut attrp);
+                }
+                Err(IOErrorBuilder::with_filename(&err, self.path, vm))
+            }
🧹 Nitpick comments (5)
scripts/libc_posix.py (4)

11-13: Tighten regex to avoid capturing functions like os.WIFEXITED(...)

Use a negative lookahead to skip tokens immediately followed by '(' to reduce reliance on EXCLUDE for function-like names.

Apply this diff:

-OS_CONSTS_PAT = re.compile(
-    r"\bos\.(_*[A-Z]+(?:_+[A-Z]+)*_*)"
-)  # TODO: Exclude matches if they have `(` after (those are functions)
+OS_CONSTS_PAT = re.compile(
+    r"\bos\.(_*[A-Z]+(?:_+[A-Z]+)*_*)(?!\s*\()"
+)  # Avoid function-like names: os.FOO(...)

68-73: Add timeouts and error handling to network fetches

urlopen without a timeout can hang CI; errors aren’t handled. Add a small timeout and surface helpful messages.

Apply this diff and the import below:

-def get_consts(url: str, pattern: re.Pattern = CONSTS_PAT) -> frozenset[str]:
-    with urllib.request.urlopen(url) as f:
-        resp = f.read().decode()
+def get_consts(url: str, pattern: re.Pattern = CONSTS_PAT) -> frozenset[str]:
+    try:
+        with urllib.request.urlopen(url, timeout=15) as f:
+            resp = f.read().decode()
+    except Exception as e:
+        raise RuntimeError(f"failed to fetch {url}: {e}") from e

Also add the import (either is fine; generic Exception above keeps it simple):

-import urllib.request
+import urllib.request
+import urllib.error

16-16: Avoid hard-coding libc version; derive or parameterize

Pinning LIBC_VERSION risks drift vs. Cargo.lock. Read it from env/CLI, falling back to the constant.

Apply this diff:

-LIBC_VERSION = "0.2.175"
+import os
+LIBC_VERSION = os.environ.get("LIBC_VERSION", "0.2.175")

If helpful, I can wire a tiny argparse to allow --libc-version too.


94-97: Target CPython source rather than rendered docs for stability

Scraping docs is brittle across versions. Prefer parsing CPython’s posixmodule.c (or a pinned commit of os.rst) so the generator aligns with the project’s targeted CPython version.

Do you want me to adjust the script to accept a CPython ref (tag/commit) and pull constants from posixmodule.c?

vm/src/stdlib/posix.rs (1)

1605-1616: Avoid hard-coding POSIX_SPAWN_SETSID magic number

If available, prefer libc::POSIX_SPAWN_SETSID to 0x0080. If not defined, gate a local const behind #[cfg(target_os = "linux")].

Apply this diff:

-                #[cfg(target_os = "linux")]
-                {
-                    flags |= 0x0080; // POSIX_SPAWN_SETSID value on Linux
-                }
+                #[cfg(target_os = "linux")]
+                {
+                    #[allow(non_upper_case_globals)]
+                    const POSIX_SPAWN_SETSID_LINUX: i32 = {
+                        #[cfg(any())] { libc::POSIX_SPAWN_SETSID } // force compile-time fallback
+                        #[cfg(not(any()))] { 0x0080 }
+                    };
+                    flags |= POSIX_SPAWN_SETSID_LINUX;
+                }

If libc::POSIX_SPAWN_SETSID exists on your minimum supported libc, you can simplify to that directly.

📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7509387 and f66367e.

📒 Files selected for processing (2)
  • scripts/libc_posix.py (1 hunks)
  • vm/src/stdlib/posix.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.py: Follow PEP 8 style for custom Python code
Use ruff for linting Python code

Files:

  • scripts/libc_posix.py
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Follow the default rustfmt code style (cargo fmt to format)
Always run clippy to lint code (cargo clippy) before completing tasks. Fix any warnings or lints that are introduced by your changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

Files:

  • vm/src/stdlib/posix.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run tests under miri
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
🔇 Additional comments (2)
vm/src/stdlib/posix.rs (2)

50-56: Nice: cleanly grouped android-only base constants

The android-gated set looks consistent and mirrors CPython exposure.


136-138: Verify SEEK_DATA/SEEK_HOLE availability on all targets
vm/src/stdlib/posix.rs:136–138
SEEK_DATA and SEEK_HOLE aren’t guaranteed in Android or DragonFly’s libc—run per-target cargo check (e.g. aarch64-linux-android, x86_64-unknown-dragonfly) to confirm these imports build, and add #[cfg] guards if any fail.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hide comment

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
vm/src/stdlib/posix.rs (3)

1519-1523: Don’t use asserts for posix_spawn initializers; return proper OSErrors

Asserts will abort instead of surfacing OSError to Python. Handle init failures explicitly.

Apply:

             let mut file_actions = unsafe {
                 let mut fa = std::mem::MaybeUninit::uninit();
-                assert!(libc::posix_spawn_file_actions_init(fa.as_mut_ptr()) == 0);
+                let r = libc::posix_spawn_file_actions_init(fa.as_mut_ptr());
+                if r != 0 {
+                    return Err(vm.new_os_error(format!("posix_spawn_file_actions_init failed: {r}")));
+                }
                 fa.assume_init()
             };
             let mut attrp = unsafe {
                 let mut sa = std::mem::MaybeUninit::uninit();
-                assert!(libc::posix_spawnattr_init(sa.as_mut_ptr()) == 0);
+                let r = libc::posix_spawnattr_init(sa.as_mut_ptr());
+                if r != 0 {
+                    // cleanup file_actions before returning
+                    libc::posix_spawn_file_actions_destroy(&mut file_actions);
+                    return Err(vm.new_os_error(format!("posix_spawnattr_init failed: {r}")));
+                }
                 sa.assume_init()
             };

Also applies to: 1572-1576


1565-1569: Leak fix: always destroy posix_spawn file_actions/attr on all exit paths

posix_spawn_file_actions_init/posix_spawnattr_init allocate resources that must be destroyed. Several early returns skip destruction.

Apply:

-                    if ret != 0 {
-                        let err = std::io::Error::from_raw_os_error(ret);
-                        return Err(IOErrorBuilder::with_filename(&err, self.path, vm));
-                    }
+                    if ret != 0 {
+                        let err = std::io::Error::from_raw_os_error(ret);
+                        unsafe { libc::posix_spawn_file_actions_destroy(&mut file_actions); }
+                        return Err(IOErrorBuilder::with_filename(&err, self.path, vm));
+                    }
-                if ret != 0 {
-                    return Err(vm.new_os_error(format!("posix_spawnattr_setflags failed: {ret}")));
-                }
+                if ret != 0 {
+                    unsafe {
+                        libc::posix_spawn_file_actions_destroy(&mut file_actions);
+                        libc::posix_spawnattr_destroy(&mut attrp);
+                    }
+                    return Err(vm.new_os_error(format!("posix_spawnattr_setflags failed: {ret}")));
+                }
-            if ret == 0 {
-                Ok(pid)
-            } else {
-                let err = std::io::Error::from_raw_os_error(ret);
-                Err(IOErrorBuilder::with_filename(&err, self.path, vm))
-            }
+            unsafe {
+                libc::posix_spawn_file_actions_destroy(&mut file_actions);
+                libc::posix_spawnattr_destroy(&mut attrp);
+            }
+            if ret == 0 {
+                Ok(pid)
+            } else {
+                let err = std::io::Error::from_raw_os_error(ret);
+                Err(IOErrorBuilder::with_filename(&err, self.path, vm))
+            }

Optional: wrap these in small RAII types with Drop to make this bulletproof and simplify control flow. I can draft that if you want.

Also applies to: 1653-1657, 1703-1709


1577-1591: Set POSIX_SPAWN_SETSIGDEF when setting the default signal set

Without the flag, the defaulted signal set may be ignored.

Apply:

                 assert!(
                     unsafe { libc::posix_spawnattr_setsigdefault(&mut attrp, set.as_ref()) } == 0
                 );
+                flags |= libc::POSIX_SPAWN_SETSIGDEF;
🧹 Nitpick comments (2)
vm/src/stdlib/posix.rs (2)

97-100: Verify NetBSD XATTR_*; likely Linux/macOS only

NetBSD generally uses extattr(2) namespaces rather than XATTR_* macros. This import may not exist and could break builds.

Proposed tightening (if confirmed):

-#[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd"))]
+#[cfg(any(target_os = "linux", target_os = "macos"))]
 #[pyattr]
 use libc::{XATTR_CREATE, XATTR_REPLACE};

128-137: Android gating for SEEK_DATA/SEEK_HOLE may be risky

SEEK_{DATA,HOLE} are not consistently available on Android bionic headers. Consider dropping Android from this block unless you’ve verified libc exposes them on your min API level.

📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f66367e and e9594c3.

📒 Files selected for processing (2)
  • scripts/libc_posix.py (1 hunks)
  • vm/src/stdlib/posix.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • scripts/libc_posix.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Follow the default rustfmt code style (cargo fmt to format)
Always run clippy to lint code (cargo clippy) before completing tasks. Fix any warnings or lints that are introduced by your changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

Files:

  • vm/src/stdlib/posix.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run tests under miri
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests (macos-latest)
🔇 Additional comments (2)
vm/src/stdlib/posix.rs (2)

101-109: Double-check GRND_ gating*

GRND_RANDOM/NONBLOCK are certainly on Linux/Android; availability on DragonFly/NetBSD is not universal and may not be exposed by libc.

Would you like me to check libc’s per-target bindings and BSD manpages for these flags and propose exact cfgs?


1607-1619: Use libc::POSIX_SPAWN_SETSID instead of magic number
Confirm that your libc crate version defines POSIX_SPAWN_SETSID (requires glibc ≥ 2.26 with _GNU_SOURCE); if it’s missing, bump libc or gate out/implement a fallback. (spinics.net)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hide comment

Actionable comments posted: 1

♻️ Duplicate comments (5)
vm/src/stdlib/posix.rs (5)

50-53: Fix FreeBSD import: drop Linux-only MFD_HUGE_MASK

MFD_HUGE_MASK isn’t defined on FreeBSD and will break that build. Keep only the SF_* flags here.

-#[cfg(target_os = "freebsd")]
-#[pyattr]
-use libc::{MFD_HUGE_MASK, SF_MNOWAIT, SF_NOCACHE, SF_NODISKIO, SF_SYNC};
+#[cfg(target_os = "freebsd")]
+#[pyattr]
+use libc::{SF_MNOWAIT, SF_NOCACHE, SF_NODISKIO, SF_SYNC};

87-93: Split memfd flags from POSIX_FADV_*; avoid FreeBSD/Android build breaks

MFD_* are Linux/Android-only. POSIX_FADV_* are also available on FreeBSD. Split the groups.

-#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))]
-#[pyattr]
-use libc::{
-    MFD_ALLOW_SEALING, MFD_CLOEXEC, MFD_HUGETLB, POSIX_FADV_DONTNEED, POSIX_FADV_NOREUSE,
-    POSIX_FADV_NORMAL, POSIX_FADV_RANDOM, POSIX_FADV_SEQUENTIAL, POSIX_FADV_WILLNEED,
-};
+// memfd_* flags: Linux/Android only
+#[cfg(any(target_os = "android", target_os = "linux"))]
+#[pyattr]
+use libc::{MFD_ALLOW_SEALING, MFD_CLOEXEC, MFD_HUGETLB};
+
+// posix_fadvise advice values (Android/FreeBSD/Linux)
+#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))]
+#[pyattr]
+use libc::{
+    POSIX_FADV_DONTNEED, POSIX_FADV_NOREUSE, POSIX_FADV_NORMAL, POSIX_FADV_RANDOM,
+    POSIX_FADV_SEQUENTIAL, POSIX_FADV_WILLNEED,
+};

94-97: Restrict TFD_ (timerfd) to Linux/Android*

NetBSD doesn’t provide timerfd.

-#[cfg(any(target_os = "android", target_os = "linux", target_os = "netbsd"))]
+#[cfg(any(target_os = "android", target_os = "linux"))]
 #[pyattr]
 use libc::{TFD_CLOEXEC, TFD_NONBLOCK, TFD_TIMER_ABSTIME, TFD_TIMER_CANCEL_ON_SET};

111-118: O_PATH is Linux-specific (Android may also expose); remove FreeBSD/Redox

This will fail on FreeBSD/Redox.

-#[cfg(any(
-    target_os = "android",
-    target_os = "freebsd",
-    target_os = "linux",
-    target_os = "redox"
-))]
+#[cfg(any(target_os = "android", target_os = "linux"))]
 #[pyattr]
 use libc::O_PATH;

120-127: Restrict O_RSYNC to Linux

O_RSYNC isn’t generally exposed on BSDs; Android’s support is unclear.

-#[cfg(any(
-    target_os = "android",
-    target_os = "linux",
-    target_os = "netbsd",
-    target_os = "openbsd"
-))]
-#[pyattr]
-use libc::O_RSYNC;
+#[cfg(target_os = "linux")]
+#[pyattr]
+use libc::O_RSYNC;
🧹 Nitpick comments (3)
vm/src/stdlib/posix.rs (3)

75-82: Nit: simplify cfg to unix

any(target_os = "android", unix) is redundant; Android is already unix.

-#[cfg(any(target_os = "android", unix))]
+#[cfg(unix)]
 #[pyattr]
 use libc::{
     F_OK, O_CLOEXEC, O_DIRECTORY, O_NOFOLLOW, O_NONBLOCK, PRIO_PGRP, PRIO_PROCESS, PRIO_USER,
     R_OK, RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NOW, W_OK, WCONTINUED, WNOHANG, WUNTRACED,
     X_OK,
 };

193-208: Verify CLD_ and F_LOCK family coverage; consider dropping redox*

Some CLD_* and F_LOCK/TLOCK/ULOCK may not exist on Redox; broad gating risks build breaks.

-#[cfg(any(
+#[cfg(any(
     target_os = "android",
     target_os = "dragonfly",
     target_os = "freebsd",
     target_os = "linux",
     target_os = "macos",
     target_os = "netbsd",
-    target_os = "openbsd",
-    target_os = "redox"
+    target_os = "openbsd"
 ))]

209-221: Verify O_ASYNC/WEXITED/WNOWAIT/WSTOPPED on Redox

These waitid/async constants may be missing on Redox; suggest excluding if CI fails.

-#[cfg(any(
+#[cfg(any(
     target_os = "android",
     target_os = "dragonfly",
     target_os = "freebsd",
     target_os = "linux",
     target_os = "macos",
     target_os = "netbsd",
-    target_os = "openbsd",
-    target_os = "redox"
+    target_os = "openbsd"
 ))]
📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e9594c3 and 29c40ae.

📒 Files selected for processing (2)
  • scripts/libc_posix.py (1 hunks)
  • vm/src/stdlib/posix.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • scripts/libc_posix.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Follow the default rustfmt code style (cargo fmt to format)
Always run clippy to lint code (cargo clippy) before completing tasks. Fix any warnings or lints that are introduced by your changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

Files:

  • vm/src/stdlib/posix.rs
🧠 Learnings (1)
📚 Learning: 2025-06-27T14:47:28.810Z
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.810Z
Learning: In RustPython's stat module implementation, platform-specific constants like SF_SUPPORTED and SF_SYNTHETIC should be conditionally declared only for the platforms where they're available (e.g., macOS), following CPython's approach of optional declaration using #ifdef checks rather than providing fallback values for other platforms.

Applied to files:

  • vm/src/stdlib/posix.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (ubuntu-latest)
🔇 Additional comments (11)
vm/src/stdlib/posix.rs (11)

54-57: LGTM: PIDFD_NONBLOCK gating is correct (Linux-only).


58-64: LGTM: Darwin-only constants and aliasing to _COPYFILE_DATA look good.


83-86: LGTM: O_SYMLINK correctly gated to macOS/redox.


102-110: LGTM: GRND_ coverage looks reasonable across the listed Unixes.*


149-159: LGTM: RTLD_NOLOAD gating looks fine.


160-169: LGTM: O_DSYNC across listed Unixes is reasonable.


171-181: LGTM: SCHED_OTHER exposure across these targets is fine.


139-147: Remove macOS from O_DIRECT (not a Darwin open(2) flag)

macOS uses F_NOCACHE via fcntl; O_DIRECT isn’t available there.

-#[cfg(any(
-    target_os = "android",
-    target_os = "dragonfly",
-    target_os = "freebsd",
-    target_os = "linux",
-    target_os = "netbsd"
-))]
+#[cfg(any(
+    target_os = "android",
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "linux",
+    target_os = "netbsd"
+))]
 #[pyattr]
 use libc::O_DIRECT;

Likely an incorrect or invalid review comment.


182-192: Keep Redox in the cfg since O_EXLOCK and O_SHLOCK are defined in Redox’s libc.

Likely an incorrect or invalid review comment.


98-101: Retain NetBSD in cfg NetBSD’s Linux-compatible sys/xattr.h defines XATTR_CREATE and XATTR_REPLACE, so the original #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd"))] is correct.

Likely an incorrect or invalid review comment.


129-137: Keep the single import; all three flags are supported on macOS and Android
macOS’s <dlfcn.h> defines RTLD_NODELETE and its headers (and Python itself) expose SEEK_DATA/SEEK_HOLE (opensource.apple.com, docs.python.org). Android’s Bionic <dlfcn.h> defines RTLD_NODELETE and its <unistd.h> pulls in bits/seek_constants.h for SEEK_DATA/SEEK_HOLE (android.googlesource.com). The existing #[cfg(any(target_os = "android", "dragonfly", "freebsd", "linux", "macos"))] use libc::{RTLD_NODELETE, SEEK_DATA, SEEK_HOLE}; is correct.

Likely an incorrect or invalid review comment.

@youknowone

Copy link
Copy Markdown
Member

I ain't so sure how we decide what goes into os directly and what into posix

I can say it is arbitrary based on history of the module. Currently os.rs tends to have shared definitions between nt, posix, and posix_compat, but not strictly. You can safely relocate everything if it is better.

@youknowone youknowone left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hide comment

👍

Hide details View details @youknowone youknowone merged commit 056795e into RustPython:main Sep 3, 2025
12 checks passed
@ShaharNaveh ShaharNaveh mentioned this pull request Sep 3, 2025
@ShaharNaveh ShaharNaveh deleted the automate-posix-consts branch September 7, 2025 07:09
@ShaharNaveh ShaharNaveh changed the title Attenpt to automate posix consts Sep 16, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Mar 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants