From 671a219316a6e22c69fe84bc8e6f5b398552512e Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Wed, 22 Jul 2026 14:19:31 -0600 Subject: [PATCH 1/8] StatFS implementation --- Sources/CSystem/include/CSystemLinux.h | 22 +- Sources/CSystem/shims.c | 25 + Sources/System/CMakeLists.txt | 6 +- Sources/System/FileSystem/MountFlags.swift | 522 ++++++++++++++ Sources/System/FileSystem/StatFS.swift | 748 +++++++++++++++++++++ Sources/System/Internals/CInterop.swift | 23 + Sources/System/Internals/Constants.swift | 346 ++++++++++ Sources/System/Internals/Exports.swift | 20 + Tests/SystemTests/StatFSTests.swift | 475 +++++++++++++ 9 files changed, 2184 insertions(+), 3 deletions(-) create mode 100644 Sources/System/FileSystem/MountFlags.swift create mode 100644 Sources/System/FileSystem/StatFS.swift create mode 100644 Tests/SystemTests/StatFSTests.swift diff --git a/Sources/CSystem/include/CSystemLinux.h b/Sources/CSystem/include/CSystemLinux.h index 815e142..5176f20 100644 --- a/Sources/CSystem/include/CSystemLinux.h +++ b/Sources/CSystem/include/CSystemLinux.h @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -20,5 +20,25 @@ #include #include #include "io_uring.h" + +// The `ST_*` mount-flag constants in require _GNU_SOURCE. +// Rather than define _GNU_SOURCE module-wide, which clashes with SwiftGlibc, +// expose them through these getters, defined in shims.c under _GNU_SOURCE. +#include +uint64_t _system_get_ST_RDONLY(void); +uint64_t _system_get_ST_NOSUID(void); +uint64_t _system_get_ST_NODEV(void); +uint64_t _system_get_ST_NOEXEC(void); +uint64_t _system_get_ST_SYNCHRONOUS(void); +uint64_t _system_get_ST_MANDLOCK(void); +uint64_t _system_get_ST_NOATIME(void); +uint64_t _system_get_ST_NODIRATIME(void); +uint64_t _system_get_ST_RELATIME(void); +uint64_t _system_get_ST_NOSYMFOLLOW(void); +#if !defined(__ANDROID__) +uint64_t _system_get_ST_WRITE(void); +uint64_t _system_get_ST_APPEND(void); +uint64_t _system_get_ST_IMMUTABLE(void); +#endif #endif diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c index b32bd84..a477bbb 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -19,7 +19,32 @@ #endif #ifdef __linux__ + +// The `ST_*` mount-flag constants in require _GNU_SOURCE. +// Define it here, in a dedicated translation unit, not in CSystemLinux.h, +// since defining it there changes libc types like `fd_set` for every file +// that imports CSystem and conflicts with SwiftGlibc. #define _GNU_SOURCE +#include +#include + +uint64_t _system_get_ST_RDONLY(void) { return ST_RDONLY; } +uint64_t _system_get_ST_NOSUID(void) { return ST_NOSUID; } +uint64_t _system_get_ST_NODEV(void) { return ST_NODEV; } +uint64_t _system_get_ST_NOEXEC(void) { return ST_NOEXEC; } +uint64_t _system_get_ST_SYNCHRONOUS(void) { return ST_SYNCHRONOUS; } +uint64_t _system_get_ST_MANDLOCK(void) { return ST_MANDLOCK; } +uint64_t _system_get_ST_NOATIME(void) { return ST_NOATIME; } +uint64_t _system_get_ST_NODIRATIME(void) { return ST_NODIRATIME; } +uint64_t _system_get_ST_RELATIME(void) { return ST_RELATIME; } +uint64_t _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; } + +#if !defined(__ANDROID__) +uint64_t _system_get_ST_WRITE(void) { return ST_WRITE; } +uint64_t _system_get_ST_APPEND(void) { return ST_APPEND; } +uint64_t _system_get_ST_IMMUTABLE(void) { return ST_IMMUTABLE; } +#endif + #include #endif diff --git a/Sources/System/CMakeLists.txt b/Sources/System/CMakeLists.txt index 8062a8d..73d8098 100644 --- a/Sources/System/CMakeLists.txt +++ b/Sources/System/CMakeLists.txt @@ -1,7 +1,7 @@ #[[ This source file is part of the Swift System open source project -Copyright (c) 2020 Apple Inc. and the Swift System project authors +Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information @@ -61,7 +61,9 @@ target_sources(SystemPackage PRIVATE FileSystem/FileMode.swift FileSystem/FileType.swift FileSystem/Identifiers.swift - FileSystem/Stat.swift) + FileSystem/MountFlags.swift + FileSystem/Stat.swift + FileSystem/StatFS.swift) if(CMAKE_SYSTEM_NAME STREQUAL Linux) target_sources(SystemPackage PRIVATE IORing/IOCompletion.swift diff --git a/Sources/System/FileSystem/MountFlags.swift b/Sources/System/FileSystem/MountFlags.swift new file mode 100644 index 0000000..622ef61 --- /dev/null +++ b/Sources/System/FileSystem/MountFlags.swift @@ -0,0 +1,522 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift System open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift System project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// |-------------------------------------------------------------------------------------------------------------------------------------------| +// | Swift API to C Mapping | +// |-------------------------------------------------------------------------------------------------------------------------------------------| +// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android | WASI | +// |-----------------------------|----------------------|-----------------|-----------------|----------------|----------------|----------------| +// | readOnly | MNT_RDONLY | MNT_RDONLY | MNT_RDONLY | ST_RDONLY | ST_RDONLY | ST_RDONLY | +// | synchronous | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | ST_SYNCHRONOUS | ST_SYNCHRONOUS | ST_SYNCHRONOUS | +// | noExecution | MNT_NOEXEC | MNT_NOEXEC | MNT_NOEXEC | ST_NOEXEC | ST_NOEXEC | ST_NOEXEC | +// | noSetUserID | MNT_NOSUID | MNT_NOSUID | MNT_NOSUID | ST_NOSUID | ST_NOSUID | ST_NOSUID | +// | noAccessTime | MNT_NOATIME | MNT_NOATIME | MNT_NOATIME | ST_NOATIME | ST_NOATIME | ST_NOATIME | +// | noDevices | MNT_NODEV | N/A | MNT_NODEV | ST_NODEV | ST_NODEV | ST_NODEV | +// | mandatoryLockingPermitted | N/A | N/A | N/A | ST_MANDLOCK | ST_MANDLOCK | ST_MANDLOCK | +// | noDirectoryAccessTime | N/A | N/A | N/A | ST_NODIRATIME | ST_NODIRATIME | ST_NODIRATIME | +// | relativeAccessTime | N/A | N/A | N/A | ST_RELATIME | ST_RELATIME | ST_RELATIME | +// | write | N/A | N/A | N/A | ST_WRITE | N/A | ST_WRITE | +// | appendOnly | N/A | N/A | N/A | ST_APPEND | N/A | ST_APPEND | +// | immutable | N/A | N/A | N/A | ST_IMMUTABLE | N/A | ST_IMMUTABLE | +// | noSymlinkFollow | N/A | MNT_NOSYMFOLLOW | N/A | ST_NOSYMFOLLOW | ST_NOSYMFOLLOW | N/A | +// | asynchronous | MNT_ASYNC | MNT_ASYNC | MNT_ASYNC | N/A | N/A | N/A | +// | exported | MNT_EXPORTED | MNT_EXPORTED | MNT_EXPORTED | N/A | N/A | N/A | +// | local | MNT_LOCAL | MNT_LOCAL | MNT_LOCAL | N/A | N/A | N/A | +// | quota | MNT_QUOTA | MNT_QUOTA | MNT_QUOTA | N/A | N/A | N/A | +// | rootFileSystem | MNT_ROOTFS | MNT_ROOTFS | MNT_ROOTFS | N/A | N/A | N/A | +// | union | MNT_UNION | MNT_UNION | N/A | N/A | N/A | N/A | +// | automounted | MNT_AUTOMOUNTED | MNT_AUTOMOUNTED | N/A | N/A | N/A | N/A | +// | multiLabel | MNT_MULTILABEL | MNT_MULTILABEL | N/A | N/A | N/A | N/A | +// | exportedReadOnly | N/A | MNT_EXRDONLY | MNT_EXRDONLY | N/A | N/A | N/A | +// | exportedByDefault | N/A | MNT_DEFEXPORTED | MNT_DEFEXPORTED | N/A | N/A | N/A | +// | exportedAnonymously | N/A | MNT_EXPORTANON | MNT_EXPORTANON | N/A | N/A | N/A | +// | softUpdates | N/A | MNT_SOFTDEP | MNT_SOFTDEP | N/A | N/A | N/A | +// | contentProtection | MNT_CPROTECT | N/A | N/A | N/A | N/A | N/A | +// | removable | MNT_REMOVABLE | N/A | N/A | N/A | N/A | N/A | +// | quarantine | MNT_QUARANTINE | N/A | N/A | N/A | N/A | N/A | +// | volumeFileSystem | MNT_DOVOLFS | N/A | N/A | N/A | N/A | N/A | +// | noBrowsing | MNT_DONTBROWSE | N/A | N/A | N/A | N/A | N/A | +// | ignoreOwnership | MNT_IGNORE_OWNERSHIP | N/A | N/A | N/A | N/A | N/A | +// | journaled | MNT_JOURNALED | N/A | N/A | N/A | N/A | N/A | +// | noUserExtendedAttributes | MNT_NOUSERXATTR | N/A | N/A | N/A | N/A | N/A | +// | deferWrites | MNT_DEFWRITE | N/A | N/A | N/A | N/A | N/A | +// | noSymlinkFollowAtMountPoint | MNT_NOFOLLOW | N/A | N/A | N/A | N/A | N/A | +// | snapshot | MNT_SNAPSHOT | N/A | N/A | N/A | N/A | N/A | +// | strictAccessTime | MNT_STRICTATIME | N/A | N/A | N/A | N/A | N/A | +// | exportedKerberos | N/A | MNT_EXKERB | N/A | N/A | N/A | N/A | +// | exportedPublic | N/A | MNT_EXPUBLIC | N/A | N/A | N/A | N/A | +// | posixACLs | N/A | MNT_ACLS | N/A | N/A | N/A | N/A | +// | geomJournaled | N/A | MNT_GJOURNAL | N/A | N/A | N/A | N/A | +// | excludedFromDiskFreeReports | N/A | MNT_IGNORE | N/A | N/A | N/A | N/A | +// | nfs4ACLs | N/A | MNT_NFS4ACLS | N/A | N/A | N/A | N/A | +// | noClusterRead | N/A | MNT_NOCLUSTERR | N/A | N/A | N/A | N/A | +// | noClusterWrite | N/A | MNT_NOCLUSTERW | N/A | N/A | N/A | N/A | +// | setUserIDDirectory | N/A | MNT_SUIDDIR | N/A | N/A | N/A | N/A | +// | softUpdateJournaling | N/A | MNT_SUJ | N/A | N/A | N/A | N/A | +// | untrusted | N/A | MNT_UNTRUSTED | N/A | N/A | N/A | N/A | +// | mountedByUser | N/A | MNT_USER | N/A | N/A | N/A | N/A | +// | verified | N/A | MNT_VERIFIED | N/A | N/A | N/A | N/A | +// | noPermissionChecks | N/A | N/A | MNT_NOPERM | N/A | N/A | N/A | +// | writeExecuteAllowed | N/A | N/A | MNT_WXALLOWED | N/A | N/A | N/A | +// |-------------------------------------------------------------------------------------------------------------------------------------------| + +#if !os(Windows) + +/// Options employed when mounting a file system. +/// +/// These are the flags reported in the `f_flags` field of a `statfs` struct on +/// Darwin and BSD, or the `f_flag` field of a `statvfs` struct on other +/// platforms. +/// +/// - Note: Only available on Unix-like platforms. +@frozen +@available(System 199, *) +public struct MountFlags: OptionSet, Sendable, Hashable, Codable { + + /// The raw C flags. + @_alwaysEmitIntoClient + public let rawValue: CInterop.MountFlags + + /// Creates a strongly-typed `MountFlags` from the raw C value. + @_alwaysEmitIntoClient + public init(rawValue: CInterop.MountFlags) { self.rawValue = rawValue } + + // MARK: Flags Available on All Platforms + + /// The file system is mounted read-only, even for the super-user. + /// + /// The corresponding C constant is `MNT_RDONLY` on Darwin and BSD, + /// or `ST_RDONLY` otherwise. + @_alwaysEmitIntoClient + public static var readOnly: MountFlags { MountFlags(rawValue: _MOUNT_RDONLY) } + + /// The file system is written to synchronously. + /// + /// The corresponding C constant is `MNT_SYNCHRONOUS` on Darwin and BSD, + /// or `ST_SYNCHRONOUS` otherwise. + @_alwaysEmitIntoClient + public static var synchronous: MountFlags { MountFlags(rawValue: _MOUNT_SYNCHRONOUS) } + + /// Programs may not be executed from the file system. + /// + /// The corresponding C constant is `MNT_NOEXEC` on Darwin and BSD, + /// or `ST_NOEXEC` otherwise. + @_alwaysEmitIntoClient + public static var noExecution: MountFlags { MountFlags(rawValue: _MOUNT_NOEXEC) } + + /// Set-user-ID and set-group-ID bits are not honored on the file system. + /// + /// The corresponding C constant is `MNT_NOSUID` on Darwin and BSD, + /// or `ST_NOSUID` otherwise. + @_alwaysEmitIntoClient + public static var noSetUserID: MountFlags { MountFlags(rawValue: _MOUNT_NOSUID) } + + /// Access times are not updated on the file system. + /// + /// The corresponding C constant is `MNT_NOATIME` on Darwin and BSD, + /// or `ST_NOATIME` otherwise. + /// - Note: On OpenBSD, access time may still be updated when the + /// modification or status-change time is also being updated. + @_alwaysEmitIntoClient + public static var noAccessTime: MountFlags { MountFlags(rawValue: _MOUNT_NOATIME) } + + // MARK: Flags Available on All Platforms Except FreeBSD + + #if !os(FreeBSD) + /// Special files may not be interpreted on the file system. + /// + /// The corresponding C constant is `MNT_NODEV` on Darwin and OpenBSD, + /// or `ST_NODEV` otherwise. + /// - Note: Not available on FreeBSD. + @_alwaysEmitIntoClient + public static var noDevices: MountFlags { MountFlags(rawValue: _MOUNT_NODEV) } + #endif + + // MARK: Flags Available on Linux, WASI, and Android + + #if os(Linux) || os(WASI) || os(Android) + /// The file system permits mandatory file locking. + /// + /// The corresponding C constant is `ST_MANDLOCK`. + /// - Note: Only available on Linux, WASI, and Android. + /// - Note: Mandatory locking was deprecated and removed in Linux 5.15. + @_alwaysEmitIntoClient + public static var mandatoryLockingPermitted: MountFlags { MountFlags(rawValue: _ST_MANDLOCK) } + + /// Directory access times are not updated on the file system. + /// + /// The corresponding C constant is `ST_NODIRATIME`. + /// - Note: Only available on Linux, WASI, and Android. + @_alwaysEmitIntoClient + public static var noDirectoryAccessTime: MountFlags { MountFlags(rawValue: _ST_NODIRATIME) } + + /// The access time is only updated if it's earlier than or equal to the file's + /// last modification or status-change time, or if it's more than a day old. + /// + /// The corresponding C constant is `ST_RELATIME`. + /// - Note: Only available on Linux, WASI, and Android. + @_alwaysEmitIntoClient + public static var relativeAccessTime: MountFlags { MountFlags(rawValue: _ST_RELATIME) } + #endif + + // MARK: Flags Available on Linux and WASI Only + + #if os(Linux) || os(WASI) + /// Files, directories, and symbolic links on the file system are writable. + /// + /// The corresponding C constant is `ST_WRITE`. + /// - Note: Only available on Linux and WASI. + @_alwaysEmitIntoClient + public static var write: MountFlags { MountFlags(rawValue: _ST_WRITE) } + + /// Files on the file system are append-only. + /// + /// The corresponding C constant is `ST_APPEND`. + /// - Note: Only available on Linux and WASI. + @_alwaysEmitIntoClient + public static var appendOnly: MountFlags { MountFlags(rawValue: _ST_APPEND) } + + /// Files on the file system are immutable. + /// + /// The corresponding C constant is `ST_IMMUTABLE`. + /// - Note: Only available on Linux and WASI. + @_alwaysEmitIntoClient + public static var immutable: MountFlags { MountFlags(rawValue: _ST_IMMUTABLE) } + #endif + + // MARK: Flags Available on Linux, Android, and FreeBSD + + #if os(Linux) || os(Android) || os(FreeBSD) + /// Symbolic links are not followed when resolving paths on the file system. + /// + /// Unlike Darwin's `noSymlinkFollowAtMountPoint`, this suppresses symlink + /// following for all path resolution on the mount, not just when resolving + /// the mount point. + /// + /// The corresponding C constant is `MNT_NOSYMFOLLOW` on FreeBSD, + /// or `ST_NOSYMFOLLOW` on Linux and Android. + /// - Note: Only available on Linux, Android, and FreeBSD. + @_alwaysEmitIntoClient + public static var noSymlinkFollow: MountFlags { MountFlags(rawValue: _MOUNT_NOSYMFOLLOW) } + #endif + + // MARK: Flags Available on Darwin, FreeBSD, and OpenBSD + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + /// The file system is written to asynchronously. + /// + /// The corresponding C constant is `MNT_ASYNC`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public static var asynchronous: MountFlags { MountFlags(rawValue: _MNT_ASYNC) } + + /// The file system is exported for use over the network via NFS. + /// + /// The corresponding C constant is `MNT_EXPORTED`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public static var exported: MountFlags { MountFlags(rawValue: _MNT_EXPORTED) } + + /// The file system is stored locally, rather than being accessed over a network. + /// + /// The corresponding C constant is `MNT_LOCAL`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public static var local: MountFlags { MountFlags(rawValue: _MNT_LOCAL) } + + /// Quotas are enabled on the file system. + /// + /// The corresponding C constant is `MNT_QUOTA`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public static var quota: MountFlags { MountFlags(rawValue: _MNT_QUOTA) } + + /// The file system is the root file system. + /// + /// The corresponding C constant is `MNT_ROOTFS`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public static var rootFileSystem: MountFlags { MountFlags(rawValue: _MNT_ROOTFS) } + #endif + + // MARK: Flags Available on Darwin and FreeBSD + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) + /// The file system is unioned with the underlying file system, rather than + /// obscuring it. + /// + /// The corresponding C constant is `MNT_UNION`. + /// - Note: Only available on Darwin and FreeBSD. + @_alwaysEmitIntoClient + public static var union: MountFlags { MountFlags(rawValue: _MNT_UNION) } + + /// The file system was mounted by the automounter. + /// + /// The corresponding C constant is `MNT_AUTOMOUNTED`. + /// - Note: Only available on Darwin and FreeBSD. See `autofs(4)`. + @_alwaysEmitIntoClient + public static var automounted: MountFlags { MountFlags(rawValue: _MNT_AUTOMOUNTED) } + + /// The file system supports Mandatory Access Control (MAC) labels for + /// individual objects. + /// + /// The corresponding C constant is `MNT_MULTILABEL`. + /// - Note: Only available on Darwin and FreeBSD. + @_alwaysEmitIntoClient + public static var multiLabel: MountFlags { MountFlags(rawValue: _MNT_MULTILABEL) } + #endif + + // MARK: Flags Available on FreeBSD and OpenBSD + + #if os(FreeBSD) || os(OpenBSD) + /// The file system is exported for reading only. + /// + /// The corresponding C constant is `MNT_EXRDONLY`. + /// - Note: Only available on FreeBSD and OpenBSD. + @_alwaysEmitIntoClient + public static var exportedReadOnly: MountFlags { MountFlags(rawValue: _MNT_EXRDONLY) } + + /// The file system is exported for reading and writing to any host by default. + /// + /// The corresponding C constant is `MNT_DEFEXPORTED`. + /// - Note: Only available on FreeBSD and OpenBSD. + @_alwaysEmitIntoClient + public static var exportedByDefault: MountFlags { MountFlags(rawValue: _MNT_DEFEXPORTED) } + + /// The file system maps all remote users to the anonymous user account. + /// + /// The corresponding C constant is `MNT_EXPORTANON`. + /// - Note: Only available on FreeBSD and OpenBSD. + @_alwaysEmitIntoClient + public static var exportedAnonymously: MountFlags { MountFlags(rawValue: _MNT_EXPORTANON) } + + /// The file system uses soft updates. + /// + /// The corresponding C constant is `MNT_SOFTDEP`. + /// - Note: Only available on FreeBSD and OpenBSD. Accepted for compatibility + /// on OpenBSD, but has no effect there. + @_alwaysEmitIntoClient + public static var softUpdates: MountFlags { MountFlags(rawValue: _MNT_SOFTDEP) } + #endif + + // MARK: Flags Available on Darwin Only + + #if SYSTEM_PACKAGE_DARWIN + /// The file system supports per-file encrypted data protection. + /// + /// The corresponding C constant is `MNT_CPROTECT`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var contentProtection: MountFlags { MountFlags(rawValue: _MNT_CPROTECT) } + + /// The file system resides on removable media. + /// + /// The corresponding C constant is `MNT_REMOVABLE`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var removable: MountFlags { MountFlags(rawValue: _MNT_REMOVABLE) } + + /// The file system is quarantined. + /// + /// The corresponding C constant is `MNT_QUARANTINE`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var quarantine: MountFlags { MountFlags(rawValue: _MNT_QUARANTINE) } + + /// The file system supports volfs. + /// + /// The corresponding C constant is `MNT_DOVOLFS`. + /// - Note: Only available on Darwin. Deprecated since Mac OS X 10.5 and + /// not set on modern systems. + @_alwaysEmitIntoClient + public static var volumeFileSystem: MountFlags { MountFlags(rawValue: _MNT_DOVOLFS) } + + /// The file system should not be presented to the user for browsing + /// (e.g. hidden in Finder). + /// + /// The corresponding C constant is `MNT_DONTBROWSE`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var noBrowsing: MountFlags { MountFlags(rawValue: _MNT_DONTBROWSE) } + + /// Ownership information on the file system is ignored. + /// + /// The corresponding C constant is `MNT_IGNORE_OWNERSHIP`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var ignoreOwnership: MountFlags { MountFlags(rawValue: _MNT_IGNORE_OWNERSHIP) } + + /// The file system is journaled. + /// + /// The corresponding C constant is `MNT_JOURNALED`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var journaled: MountFlags { MountFlags(rawValue: _MNT_JOURNALED) } + + /// User extended attributes are not allowed on the file system. + /// + /// The corresponding C constant is `MNT_NOUSERXATTR`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var noUserExtendedAttributes: MountFlags { MountFlags(rawValue: _MNT_NOUSERXATTR) } + + /// The file system defers writes. + /// + /// The corresponding C constant is `MNT_DEFWRITE`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var deferWrites: MountFlags { MountFlags(rawValue: _MNT_DEFWRITE) } + + /// Symbolic links are not followed when resolving the mount point. + /// + /// The corresponding C constant is `MNT_NOFOLLOW`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var noSymlinkFollowAtMountPoint: MountFlags { MountFlags(rawValue: _MNT_NOFOLLOW) } + + /// The mount is a snapshot. + /// + /// The corresponding C constant is `MNT_SNAPSHOT`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var snapshot: MountFlags { MountFlags(rawValue: _MNT_SNAPSHOT) } + + /// Access times are always updated on access. Relatime-style optimizations + /// are disabled. + /// + /// The corresponding C constant is `MNT_STRICTATIME`. + /// - Note: Only available on Darwin. + @_alwaysEmitIntoClient + public static var strictAccessTime: MountFlags { MountFlags(rawValue: _MNT_STRICTATIME) } + #endif + + // MARK: Flags Available on FreeBSD Only + + #if os(FreeBSD) + /// The file system is exported with Kerberos user-ID mapping. + /// + /// The corresponding C constant is `MNT_EXKERB`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var exportedKerberos: MountFlags { MountFlags(rawValue: _MNT_EXKERB) } + + /// The file system is exported publicly for WebNFS clients. + /// + /// The corresponding C constant is `MNT_EXPUBLIC`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var exportedPublic: MountFlags { MountFlags(rawValue: _MNT_EXPUBLIC) } + + /// The file system supports POSIX.1e ACLs. + /// + /// The corresponding C constant is `MNT_ACLS`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var posixACLs: MountFlags { MountFlags(rawValue: _MNT_ACLS) } + + /// The file system uses `gjournal`. + /// + /// The corresponding C constant is `MNT_GJOURNAL`. + /// - Note: Only available on FreeBSD. See `gjournal(8)`. + @_alwaysEmitIntoClient + public static var geomJournaled: MountFlags { MountFlags(rawValue: _MNT_GJOURNAL) } + + /// The file system is omitted from `df(1)` listings. + /// + /// The corresponding C constant is `MNT_IGNORE`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var excludedFromDiskFreeReports: MountFlags { MountFlags(rawValue: _MNT_IGNORE) } + + /// The file system supports NFSv4 ACLs. + /// + /// The corresponding C constant is `MNT_NFS4ACLS`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var nfs4ACLs: MountFlags { MountFlags(rawValue: _MNT_NFS4ACLS) } + + /// Clustered reads are disabled on the file system. + /// + /// The corresponding C constant is `MNT_NOCLUSTERR`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var noClusterRead: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERR) } + + /// Clustered writes are disabled on the file system. + /// + /// The corresponding C constant is `MNT_NOCLUSTERW`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var noClusterWrite: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERW) } + + /// Newly created files in a directory with the set-user-ID bit set are owned + /// by that directory's owner, rather than by the creating user. + /// + /// The corresponding C constant is `MNT_SUIDDIR`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var setUserIDDirectory: MountFlags { MountFlags(rawValue: _MNT_SUIDDIR) } + + /// The file system uses soft updates with journaling. + /// + /// The corresponding C constant is `MNT_SUJ`. + /// - Note: Only available on FreeBSD. Combines `softUpdates` with a journal + /// for fast recovery. + @_alwaysEmitIntoClient + public static var softUpdateJournaling: MountFlags { MountFlags(rawValue: _MNT_SUJ) } + + /// The file system is untrusted, as the integrity of its media is unknown. + /// + /// The corresponding C constant is `MNT_UNTRUSTED`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var untrusted: MountFlags { MountFlags(rawValue: _MNT_UNTRUSTED) } + + /// The file system was mounted by a non-root user. + /// + /// The corresponding C constant is `MNT_USER`. + /// - Note: Only available on FreeBSD. + @_alwaysEmitIntoClient + public static var mountedByUser: MountFlags { MountFlags(rawValue: _MNT_USER) } + + /// The file system is marked as verified, so per-file integrity checks are + /// skipped on execution. + /// + /// The corresponding C constant is `MNT_VERIFIED`. + /// - Note: Only available on FreeBSD. See `mac_veriexec(4)`. + @_alwaysEmitIntoClient + public static var verified: MountFlags { MountFlags(rawValue: _MNT_VERIFIED) } + #endif + + // MARK: Flags Available on OpenBSD Only + + #if os(OpenBSD) + /// File permissions are not checked on the file system (FFS only). + /// + /// The corresponding C constant is `MNT_NOPERM`. + /// - Note: Only available on OpenBSD. + @_alwaysEmitIntoClient + public static var noPermissionChecks: MountFlags { MountFlags(rawValue: _MNT_NOPERM) } + + /// Programs residing on the file system may create memory mappings that are + /// both writable and executable. + /// + /// By default, requesting such a mapping (via `mmap(2)` or `mprotect(2)`) + /// kills the process. This flag lifts that restriction. + /// + /// The corresponding C constant is `MNT_WXALLOWED`. + /// - Note: Only available on OpenBSD. + @_alwaysEmitIntoClient + public static var writeExecuteAllowed: MountFlags { MountFlags(rawValue: _MNT_WXALLOWED) } + #endif +} + +#endif // !os(Windows) diff --git a/Sources/System/FileSystem/StatFS.swift b/Sources/System/FileSystem/StatFS.swift new file mode 100644 index 0000000..b653328 --- /dev/null +++ b/Sources/System/FileSystem/StatFS.swift @@ -0,0 +1,748 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift System open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift System project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if os(Windows) + +/// A Swift wrapper of the C `statfs` struct on Darwin and BSD operating +/// systems, or the standard `statvfs` otherwise. +/// +/// - Note: Only available on Unix-like platforms. +@available(Windows, unavailable, message: "StatFS is unavailable on Windows. Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") +public struct StatFS {} + +extension FileDescriptor { + /// Creates a `StatFS` for the file system containing the file referenced by + /// this `FileDescriptor`. + @available(Windows, unavailable, message: "StatFS is unavailable on Windows. Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") + public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { + fatalError("StatFS is unavailable on Windows") + } +} + +extension FilePath { + /// Creates a `StatFS` for the file system containing the file referenced by + /// this `FilePath`. + @available(Windows, unavailable, message: "StatFS is unavailable on Windows. Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") + public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { + fatalError("StatFS is unavailable on Windows") + } +} + +#else + +// Must import here to use C statfs/statvfs properties in +// @_alwaysEmitIntoClient APIs. +#if SYSTEM_PACKAGE_DARWIN +import Darwin +#elseif canImport(Glibc) +import CSystem +import Glibc +#elseif canImport(Musl) +import CSystem +import Musl +#elseif canImport(WASILibc) +import WASILibc +#elseif canImport(Android) +import CSystem +import Android +#else +#error("Unsupported Platform") +#endif + +// MARK: - FileSystemID + +/// A Swift wrapper of the C `f_fsid` file system ID found in a `statfs` or +/// `statvfs` struct. +@frozen +@available(System 199, *) +public struct FileSystemID: RawRepresentable, Sendable { + + /// The raw C file system ID. + @_alwaysEmitIntoClient + public var rawValue: CInterop.FileSystemID + + /// Creates a strongly-typed `FileSystemID` from the raw C value. + @_alwaysEmitIntoClient + public init(rawValue: CInterop.FileSystemID) { self.rawValue = rawValue } + + /// Creates a strongly-typed `FileSystemID` from the raw C value. + @_alwaysEmitIntoClient + public init(_ rawValue: CInterop.FileSystemID) { self.rawValue = rawValue } +} + +// On Darwin, FreeBSD, and OpenBSD, `CInterop.FileSystemID` is the C `fsid_t` +// struct (a fixed two-element `int32_t` array), which provides no synthesized +// conformances. Implement `Equatable`, `Hashable`, and `Codable` manually in +// terms of the underlying `val` members. On other platforms, the raw value is +// an integer, so the conformances are derived automatically. +#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) +@available(System 199, *) +extension FileSystemID: Equatable { + @_alwaysEmitIntoClient + public static func == (lhs: Self, rhs: Self) -> Bool { + lhs.rawValue.val.0 == rhs.rawValue.val.0 && lhs.rawValue.val.1 == rhs.rawValue.val.1 + } +} + +@available(System 199, *) +extension FileSystemID: Hashable { + @_alwaysEmitIntoClient + public func hash(into hasher: inout Hasher) { + hasher.combine(rawValue.val.0) + hasher.combine(rawValue.val.1) + } +} + +@available(System 199, *) +extension FileSystemID: Codable { + @_alwaysEmitIntoClient + public func encode(to encoder: any Encoder) throws { + var container = encoder.unkeyedContainer() + try container.encode(rawValue.val.0) + try container.encode(rawValue.val.1) + } + + @_alwaysEmitIntoClient + public init(from decoder: any Decoder) throws { + var container = try decoder.unkeyedContainer() + let val0 = try container.decode(Int32.self) + let val1 = try container.decode(Int32.self) + self.init(rawValue: CInterop.FileSystemID(val: (val0, val1))) + } +} +#else +@available(System 199, *) +extension FileSystemID: Equatable, Hashable, Codable {} +#endif + +#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) +// MARK: - FileSystemType + +/// A Swift wrapper of the C `f_type` file system type found in a `statfs` +/// struct on Darwin and FreeBSD. +/// +/// - Note: Only available on Darwin and FreeBSD. +@frozen +@available(System 199, *) +public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable { + + /// The raw C file system type. + @_alwaysEmitIntoClient + public var rawValue: UInt32 + + /// Creates a strongly-typed `FileSystemType` from the raw C value. + @_alwaysEmitIntoClient + public init(rawValue: UInt32) { self.rawValue = rawValue } + + /// Creates a strongly-typed `FileSystemType` from the raw C value. + @_alwaysEmitIntoClient + public init(_ rawValue: UInt32) { self.rawValue = rawValue } +} +#endif + +#if SYSTEM_PACKAGE_DARWIN +// MARK: - FileSystemSubtype + +/// A Swift wrapper of the C `f_fssubtype` file system subtype found in a +/// `statfs` struct on Darwin. +/// +/// - Note: Only available on Darwin. +@frozen +@available(System 199, *) +public struct FileSystemSubtype: RawRepresentable, Sendable, Hashable, Codable { + + /// The raw C file system subtype. + @_alwaysEmitIntoClient + public var rawValue: UInt32 + + /// Creates a strongly-typed `FileSystemSubtype` from the raw C value. + @_alwaysEmitIntoClient + public init(rawValue: UInt32) { self.rawValue = rawValue } + + /// Creates a strongly-typed `FileSystemSubtype` from the raw C value. + @_alwaysEmitIntoClient + public init(_ rawValue: UInt32) { self.rawValue = rawValue } +} +#endif + +// MARK: - StatFS + +#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) +// Helpers for reading the fixed-size, NUL-terminated C character buffers +// (`f_fstypename`, `f_mntonname`, `f_mntfromname`) in Darwin/BSD `statfs`. +// If the buffer has no NUL (malformed), the entire buffer is used. +@available(System 199, *) +extension String { + @usableFromInline + internal init(_nullTerminatedBytes buffer: UnsafeRawBufferPointer) { + let bytes = buffer.prefix { $0 != 0 } + self = String(decoding: bytes, as: CInterop.PlatformUnicodeEncoding.self) + } +} + +@available(System 199, *) +extension FilePath { + @usableFromInline + internal init(_nullTerminatedBytes buffer: UnsafeRawBufferPointer) { + let chars = buffer.bindMemory(to: CInterop.PlatformChar.self) + guard let base = chars.baseAddress else { + self = FilePath() + return + } + self = if chars.firstIndex(of: 0) != nil { + FilePath(platformString: base) + } else { + withUnsafeTemporaryAllocation( + of: CInterop.PlatformChar.self, + capacity: chars.count + 1 + ) { terminatedBuffer in + terminatedBuffer.baseAddress!.initialize(from: base, count: chars.count) + terminatedBuffer[chars.count] = 0 + return FilePath(platformString: terminatedBuffer.baseAddress!) + } + } + } +} +#endif + +/// A Swift wrapper of the C `statfs` struct on Darwin and BSD operating +/// systems, or the standard `statvfs` otherwise. +/// +/// - Note: Only available on Unix-like platforms. +/// - Note: The numeric properties clamp to the range of the underlying C +/// field in both directions. Use `rawValue` for exact, unclamped access. +@frozen +@available(System 199, *) +public struct StatFS: RawRepresentable, Sendable, Hashable { + + /// The raw C `statfs` struct on Darwin and BSD, or the `statvfs` struct + /// otherwise. + @_alwaysEmitIntoClient + public var rawValue: CInterop.StatFS + + /// Creates a Swift `StatFS` from the raw C struct. + @_alwaysEmitIntoClient + public init(rawValue: CInterop.StatFS) { self.rawValue = rawValue } + + // MARK: Initializers + + /// Creates a `StatFS` from a `FilePath`. + /// + /// The corresponding C function is `statfs()` on Darwin and BSD, or + /// `statvfs()` otherwise. + @_alwaysEmitIntoClient + public init( + _ path: FilePath, + retryOnInterrupt: Bool = true + ) throws(Errno) { + self.rawValue = try path.withPlatformString { + Self._statfs($0, retryOnInterrupt: retryOnInterrupt) + }.get() + } + + /// Creates a `StatFS` from a null-terminated `UnsafePointer` path. + /// + /// The corresponding C function is `statfs()` on Darwin and BSD, or + /// `statvfs()` otherwise. + @_alwaysEmitIntoClient + public init( + _ path: UnsafePointer, + retryOnInterrupt: Bool = true + ) throws(Errno) { + self.rawValue = try Self._statfs( + path, retryOnInterrupt: retryOnInterrupt + ).get() + } + + @usableFromInline + internal static func _statfs( + _ path: UnsafePointer, + retryOnInterrupt: Bool + ) -> Result { + var result = CInterop.StatFS() + return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + system_statfs(path, &result) + #else + system_statvfs(path, &result) + #endif + }.map { result } + } + + /// Creates a `StatFS` from a `FileDescriptor`. + /// + /// The corresponding C function is `fstatfs()` on Darwin and BSD, or + /// `fstatvfs()` otherwise. + @_alwaysEmitIntoClient + public init( + _ fd: FileDescriptor, + retryOnInterrupt: Bool = true + ) throws(Errno) { + self.rawValue = try Self._fstatfs( + fd, retryOnInterrupt: retryOnInterrupt + ).get() + } + + @usableFromInline + internal static func _fstatfs( + _ fd: FileDescriptor, + retryOnInterrupt: Bool + ) -> Result { + var result = CInterop.StatFS() + return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + system_fstatfs(fd.rawValue, &result) + #else + system_fstatvfs(fd.rawValue, &result) + #endif + }.map { result } + } + + // MARK: Properties + + /// File system block size, in bytes. + /// + /// The corresponding C property is `f_bsize`. + /// - Note: On Darwin and BSD, this is the fundamental size for block counts. + /// `statvfs` platforms use `fragmentSize` (`f_frsize`) instead. + @_alwaysEmitIntoClient + public var blockSize: Int { + get { Int(clamping: rawValue.f_bsize) } + set { rawValue.f_bsize = .init(clamping: newValue) } + } + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + /// Block size for optimal data transfer, in bytes. + /// + /// The corresponding C property is `f_iosize`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public var preferredIOBlockSize: Int { + get { Int(clamping: rawValue.f_iosize) } + set { rawValue.f_iosize = .init(clamping: newValue) } + } + #else + /// File system fragment size, in bytes. + /// + /// The corresponding C property is `f_frsize`. + /// - Note: On `statvfs` platforms, this is the fundamental size for block + /// counts. Not present on Darwin or BSD, which use `blockSize` instead. + @_alwaysEmitIntoClient + public var fragmentSize: Int { + get { Int(clamping: rawValue.f_frsize) } + set { rawValue.f_frsize = .init(clamping: newValue) } + } + #endif + + /// The fundamental block size used for space calculations, in bytes. + /// + /// This is `blockSize` on Darwin and BSD (`statfs`), or `fragmentSize` + /// otherwise (`statvfs`). + @_alwaysEmitIntoClient + internal var _fundamentalBlockSize: UInt64 { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + UInt64(clamping: rawValue.f_bsize) + #else + UInt64(clamping: rawValue.f_frsize) + #endif + } + + /// Multiplies a block count by the fundamental block size, saturating to + /// `UInt64.max` on overflow. + @_alwaysEmitIntoClient + internal func _saturatingSpace(_ blocks: UInt64) -> UInt64 { + let (result, overflow) = blocks.multipliedReportingOverflow(by: _fundamentalBlockSize) + return overflow ? .max : result + } + + /// Total number of blocks in the file system. + /// + /// The corresponding C property is `f_blocks`. + /// - Note: In units of `blockSize` on Darwin and BSD (`statfs`), or + /// `fragmentSize` otherwise (`statvfs`). + @_alwaysEmitIntoClient + public var totalBlocks: UInt64 { + get { UInt64(clamping: rawValue.f_blocks) } + set { rawValue.f_blocks = .init(clamping: newValue) } + } + + /// Total size of the file system, in bytes. + /// + /// - Note: Computed for convenience as `totalBlocks` times the fundamental + /// block size (see `totalBlocks`). Saturates to `UInt64.max` on overflow. + @_alwaysEmitIntoClient + public var totalSpace: UInt64 { _saturatingSpace(totalBlocks) } + + /// Number of free blocks in the file system. + /// + /// The corresponding C property is `f_bfree`. + /// - Note: In units of `blockSize` on Darwin and BSD (`statfs`), or + /// `fragmentSize` otherwise (`statvfs`). + @_alwaysEmitIntoClient + public var freeBlocks: UInt64 { + get { UInt64(clamping: rawValue.f_bfree) } + set { rawValue.f_bfree = .init(clamping: newValue) } + } + + /// Free space in the file system, in bytes. + /// + /// - Note: Computed for convenience as `freeBlocks` times the fundamental + /// block size (see `freeBlocks`). Saturates to `UInt64.max` on overflow. + @_alwaysEmitIntoClient + public var freeSpace: UInt64 { _saturatingSpace(freeBlocks) } + + /// Number of free blocks available to non-superuser. + /// + /// The corresponding C property is `f_bavail`. + /// - Note: In units of `blockSize` on Darwin and BSD (`statfs`), or + /// `fragmentSize` otherwise (`statvfs`). On FreeBSD and OpenBSD, the + /// underlying C property is signed; negative values are clamped to 0. + @_alwaysEmitIntoClient + public var availableBlocks: UInt64 { + get { UInt64(clamping: rawValue.f_bavail) } + set { rawValue.f_bavail = .init(clamping: newValue) } + } + + /// Available space in the file system for non-superuser, in bytes. + /// + /// - Note: Computed for convenience as `availableBlocks` times the fundamental + /// block size (see `availableBlocks`). Saturates to `UInt64.max` on overflow. + @_alwaysEmitIntoClient + public var availableSpace: UInt64 { _saturatingSpace(availableBlocks) } + + /// Total number of inodes in the file system. + /// + /// The corresponding C property is `f_files`. + @_alwaysEmitIntoClient + public var totalInodes: UInt64 { + get { UInt64(clamping: rawValue.f_files) } + set { rawValue.f_files = .init(clamping: newValue) } + } + + /// Number of free inodes in the file system. + /// + /// The corresponding C property is `f_ffree`. + /// - Note: On FreeBSD, this reports the inodes available to a non-superuser + /// rather than the total free count, and the underlying C field is signed + /// (negative values are clamped to 0); on other platforms, it is the total + /// number of free inodes. + @_alwaysEmitIntoClient + public var freeInodes: UInt64 { + get { UInt64(clamping: rawValue.f_ffree) } + set { rawValue.f_ffree = .init(clamping: newValue) } + } + + #if !SYSTEM_PACKAGE_DARWIN && !os(FreeBSD) + /// Number of free inodes available to non-superuser. + /// + /// The corresponding C property is `f_favail`, reported on the `statvfs` + /// platforms and by OpenBSD's `statfs`. + /// - Note: Darwin and FreeBSD `statfs` do not report it. On OpenBSD, the + /// underlying C property is signed; negative values are clamped to 0. + @_alwaysEmitIntoClient + public var availableInodes: UInt64 { + get { UInt64(clamping: rawValue.f_favail) } + set { rawValue.f_favail = .init(clamping: newValue) } + } + #endif + + #if !SYSTEM_PACKAGE_DARWIN + /// Maximum length of a file name on the file system, in bytes. + /// + /// The corresponding C property is `f_namemax`, reported on the `statvfs` + /// platforms and by FreeBSD and OpenBSD `statfs`. + /// - Note: Darwin's `statfs` does not report it. + @_alwaysEmitIntoClient + public var maximumNameLength: Int { + get { Int(clamping: rawValue.f_namemax) } + set { rawValue.f_namemax = .init(clamping: newValue) } + } + #endif + + /// File system ID. + /// + /// The corresponding C property is `f_fsid`. + @_alwaysEmitIntoClient + public var fileSystemID: FileSystemID { + get { FileSystemID(rawValue: rawValue.f_fsid) } + set { rawValue.f_fsid = newValue.rawValue } + } + + /// Mount flags indicating the options employed when mounting the file system. + /// + /// The corresponding C property is `f_flags` on Darwin and BSD, or `f_flag` + /// otherwise. + @_alwaysEmitIntoClient + public var mountFlags: MountFlags { + get { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + MountFlags(rawValue: rawValue.f_flags) + #else + MountFlags(rawValue: rawValue.f_flag) + #endif + } + set { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + rawValue.f_flags = newValue.rawValue + #else + rawValue.f_flag = newValue.rawValue + #endif + } + } + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) + /// File system type. + /// + /// The corresponding C property is `f_type`. + /// - Note: Only available on Darwin and FreeBSD, where this is an internal, + /// kernel-assigned VFS type index with no stable, public constants; it is + /// *not* a filesystem magic number like those found in the Linux `statfs`. + /// Prefer `typeName` to identify the file system in a readable format. + @_alwaysEmitIntoClient + public var type: FileSystemType { + get { FileSystemType(rawValue: numericCast(rawValue.f_type)) } + set { rawValue.f_type = numericCast(newValue.rawValue) } + } + #endif + + #if SYSTEM_PACKAGE_DARWIN + /// File system subtype. + /// + /// The corresponding C property is `f_fssubtype`. + /// - Note: Like `type`, this is a numeric value with no stable, public + /// constants. Only available on Darwin. + @_alwaysEmitIntoClient + public var subtype: FileSystemSubtype { + get { FileSystemSubtype(rawValue: numericCast(rawValue.f_fssubtype)) } + set { rawValue.f_fssubtype = numericCast(newValue.rawValue) } + } + #endif + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + /// User that mounted the file system. + /// + /// The corresponding C property is `f_owner`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public var owner: UserID { + get { UserID(rawValue: rawValue.f_owner) } + set { rawValue.f_owner = newValue.rawValue } + } + + /// File system type name. + /// + /// The corresponding C property is `f_fstypename`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public var typeName: String { + withUnsafeBytes(of: rawValue.f_fstypename) { + String(_nullTerminatedBytes: $0) + } + } + + /// Directory where the file system is mounted, such as "/System/Volumes/Data". + /// + /// The corresponding C property is `f_mntonname`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public var mountPoint: FilePath { + withUnsafeBytes(of: rawValue.f_mntonname) { + FilePath(_nullTerminatedBytes: $0) + } + } + + /// The source of the mounted file system, such as "/dev/disk3s7". + /// + /// The corresponding C property is `f_mntfromname`. + /// - Note: Only available on Darwin and BSD. + @_alwaysEmitIntoClient + public var mountSource: FilePath { + withUnsafeBytes(of: rawValue.f_mntfromname) { + FilePath(_nullTerminatedBytes: $0) + } + } + #endif +} + +// MARK: - StatFS Equatable & Hashable + +@available(System 199, *) +extension StatFS { + /// Compares the meaningful file-system metadata fields of two `StatFS` values. + /// + /// Reserved/"spare" fields are not compared, and name buffers are compared + /// only up to their NUL terminators. + public static func == (lhs: Self, rhs: Self) -> Bool { + guard lhs.blockSize == rhs.blockSize, + lhs.totalBlocks == rhs.totalBlocks, + lhs.freeBlocks == rhs.freeBlocks, + lhs.availableBlocks == rhs.availableBlocks, + lhs.totalInodes == rhs.totalInodes, + lhs.freeInodes == rhs.freeInodes, + lhs.fileSystemID == rhs.fileSystemID, + lhs.mountFlags == rhs.mountFlags else { + return false + } + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + guard lhs.preferredIOBlockSize == rhs.preferredIOBlockSize else { + return false + } + #else + guard lhs.fragmentSize == rhs.fragmentSize else { + return false + } + #endif + + #if !SYSTEM_PACKAGE_DARWIN && !os(FreeBSD) + guard lhs.availableInodes == rhs.availableInodes else { + return false + } + #endif + + #if !SYSTEM_PACKAGE_DARWIN + guard lhs.maximumNameLength == rhs.maximumNameLength else { + return false + } + #endif + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) + guard lhs.type == rhs.type else { + return false + } + #endif + + #if SYSTEM_PACKAGE_DARWIN + guard lhs.subtype == rhs.subtype else { + return false + } + #endif + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + guard lhs.owner == rhs.owner, + _nullTerminatedBytesEqual(lhs.rawValue.f_fstypename, + rhs.rawValue.f_fstypename), + _nullTerminatedBytesEqual(lhs.rawValue.f_mntonname, + rhs.rawValue.f_mntonname), + _nullTerminatedBytesEqual(lhs.rawValue.f_mntfromname, + rhs.rawValue.f_mntfromname) else { + return false + } + #endif + + return true + } + + /// Hashes the meaningful file-system metadata fields of a `StatFS` struct. + /// + /// These are the same fields compared by `==`. Reserved/"spare" fields are + /// not hashed, and name buffers are hashed only up to their NUL terminators. + public func hash(into hasher: inout Hasher) { + hasher.combine(blockSize) + hasher.combine(totalBlocks) + hasher.combine(freeBlocks) + hasher.combine(availableBlocks) + hasher.combine(totalInodes) + hasher.combine(freeInodes) + hasher.combine(fileSystemID) + hasher.combine(mountFlags) + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + hasher.combine(preferredIOBlockSize) + #else + hasher.combine(fragmentSize) + #endif + + #if !SYSTEM_PACKAGE_DARWIN && !os(FreeBSD) + hasher.combine(availableInodes) + #endif + + #if !SYSTEM_PACKAGE_DARWIN + hasher.combine(maximumNameLength) + #endif + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) + hasher.combine(type) + #endif + + #if SYSTEM_PACKAGE_DARWIN + hasher.combine(subtype) + #endif + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + hasher.combine(owner) + Self._combineNullTerminatedBytes(rawValue.f_fstypename, into: &hasher) + Self._combineNullTerminatedBytes(rawValue.f_mntonname, into: &hasher) + Self._combineNullTerminatedBytes(rawValue.f_mntfromname, into: &hasher) + #endif + } + + // Compares two fixed-size, NUL-terminated C character buffers (such as + // `f_mntonname`) up to their first NUL terminator. + @inline(__always) + private static func _nullTerminatedBytesEqual(_ lhs: T, _ rhs: T) -> Bool { + withUnsafeBytes(of: lhs) { lhsBytes in + withUnsafeBytes(of: rhs) { rhsBytes in + lhsBytes.prefix { $0 != 0 }.elementsEqual(rhsBytes.prefix { $0 != 0 }) + } + } + } + + // Hashes a fixed-size, NUL-terminated C character buffer (such as + // `f_mntonname`) up to its first NUL terminator. + @inline(__always) + private static func _combineNullTerminatedBytes( + _ value: T, into hasher: inout Hasher + ) { + withUnsafeBytes(of: value) { buffer in + let bytes = buffer.prefix { $0 != 0 } + hasher.combine(bytes: .init(rebasing: bytes)) + } + } +} + +// MARK: - FileDescriptor Extensions + +@available(System 199, *) +extension FileDescriptor { + + /// Creates a `StatFS` for the file system containing the file referenced by + /// this `FileDescriptor`. + /// + /// The corresponding C function is `fstatfs()` on Darwin and BSD, or + /// `fstatvfs()` otherwise. + @_alwaysEmitIntoClient + public func statfs( + retryOnInterrupt: Bool = true + ) throws(Errno) -> StatFS { + try StatFS(self, retryOnInterrupt: retryOnInterrupt) + } +} + +// MARK: - FilePath Extensions + +@available(System 199, *) +extension FilePath { + + /// Creates a `StatFS` for the file system containing the file referenced by + /// this `FilePath`. + /// + /// The corresponding C function is `statfs()` on Darwin and BSD, or + /// `statvfs()` otherwise. + @_alwaysEmitIntoClient + public func statfs( + retryOnInterrupt: Bool = true + ) throws(Errno) -> StatFS { + try StatFS(self, retryOnInterrupt: retryOnInterrupt) + } +} + +#endif // !os(Windows) diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index 5570d1e..0b786ea 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -116,4 +116,27 @@ extension CInterop { public typealias FileFlags = UInt32 #endif } + +@available(System 199, *) +extension CInterop { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + public typealias StatFS = statfs + #else + public typealias StatFS = statvfs + #endif + + #if SYSTEM_PACKAGE_DARWIN || os(OpenBSD) + public typealias MountFlags = UInt32 + #elseif os(FreeBSD) + public typealias MountFlags = UInt64 + #else + public typealias MountFlags = CUnsignedLong + #endif + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + public typealias FileSystemID = fsid_t + #else + public typealias FileSystemID = CUnsignedLong + #endif +} #endif diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 7a2ad9a..1986a7f 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -796,4 +796,350 @@ internal var _UF_SYSTEM: UInt32 { UInt32(bitPattern: UF_SYSTEM) } internal var _SF_SNAPSHOT: UInt32 { UInt32(bitPattern: SF_SNAPSHOT) } #endif +// MARK: - statfs/statvfs Mount Flags + +// Darwin and BSD (`statfs`) and other platforms (`statvfs`) use different C +// names (`MNT_*` vs `ST_*`) for the flags they share, so flags are exposed +// here under general `_MOUNT_*` names that resolve per platform. + +// MARK: Flags Available on All Platforms + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MOUNT_RDONLY: CInterop.MountFlags { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + CInterop.MountFlags(truncatingIfNeeded: MNT_RDONLY) + #elseif os(Linux) || os(Android) + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_RDONLY()) + #else + CInterop.MountFlags(truncatingIfNeeded: ST_RDONLY) + #endif +} + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MOUNT_SYNCHRONOUS: CInterop.MountFlags { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + CInterop.MountFlags(truncatingIfNeeded: MNT_SYNCHRONOUS) + #elseif os(Linux) || os(Android) + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_SYNCHRONOUS()) + #else + CInterop.MountFlags(truncatingIfNeeded: ST_SYNCHRONOUS) + #endif +} + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MOUNT_NOEXEC: CInterop.MountFlags { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + CInterop.MountFlags(truncatingIfNeeded: MNT_NOEXEC) + #elseif os(Linux) || os(Android) + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NOEXEC()) + #else + CInterop.MountFlags(truncatingIfNeeded: ST_NOEXEC) + #endif +} + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MOUNT_NOSUID: CInterop.MountFlags { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + CInterop.MountFlags(truncatingIfNeeded: MNT_NOSUID) + #elseif os(Linux) || os(Android) + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NOSUID()) + #else + CInterop.MountFlags(truncatingIfNeeded: ST_NOSUID) + #endif +} + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MOUNT_NOATIME: CInterop.MountFlags { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + CInterop.MountFlags(truncatingIfNeeded: MNT_NOATIME) + #elseif os(Linux) || os(Android) + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NOATIME()) + #else + CInterop.MountFlags(truncatingIfNeeded: ST_NOATIME) + #endif +} + +// MARK: Flags Available on All Platforms Except FreeBSD + +#if !os(FreeBSD) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MOUNT_NODEV: CInterop.MountFlags { + #if SYSTEM_PACKAGE_DARWIN || os(OpenBSD) + CInterop.MountFlags(truncatingIfNeeded: MNT_NODEV) + #elseif os(Linux) || os(Android) + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NODEV()) + #else + CInterop.MountFlags(truncatingIfNeeded: ST_NODEV) + #endif +} +#endif + +// MARK: Flags Available on Linux, WASI, and Android + +#if os(Linux) || os(WASI) || os(Android) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_MANDLOCK: CInterop.MountFlags { + #if os(WASI) + CInterop.MountFlags(truncatingIfNeeded: ST_MANDLOCK) + #else + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_MANDLOCK()) + #endif +} + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_NODIRATIME: CInterop.MountFlags { + #if os(WASI) + CInterop.MountFlags(truncatingIfNeeded: ST_NODIRATIME) + #else + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NODIRATIME()) + #endif +} + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_RELATIME: CInterop.MountFlags { + #if os(WASI) + CInterop.MountFlags(truncatingIfNeeded: ST_RELATIME) + #else + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_RELATIME()) + #endif +} +#endif + +// MARK: Flags Available on Linux and WASI Only + +#if os(Linux) || os(WASI) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_WRITE: CInterop.MountFlags { + #if os(WASI) + CInterop.MountFlags(truncatingIfNeeded: ST_WRITE) + #else + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_WRITE()) + #endif +} + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_APPEND: CInterop.MountFlags { + #if os(WASI) + CInterop.MountFlags(truncatingIfNeeded: ST_APPEND) + #else + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_APPEND()) + #endif +} + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_IMMUTABLE: CInterop.MountFlags { + #if os(WASI) + CInterop.MountFlags(truncatingIfNeeded: ST_IMMUTABLE) + #else + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_IMMUTABLE()) + #endif +} +#endif + +// MARK: Flags Available on Linux, Android, and FreeBSD + +#if os(Linux) || os(Android) || os(FreeBSD) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MOUNT_NOSYMFOLLOW: CInterop.MountFlags { + #if os(FreeBSD) + CInterop.MountFlags(truncatingIfNeeded: MNT_NOSYMFOLLOW) + #else + CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NOSYMFOLLOW()) + #endif +} +#endif + +// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD + +#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_ASYNC: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ASYNC) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_EXPORTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPORTED) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_LOCAL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_LOCAL) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_QUOTA: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_QUOTA) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_ROOTFS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ROOTFS) } +#endif + +// MARK: Flags Available on Darwin and FreeBSD + +#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_UNION: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_UNION) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_AUTOMOUNTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_AUTOMOUNTED) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_MULTILABEL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_MULTILABEL) } +#endif + +// MARK: Flags Available on FreeBSD and OpenBSD + +#if os(FreeBSD) || os(OpenBSD) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_EXRDONLY: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXRDONLY) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_DEFEXPORTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DEFEXPORTED) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_EXPORTANON: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPORTANON) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_SOFTDEP: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SOFTDEP) } +#endif + +// MARK: Flags Available on Darwin Only + +#if SYSTEM_PACKAGE_DARWIN +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_CPROTECT: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_CPROTECT) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_REMOVABLE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_REMOVABLE) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_QUARANTINE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_QUARANTINE) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_DOVOLFS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DOVOLFS) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_DONTBROWSE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DONTBROWSE) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_IGNORE_OWNERSHIP: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_IGNORE_OWNERSHIP) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_JOURNALED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_JOURNALED) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_NOUSERXATTR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOUSERXATTR) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_DEFWRITE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DEFWRITE) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_NOFOLLOW: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOFOLLOW) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_SNAPSHOT: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SNAPSHOT) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_STRICTATIME: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_STRICTATIME) } +#endif + +// MARK: Flags Available on FreeBSD Only + +#if os(FreeBSD) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_EXKERB: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXKERB) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_EXPUBLIC: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPUBLIC) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_ACLS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ACLS) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_GJOURNAL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_GJOURNAL) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_IGNORE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_IGNORE) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_NFS4ACLS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NFS4ACLS) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_NOCLUSTERR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOCLUSTERR) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_NOCLUSTERW: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOCLUSTERW) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_SUIDDIR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SUIDDIR) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_SUJ: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SUJ) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_UNTRUSTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_UNTRUSTED) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_USER: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_USER) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_VERIFIED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_VERIFIED) } +#endif + +// MARK: Flags Available on OpenBSD Only + +#if os(OpenBSD) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_NOPERM: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOPERM) } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _MNT_WXALLOWED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_WXALLOWED) } +#endif + #endif // !os(Windows) diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index 6ce7d4d..e3d6d49 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -108,6 +108,26 @@ internal func system_fstat(_ fd: CInt, _ s: inout CInterop.Stat) -> Int32 { internal func system_fstatat(_ fd: CInt, _ p: UnsafePointer, _ s: inout CInterop.Stat, _ flags: CInt) -> Int32 { fstatat(fd, p, &s, flags) } + +#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) +@available(System 199, *) +internal func system_statfs(_ p: UnsafePointer, _ s: inout CInterop.StatFS) -> Int32 { + statfs(p, &s) +} +@available(System 199, *) +internal func system_fstatfs(_ fd: CInt, _ s: inout CInterop.StatFS) -> Int32 { + fstatfs(fd, &s) +} +#else +@available(System 199, *) +internal func system_statvfs(_ p: UnsafePointer, _ s: inout CInterop.StatFS) -> Int32 { + statvfs(p, &s) +} +@available(System 199, *) +internal func system_fstatvfs(_ fd: CInt, _ s: inout CInterop.StatFS) -> Int32 { + fstatvfs(fd, &s) +} +#endif #endif // Convention: `system_platform_foo` is a diff --git a/Tests/SystemTests/StatFSTests.swift b/Tests/SystemTests/StatFSTests.swift new file mode 100644 index 0000000..84c7cfd --- /dev/null +++ b/Tests/SystemTests/StatFSTests.swift @@ -0,0 +1,475 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift System open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift System project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !os(Windows) + +import Testing + +#if canImport(Foundation) +import Foundation +#endif + +#if SYSTEM_PACKAGE_DARWIN +import Darwin +#elseif canImport(Glibc) +import CSystem +import Glibc +#elseif canImport(Musl) +import CSystem +import Musl +#elseif canImport(WASILibc) +import CSystem +import WASILibc +#elseif canImport(Android) +import Android +#else +#error("Unsupported Platform") +#endif + +#if SYSTEM_PACKAGE +@testable import SystemPackage +#else +@testable import System +#endif + +@Suite("StatFS") +private struct StatFSTests { + + // On WASI, statvfs/fstatvfs are unconditional stubs that set ENOSYS and + // return -1, so every StatFS initializer throws Errno.noFunction. Skip the + // behavioral tests there. + #if !os(WASI) + + @available(System 199, *) + @Test func initializersAgree() async throws { + try withTemporaryFilePath(basename: "StatFS_initializersAgree") { tempDir in + let fromFilePath = try StatFS(tempDir) + let fromCString = try tempDir.withPlatformString { try StatFS($0) } + let fromFilePathExt = try tempDir.statfs() + + let dirFD = try FileDescriptor.open(tempDir, .readOnly) + defer { try? dirFD.close() } + let fromFD = try StatFS(dirFD) + let fromFDExt = try dirFD.statfs() + + // All construction paths describe the same file system. + #expect(fromFilePath.fileSystemID == fromCString.fileSystemID) + #expect(fromFilePath.fileSystemID == fromFilePathExt.fileSystemID) + #expect(fromFilePath.fileSystemID == fromFD.fileSystemID) + #expect(fromFilePath.fileSystemID == fromFDExt.fileSystemID) + + #expect(fromFilePath.blockSize == fromFD.blockSize) + #expect(fromFilePath.totalBlocks == fromFD.totalBlocks) + #expect(fromFilePath.mountFlags == fromFD.mountFlags) + } + } + + @available(System 199, *) + @Test func spaceAndBlocks() async throws { + try withTemporaryFilePath(basename: "StatFS_spaceAndBlocks") { tempDir in + let statfs = try StatFS(tempDir) + + #expect(statfs.blockSize > 0) + #expect(statfs.totalBlocks > 0) + + // Free space cannot exceed the total, and available (non-superuser) + // cannot exceed the total free. + #expect(statfs.freeBlocks <= statfs.totalBlocks) + #expect(statfs.availableBlocks <= statfs.freeBlocks) + + // Computed sizes are the block count times the block-count unit. + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + let unit = UInt64(statfs.blockSize) + #else + let unit = UInt64(statfs.fragmentSize) + #endif + #expect(statfs.totalSpace == statfs.totalBlocks * unit) + #expect(statfs.freeSpace == statfs.freeBlocks * unit) + #expect(statfs.availableSpace == statfs.availableBlocks * unit) + + #expect(statfs.totalSpace >= statfs.freeSpace) + #expect(statfs.freeSpace >= statfs.availableSpace) + } + } + + @available(System 199, *) + @Test func spaceSaturatesOnOverflow() async throws { + try withTemporaryFilePath(basename: "StatFS_saturates") { tempDir in + var statfs = try StatFS(tempDir) + statfs.totalBlocks = .max + #expect(statfs.blockSize > 1) + // Max blocks times a >1 unit overflows UInt64 and must saturate. + #expect(statfs.totalSpace == .max) + } + } + + @available(System 199, *) + @Test func inodes() async throws { + try withTemporaryFilePath(basename: "StatFS_inodes") { tempDir in + let statfs = try StatFS(tempDir) + // totalInodes can legitimately be 0 on file systems with dynamic inode + // allocation, so only assert the ordering when it is nonzero. + #expect(statfs.freeInodes <= statfs.totalInodes || statfs.totalInodes == 0) + #if !SYSTEM_PACKAGE_DARWIN && !os(FreeBSD) + #expect(statfs.availableInodes <= statfs.freeInodes) + #endif + } + } + + @available(System 199, *) + @Test func readOnlyFlagReflectsWritableFileSystem() async throws { + try withTemporaryFilePath(basename: "StatFS_readOnly") { tempDir in + let statfs = try StatFS(tempDir) + + // Create and write a file in the temp dir. If this succeeds, + // the file system is not read-only... + let probe = tempDir.appending("probe") + let fd = try FileDescriptor.open( + probe, .readWrite, options: .create, permissions: .ownerReadWrite) + defer { try? fd.close() } + try fd.writeAll("probe".utf8) + + // ...so the read-only mount flag must be clear. + #expect(!statfs.mountFlags.contains(.readOnly)) + } + } + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + @available(System 199, *) + @Test func darwinAndBSDFields() async throws { + try withTemporaryFilePath(basename: "StatFS_darwinBSD") { tempDir in + let statfs = try StatFS(tempDir) + #expect(statfs.preferredIOBlockSize > 0) + + // `typeName` is a non-empty, readable file system name. + #expect(!statfs.typeName.isEmpty) + + // `mountPoint` is some absolute path, and `mountSource` is a non-empty + // device path. Note that on Darwin, firmlinks mean the temp dir path is + // not necessarily a lexical prefix of its mount point, so don't assert + // that relationship. + #expect(statfs.mountPoint.isAbsolute) + #expect(!statfs.mountSource.string.isEmpty) + + // statfs of the mount point itself reports that same mount point. + let mountStatFS = try StatFS(statfs.mountPoint) + #expect(mountStatFS.mountPoint == statfs.mountPoint) + #expect(mountStatFS.typeName == statfs.typeName) + } + } + #endif + + #if SYSTEM_PACKAGE_DARWIN + @available(System 199, *) + @Test func typeAndSubtypeRoundTrip() throws { + // On Darwin, `type` and `subtype` are opaque kernel indices with no stable + // public constants, so we can only assert that mutation round-trips. + var statfs = StatFS(rawValue: CInterop.StatFS()) + statfs.type = FileSystemType(rawValue: 42) + #expect(statfs.type == FileSystemType(42)) + statfs.subtype = FileSystemSubtype(rawValue: 7) + #expect(statfs.subtype == FileSystemSubtype(7)) + } + #endif + + @available(System 199, *) + @Test func nonexistentPathThrows() async throws { + #expect(throws: Errno.noSuchFileOrDirectory) { + _ = try StatFS("/var/empty/definitely/does/not/exist") + } + #expect(throws: Errno.noSuchFileOrDirectory) { + _ = try StatFS(FilePath("/var/empty/definitely/does/not/exist")) + } + #expect(throws: Errno.noSuchFileOrDirectory) { + _ = try FilePath("/var/empty/definitely/does/not/exist").statfs() + } + } + + @available(System 199, *) + @Test func badFileDescriptorThrows() async throws { + let badFD = FileDescriptor(rawValue: -1) + #expect(throws: Errno.badFileDescriptor) { + _ = try StatFS(badFD) + } + #expect(throws: Errno.badFileDescriptor) { + _ = try badFD.statfs() + } + } + + @available(System 199, *) + @Test func propertiesMatchRawFields() async throws { + // Verify property mappings from the raw C struct + try withTemporaryFilePath(basename: "StatFS_diff") { tempDir in + var raw = CInterop.StatFS() + try tempDir.withPlatformString { + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + try #require(statfs($0, &raw) == 0, "\(Errno.current)") + #else + try #require(statvfs($0, &raw) == 0, "\(Errno.current)") + #endif + } + let s = StatFS(rawValue: raw) + + #expect(s.blockSize == Int(raw.f_bsize)) + #expect(s.totalBlocks == UInt64(clamping: raw.f_blocks)) + #expect(s.freeBlocks == UInt64(clamping: raw.f_bfree)) + #expect(s.availableBlocks == UInt64(clamping: raw.f_bavail)) + #expect(s.totalInodes == UInt64(clamping: raw.f_files)) + #expect(s.freeInodes == UInt64(clamping: raw.f_ffree)) + + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + #expect(s.preferredIOBlockSize == Int(raw.f_iosize)) + #expect(s.owner.rawValue == raw.f_owner) + #expect(s.mountFlags.rawValue == raw.f_flags) + // Decode independently with `String(cString:)`, not the implementation's + // own helper, so this checks the decode rather than restating it. + #expect(s.typeName == withUnsafeBytes(of: raw.f_fstypename) { + $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } + }) + #expect(s.mountPoint.string == withUnsafeBytes(of: raw.f_mntonname) { + $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } + }) + #expect(s.mountSource.string == withUnsafeBytes(of: raw.f_mntfromname) { + $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } + }) + #else + #expect(s.fragmentSize == Int(raw.f_frsize)) + #expect(s.availableInodes == UInt64(clamping: raw.f_favail)) + #expect(s.maximumNameLength == Int(raw.f_namemax)) + #expect(s.mountFlags.rawValue == raw.f_flag) + #endif + } + } + + #endif // !os(WASI) + + @available(System 199, *) + @Test func propertiesAndRawValueRoundTrip() throws { + var raw = CInterop.StatFS() + raw.f_bsize = 4096 + var statfs = StatFS(rawValue: raw) + #expect(statfs.blockSize == 4096) + + statfs.blockSize = 8192 + #expect(statfs.blockSize == 8192) + #expect(statfs.rawValue.f_bsize == 8192) + + statfs.totalBlocks = 123456 + #expect(statfs.totalBlocks == 123456) + #expect(statfs.rawValue.f_blocks == 123456) + + statfs.mountFlags.insert(.readOnly) + #expect(statfs.mountFlags.contains(.readOnly)) + } + + // Setters clamp to the field's range instead of trapping. If the field is + // 64-bit the write round-trips; if it's narrower the value clamps to the + // field's max. Either way, setting `UInt64.max` should never trap or wrap + // to a small value. + @available(System 199, *) + @Test func settersClamp() throws { + var statfs = StatFS(rawValue: CInterop.StatFS()) + + statfs.totalBlocks = .max + #expect(statfs.totalBlocks >= UInt64(UInt32.max)) + + statfs.blockSize = .max + #expect(statfs.blockSize > 0) + + // Writing 0 always fits and reads back exactly. + statfs.freeBlocks = 0 + #expect(statfs.freeBlocks == 0) + } + + @available(System 199, *) + @Test func craftedStructComputesSpace() throws { + var raw = CInterop.StatFS() + // The block-count unit is f_bsize on Darwin/BSD, f_frsize on statvfs. + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + raw.f_bsize = 512 + #else + raw.f_bsize = 4096 // Should not be used in calculations + raw.f_frsize = 512 + #endif + raw.f_blocks = 1000 + raw.f_bfree = 400 + raw.f_bavail = 100 + + let s = StatFS(rawValue: raw) + #expect(s.totalSpace == 1000 * 512) + #expect(s.freeSpace == 400 * 512) + #expect(s.availableSpace == 100 * 512) + } + + #if os(FreeBSD) || os(OpenBSD) + // The block/inode-count fields are signed here; negatives clamp to 0. + @available(System 199, *) + @Test func negativeCountsClampToZero() throws { + var raw = CInterop.StatFS() + raw.f_bsize = 512 + raw.f_bavail = -1 + raw.f_ffree = -1 + + let s = StatFS(rawValue: raw) + #expect(s.availableBlocks == 0) + #expect(s.availableSpace == 0) + #expect(s.freeInodes == 0) + } + #endif + + #if os(Linux) + // /proc files report size 0 via stat, so read until EOF instead of getting + // the size up front. + private func _readEntireFile(_ path: String) throws -> String { + let fd = try FileDescriptor.open(FilePath(path), .readOnly) + defer { try? fd.close() } + var result = [UInt8]() + var chunk = [UInt8](repeating: 0, count: 64 * 1024) + while true { + let n = try chunk.withUnsafeMutableBytes { try fd.read(into: $0) } + if n == 0 { break } + result.append(contentsOf: chunk[..] = [:] + for line in contents.split(separator: "\n") { + let fields = line.split(separator: " ") + guard fields.count >= 4 else { continue } + let mountPoint = String(fields[1]) + // Skip octal-escaped paths (spaces, tabs, etc.). + if mountPoint.contains(where: { $0 == "\\" }) { continue } + mounts[mountPoint] = Set(fields[3].split(separator: ",").map(String.init)) + } + + // Match whole options, so "errors=remount-ro" doesn't look like "ro". + let checks: [(option: String, flag: MountFlags)] = [ + ("ro", .readOnly), + ("noexec", .noExecution), + ("nosuid", .noSetUserID), + ("nodev", .noDevices), + ("noatime", .noAccessTime), + ] + + var verified = 0 + for (mountPoint, options) in mounts { + guard let statfs = try? StatFS(FilePath(mountPoint)) else { continue } + for (option, flag) in checks { + #expect( + statfs.mountFlags.contains(flag) == options.contains(option), + "\(mountPoint): flag \(flag) disagrees with options \(options)" + ) + } + verified += 1 + } + + // Guard against a parser that silently matched nothing: "/" always works. + #expect(verified > 0) + } + #endif + + #if os(WASI) + @available(System 199, *) + @Test func wasiThrowsNoFunction() async throws { + // wasi-libc's statvfs is a stub that always fails with ENOSYS. + #expect(throws: Errno.noFunction) { + _ = try StatFS("/") + } + } + #endif + + @available(System 199, *) + @Test func fileSystemIDConformances() throws { + let a = FileSystemID(rawValue: CInterop.FileSystemID()) + let b = FileSystemID(rawValue: CInterop.FileSystemID()) + #expect(a == b) + #expect(a.hashValue == b.hashValue) + + // Codable round-trips, including the manual fsid_t implementation on + // Darwin and BSD. + #if canImport(Foundation) + let statfs = try? StatFS(FilePath("/")) + if let id = statfs?.fileSystemID { + let data = try JSONEncoder().encode(id) + let decoded = try JSONDecoder().decode(FileSystemID.self, from: data) + #expect(decoded == id) + #expect(decoded.hashValue == id.hashValue) + } + #endif + } + + @available(System 199, *) + @Test func mountFlagsIsOptionSet() throws { + var flags: MountFlags = [.readOnly, .noExecution] + #expect(flags.contains(.readOnly)) + #expect(flags.contains(.noExecution)) + #expect(!flags.contains(.synchronous)) + + flags.remove(.readOnly) + #expect(!flags.contains(.readOnly)) + + let empty = MountFlags(rawValue: 0) + #expect(empty.isEmpty) + } + + #if !os(WASI) + @available(System 199, *) + @Test func equalityAndHashing() throws { + try withTemporaryFilePath(basename: "StatFS_equality") { tempDir in + let statfs = try StatFS(tempDir) + let copy = statfs + #expect(statfs == copy) + #expect(statfs.hashValue == copy.hashValue) + #expect(Set([statfs, copy]).count == 1) + + var mutated = statfs + mutated.totalBlocks &+= 1 + #expect(statfs != mutated) + + // Reserved fields are not part of the value. + #if SYSTEM_PACKAGE_DARWIN + var reserved = statfs + reserved.rawValue.f_reserved.0 &+= 1 + #expect(statfs == reserved) + #expect(statfs.hashValue == reserved.hashValue) + #endif + + // Name buffers are read only up to their NUL terminator, so bytes past + // it don't affect the value. + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + var trailing = statfs + try withUnsafeMutableBytes(of: &trailing.rawValue.f_mntonname) { buffer in + // The kernel always NUL-terminates the name buffers. + let terminator = try #require(buffer.firstIndex(of: 0)) + if terminator + 1 < buffer.count { + buffer[terminator + 1] &+= 1 + } + } + #expect(statfs == trailing) + #expect(statfs.hashValue == trailing.hashValue) + #endif + } + } + #endif + +} + +#endif From b2237390d8f8b03720ce9a06fd9a033148290771 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Thu, 23 Jul 2026 13:58:25 -0600 Subject: [PATCH 2/8] Define ST_NOSYMFOLLOW for older Linux versions --- Sources/CSystem/shims.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c index a477bbb..343895f 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -37,6 +37,13 @@ uint64_t _system_get_ST_MANDLOCK(void) { return ST_MANDLOCK; } uint64_t _system_get_ST_NOATIME(void) { return ST_NOATIME; } uint64_t _system_get_ST_NODIRATIME(void) { return ST_NODIRATIME; } uint64_t _system_get_ST_RELATIME(void) { return ST_RELATIME; } + +// ST_NOSYMFOLLOW was added to glibc's in Linux 5.10. For +// older versions, fall back to the fixed kernel UAPI bit (), +// which is the same value a newer glibc header defines. +#ifndef ST_NOSYMFOLLOW +#define ST_NOSYMFOLLOW 0x2000 +#endif uint64_t _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; } #if !defined(__ANDROID__) From 292eb444424093988584a0e294537a25188f6b08 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Thu, 23 Jul 2026 14:10:12 -0600 Subject: [PATCH 3/8] Add missing CSystem import on Android --- Sources/System/Internals/Constants.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 1986a7f..966d5ee 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -23,6 +23,7 @@ import Musl #elseif canImport(WASILibc) import WASILibc #elseif canImport(Android) +import CSystem import Android #else #error("Unsupported Platform") From 9a9b78e4e93c509e0576d7dd0e0c45b332edaad5 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Thu, 23 Jul 2026 14:36:08 -0600 Subject: [PATCH 4/8] Include statvfs.h in CSystemWASI --- Sources/CSystem/include/CSystemWASI.h | 4 ++++ Sources/System/FileSystem/StatFS.swift | 1 + Sources/System/Internals/CInterop.swift | 1 + Sources/System/Internals/Exports.swift | 1 + 4 files changed, 7 insertions(+) diff --git a/Sources/CSystem/include/CSystemWASI.h b/Sources/CSystem/include/CSystemWASI.h index 1c8cd0f..7ad6d05 100644 --- a/Sources/CSystem/include/CSystemWASI.h +++ b/Sources/CSystem/include/CSystemWASI.h @@ -16,6 +16,10 @@ #include #include // For NAME_MAX +// wasi-libc ships , but the Swift WASILibc module does not +// surface it. Re-export them through CSystem here. +#include + // wasi-libc defines the following constants in a way that Clang Importer can't // understand, so we need to expose them manually. static inline int32_t _getConst_O_ACCMODE(void) { return O_ACCMODE; } diff --git a/Sources/System/FileSystem/StatFS.swift b/Sources/System/FileSystem/StatFS.swift index b653328..91618f1 100644 --- a/Sources/System/FileSystem/StatFS.swift +++ b/Sources/System/FileSystem/StatFS.swift @@ -49,6 +49,7 @@ import Glibc import CSystem import Musl #elseif canImport(WASILibc) +import CSystem import WASILibc #elseif canImport(Android) import CSystem diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index 0b786ea..119b549 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -19,6 +19,7 @@ import Glibc import CSystem import Musl #elseif canImport(WASILibc) +import CSystem import WASILibc #elseif canImport(Bionic) import CSystem diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index e3d6d49..401dba2 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -24,6 +24,7 @@ import Glibc import CSystem import Musl #elseif canImport(WASILibc) +@_implementationOnly import CSystem import WASILibc #elseif canImport(Android) import CSystem From cf36a2fe7bfce5a41d12db16003e6d02796a0773 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Wed, 30 Sep 2026 15:30:18 -0600 Subject: [PATCH 5/8] v2: Use `statfs` on Linux and Android, make `StatFS` unavailable on WASI, omit Linux flags the kernel never reports, add descriptions for `MountFlags` and `FileSystemID`, and back-deploy `CInterop.StatFS` with `CInterop.statfs(_:_:)` for migration --- Package.swift | 8 +- Sources/CMakeLists.txt | 3 + Sources/CSystem/include/CSystemLinux.h | 10 +- Sources/CSystem/include/CSystemWASI.h | 4 - Sources/CSystem/shims.c | 16 +- Sources/CSystemStatFS/CMakeLists.txt | 19 + Sources/CSystemStatFS/CSystemStatFS.h | 18 + Sources/CSystemStatFS/module.modulemap | 4 + Sources/System/CMakeLists.txt | 4 + Sources/System/FileSystem/MountFlags.swift | 414 +++++++++++------ Sources/System/FileSystem/StatFS.swift | 513 +++++++++++++-------- Sources/System/Internals/CInterop.swift | 42 +- Sources/System/Internals/Constants.swift | 151 +++--- Sources/System/Internals/Exports.swift | 18 +- Tests/MemberImportVisibility/Probe.swift | 22 + Tests/SystemTests/StatFSTests.swift | 339 +++++++------- 16 files changed, 958 insertions(+), 627 deletions(-) create mode 100644 Sources/CSystemStatFS/CMakeLists.txt create mode 100644 Sources/CSystemStatFS/CSystemStatFS.h create mode 100644 Sources/CSystemStatFS/module.modulemap diff --git a/Package.swift b/Package.swift index 7d5471a..8398c20 100644 --- a/Package.swift +++ b/Package.swift @@ -125,9 +125,15 @@ let package = Package( dependencies: [], exclude: ["CMakeLists.txt"], cSettings: cSettings), + .systemLibrary( + name: "CSystemStatFS", + path: "Sources/CSystemStatFS"), .target( name: "SystemPackage", - dependencies: ["CSystem"], + dependencies: [ + "CSystem", + .target(name: "CSystemStatFS", condition: .when(platforms: [.linux])), + ], path: "Sources/System", exclude: filesToExclude, cSettings: cSettings, diff --git a/Sources/CMakeLists.txt b/Sources/CMakeLists.txt index d788b8c..c23a961 100644 --- a/Sources/CMakeLists.txt +++ b/Sources/CMakeLists.txt @@ -8,4 +8,7 @@ See https://swift.org/LICENSE.txt for license information #]] add_subdirectory(CSystem) +if(CMAKE_SYSTEM_NAME STREQUAL Linux) + add_subdirectory(CSystemStatFS) +endif() add_subdirectory(System) diff --git a/Sources/CSystem/include/CSystemLinux.h b/Sources/CSystem/include/CSystemLinux.h index 5176f20..5c5c15f 100644 --- a/Sources/CSystem/include/CSystemLinux.h +++ b/Sources/CSystem/include/CSystemLinux.h @@ -21,9 +21,8 @@ #include #include "io_uring.h" -// The `ST_*` mount-flag constants in require _GNU_SOURCE. -// Rather than define _GNU_SOURCE module-wide, which clashes with SwiftGlibc, -// expose them through these getters, defined in shims.c under _GNU_SOURCE. +// Test-only: libc's `ST_*` values, which glibc gates on _GNU_SOURCE. Defining +// that here would clash with SwiftGlibc, so shims.c defines it instead. #include uint64_t _system_get_ST_RDONLY(void); uint64_t _system_get_ST_NOSUID(void); @@ -35,10 +34,5 @@ uint64_t _system_get_ST_NOATIME(void); uint64_t _system_get_ST_NODIRATIME(void); uint64_t _system_get_ST_RELATIME(void); uint64_t _system_get_ST_NOSYMFOLLOW(void); -#if !defined(__ANDROID__) -uint64_t _system_get_ST_WRITE(void); -uint64_t _system_get_ST_APPEND(void); -uint64_t _system_get_ST_IMMUTABLE(void); -#endif #endif diff --git a/Sources/CSystem/include/CSystemWASI.h b/Sources/CSystem/include/CSystemWASI.h index 7ad6d05..1c8cd0f 100644 --- a/Sources/CSystem/include/CSystemWASI.h +++ b/Sources/CSystem/include/CSystemWASI.h @@ -16,10 +16,6 @@ #include #include // For NAME_MAX -// wasi-libc ships , but the Swift WASILibc module does not -// surface it. Re-export them through CSystem here. -#include - // wasi-libc defines the following constants in a way that Clang Importer can't // understand, so we need to expose them manually. static inline int32_t _getConst_O_ACCMODE(void) { return O_ACCMODE; } diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c index 343895f..077e42a 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -19,11 +19,6 @@ #endif #ifdef __linux__ - -// The `ST_*` mount-flag constants in require _GNU_SOURCE. -// Define it here, in a dedicated translation unit, not in CSystemLinux.h, -// since defining it there changes libc types like `fd_set` for every file -// that imports CSystem and conflicts with SwiftGlibc. #define _GNU_SOURCE #include #include @@ -38,20 +33,13 @@ uint64_t _system_get_ST_NOATIME(void) { return ST_NOATIME; } uint64_t _system_get_ST_NODIRATIME(void) { return ST_NODIRATIME; } uint64_t _system_get_ST_RELATIME(void) { return ST_RELATIME; } -// ST_NOSYMFOLLOW was added to glibc's in Linux 5.10. For -// older versions, fall back to the fixed kernel UAPI bit (), -// which is the same value a newer glibc header defines. +// ST_NOSYMFOLLOW wasn't defined until glibc 2.34. 0x2000 is the bit the +// kernel's internal and newer glibc both use. #ifndef ST_NOSYMFOLLOW #define ST_NOSYMFOLLOW 0x2000 #endif uint64_t _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; } -#if !defined(__ANDROID__) -uint64_t _system_get_ST_WRITE(void) { return ST_WRITE; } -uint64_t _system_get_ST_APPEND(void) { return ST_APPEND; } -uint64_t _system_get_ST_IMMUTABLE(void) { return ST_IMMUTABLE; } -#endif - #include #endif diff --git a/Sources/CSystemStatFS/CMakeLists.txt b/Sources/CSystemStatFS/CMakeLists.txt new file mode 100644 index 0000000..c0ffb2b --- /dev/null +++ b/Sources/CSystemStatFS/CMakeLists.txt @@ -0,0 +1,19 @@ +#[[ +This source file is part of the Swift System open source project + +Copyright (c) 2026 Apple Inc. and the Swift System project authors +Licensed under Apache License v2.0 with Runtime Library Exception + +See https://swift.org/LICENSE.txt for license information +#]] + +add_library(CSystemStatFS INTERFACE) +target_include_directories(CSystemStatFS INTERFACE + "$" + $) + +install(FILES + CSystemStatFS.h + module.modulemap + DESTINATION include/CSystemStatFS) +set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystemStatFS) diff --git a/Sources/CSystemStatFS/CSystemStatFS.h b/Sources/CSystemStatFS/CSystemStatFS.h new file mode 100644 index 0000000..fee8d1c --- /dev/null +++ b/Sources/CSystemStatFS/CSystemStatFS.h @@ -0,0 +1,18 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2026 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +#pragma once + +// Unlike the Musl and Android modules, Glibc doesn't export , +// which declares `struct statfs` and `statfs()`/`fstatfs()`. SystemPackage +// re-exports this module on glibc platforms so that clients can use the +// raw `CInterop.StatFS` value under MemberImportVisibility. +#if defined(__linux__) && !defined(__ANDROID__) +#include +#endif diff --git a/Sources/CSystemStatFS/module.modulemap b/Sources/CSystemStatFS/module.modulemap new file mode 100644 index 0000000..3cb1557 --- /dev/null +++ b/Sources/CSystemStatFS/module.modulemap @@ -0,0 +1,4 @@ +module CSystemStatFS [system] { + header "CSystemStatFS.h" + export * +} diff --git a/Sources/System/CMakeLists.txt b/Sources/System/CMakeLists.txt index 73d8098..d254354 100644 --- a/Sources/System/CMakeLists.txt +++ b/Sources/System/CMakeLists.txt @@ -84,6 +84,10 @@ target_sources(SystemPackage PRIVATE Internals/WindowsSyscallAdapters.swift) target_link_libraries(SystemPackage PUBLIC CSystem) +if(CMAKE_SYSTEM_NAME STREQUAL Linux) + target_link_libraries(SystemPackage PUBLIC + CSystemStatFS) +endif() set(SWIFT_SYSTEM_APPLE_PLATFORMS "Darwin" "iOS" "watchOS" "tvOS" "visionOS") if(CMAKE_SYSTEM_NAME IN_LIST SWIFT_SYSTEM_APPLE_PLATFORMS) diff --git a/Sources/System/FileSystem/MountFlags.swift b/Sources/System/FileSystem/MountFlags.swift index 622ef61..eef4a3f 100644 --- a/Sources/System/FileSystem/MountFlags.swift +++ b/Sources/System/FileSystem/MountFlags.swift @@ -9,74 +9,71 @@ // //===----------------------------------------------------------------------===// -// |-------------------------------------------------------------------------------------------------------------------------------------------| -// | Swift API to C Mapping | -// |-------------------------------------------------------------------------------------------------------------------------------------------| -// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android | WASI | -// |-----------------------------|----------------------|-----------------|-----------------|----------------|----------------|----------------| -// | readOnly | MNT_RDONLY | MNT_RDONLY | MNT_RDONLY | ST_RDONLY | ST_RDONLY | ST_RDONLY | -// | synchronous | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | ST_SYNCHRONOUS | ST_SYNCHRONOUS | ST_SYNCHRONOUS | -// | noExecution | MNT_NOEXEC | MNT_NOEXEC | MNT_NOEXEC | ST_NOEXEC | ST_NOEXEC | ST_NOEXEC | -// | noSetUserID | MNT_NOSUID | MNT_NOSUID | MNT_NOSUID | ST_NOSUID | ST_NOSUID | ST_NOSUID | -// | noAccessTime | MNT_NOATIME | MNT_NOATIME | MNT_NOATIME | ST_NOATIME | ST_NOATIME | ST_NOATIME | -// | noDevices | MNT_NODEV | N/A | MNT_NODEV | ST_NODEV | ST_NODEV | ST_NODEV | -// | mandatoryLockingPermitted | N/A | N/A | N/A | ST_MANDLOCK | ST_MANDLOCK | ST_MANDLOCK | -// | noDirectoryAccessTime | N/A | N/A | N/A | ST_NODIRATIME | ST_NODIRATIME | ST_NODIRATIME | -// | relativeAccessTime | N/A | N/A | N/A | ST_RELATIME | ST_RELATIME | ST_RELATIME | -// | write | N/A | N/A | N/A | ST_WRITE | N/A | ST_WRITE | -// | appendOnly | N/A | N/A | N/A | ST_APPEND | N/A | ST_APPEND | -// | immutable | N/A | N/A | N/A | ST_IMMUTABLE | N/A | ST_IMMUTABLE | -// | noSymlinkFollow | N/A | MNT_NOSYMFOLLOW | N/A | ST_NOSYMFOLLOW | ST_NOSYMFOLLOW | N/A | -// | asynchronous | MNT_ASYNC | MNT_ASYNC | MNT_ASYNC | N/A | N/A | N/A | -// | exported | MNT_EXPORTED | MNT_EXPORTED | MNT_EXPORTED | N/A | N/A | N/A | -// | local | MNT_LOCAL | MNT_LOCAL | MNT_LOCAL | N/A | N/A | N/A | -// | quota | MNT_QUOTA | MNT_QUOTA | MNT_QUOTA | N/A | N/A | N/A | -// | rootFileSystem | MNT_ROOTFS | MNT_ROOTFS | MNT_ROOTFS | N/A | N/A | N/A | -// | union | MNT_UNION | MNT_UNION | N/A | N/A | N/A | N/A | -// | automounted | MNT_AUTOMOUNTED | MNT_AUTOMOUNTED | N/A | N/A | N/A | N/A | -// | multiLabel | MNT_MULTILABEL | MNT_MULTILABEL | N/A | N/A | N/A | N/A | -// | exportedReadOnly | N/A | MNT_EXRDONLY | MNT_EXRDONLY | N/A | N/A | N/A | -// | exportedByDefault | N/A | MNT_DEFEXPORTED | MNT_DEFEXPORTED | N/A | N/A | N/A | -// | exportedAnonymously | N/A | MNT_EXPORTANON | MNT_EXPORTANON | N/A | N/A | N/A | -// | softUpdates | N/A | MNT_SOFTDEP | MNT_SOFTDEP | N/A | N/A | N/A | -// | contentProtection | MNT_CPROTECT | N/A | N/A | N/A | N/A | N/A | -// | removable | MNT_REMOVABLE | N/A | N/A | N/A | N/A | N/A | -// | quarantine | MNT_QUARANTINE | N/A | N/A | N/A | N/A | N/A | -// | volumeFileSystem | MNT_DOVOLFS | N/A | N/A | N/A | N/A | N/A | -// | noBrowsing | MNT_DONTBROWSE | N/A | N/A | N/A | N/A | N/A | -// | ignoreOwnership | MNT_IGNORE_OWNERSHIP | N/A | N/A | N/A | N/A | N/A | -// | journaled | MNT_JOURNALED | N/A | N/A | N/A | N/A | N/A | -// | noUserExtendedAttributes | MNT_NOUSERXATTR | N/A | N/A | N/A | N/A | N/A | -// | deferWrites | MNT_DEFWRITE | N/A | N/A | N/A | N/A | N/A | -// | noSymlinkFollowAtMountPoint | MNT_NOFOLLOW | N/A | N/A | N/A | N/A | N/A | -// | snapshot | MNT_SNAPSHOT | N/A | N/A | N/A | N/A | N/A | -// | strictAccessTime | MNT_STRICTATIME | N/A | N/A | N/A | N/A | N/A | -// | exportedKerberos | N/A | MNT_EXKERB | N/A | N/A | N/A | N/A | -// | exportedPublic | N/A | MNT_EXPUBLIC | N/A | N/A | N/A | N/A | -// | posixACLs | N/A | MNT_ACLS | N/A | N/A | N/A | N/A | -// | geomJournaled | N/A | MNT_GJOURNAL | N/A | N/A | N/A | N/A | -// | excludedFromDiskFreeReports | N/A | MNT_IGNORE | N/A | N/A | N/A | N/A | -// | nfs4ACLs | N/A | MNT_NFS4ACLS | N/A | N/A | N/A | N/A | -// | noClusterRead | N/A | MNT_NOCLUSTERR | N/A | N/A | N/A | N/A | -// | noClusterWrite | N/A | MNT_NOCLUSTERW | N/A | N/A | N/A | N/A | -// | setUserIDDirectory | N/A | MNT_SUIDDIR | N/A | N/A | N/A | N/A | -// | softUpdateJournaling | N/A | MNT_SUJ | N/A | N/A | N/A | N/A | -// | untrusted | N/A | MNT_UNTRUSTED | N/A | N/A | N/A | N/A | -// | mountedByUser | N/A | MNT_USER | N/A | N/A | N/A | N/A | -// | verified | N/A | MNT_VERIFIED | N/A | N/A | N/A | N/A | -// | noPermissionChecks | N/A | N/A | MNT_NOPERM | N/A | N/A | N/A | -// | writeExecuteAllowed | N/A | N/A | MNT_WXALLOWED | N/A | N/A | N/A | -// |-------------------------------------------------------------------------------------------------------------------------------------------| +// |--------------------------------------------------------------------------------------------------------------------------| +// | Swift API to C Mapping | +// |--------------------------------------------------------------------------------------------------------------------------| +// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android | +// |-----------------------------|----------------------|-----------------|-----------------|----------------|----------------| +// | readOnly | MNT_RDONLY | MNT_RDONLY | MNT_RDONLY | ST_RDONLY | ST_RDONLY | +// | synchronous | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | ST_SYNCHRONOUS | ST_SYNCHRONOUS | +// | noExecution | MNT_NOEXEC | MNT_NOEXEC | MNT_NOEXEC | ST_NOEXEC | ST_NOEXEC | +// | noSetUserID | MNT_NOSUID | MNT_NOSUID | MNT_NOSUID | ST_NOSUID | ST_NOSUID | +// | noAccessTime | MNT_NOATIME | MNT_NOATIME | MNT_NOATIME | ST_NOATIME | ST_NOATIME | +// | noDevices | MNT_NODEV | N/A | MNT_NODEV | ST_NODEV | ST_NODEV | +// | mandatoryLockingPermitted | N/A | N/A | N/A | ST_MANDLOCK | ST_MANDLOCK | +// | noDirectoryAccessTime | N/A | N/A | N/A | ST_NODIRATIME | ST_NODIRATIME | +// | relativeAccessTime | N/A | N/A | N/A | ST_RELATIME | ST_RELATIME | +// | noSymlinkFollow | N/A | MNT_NOSYMFOLLOW | N/A | ST_NOSYMFOLLOW | ST_NOSYMFOLLOW | +// | asynchronous | MNT_ASYNC | MNT_ASYNC | MNT_ASYNC | N/A | N/A | +// | exported | MNT_EXPORTED | MNT_EXPORTED | MNT_EXPORTED | N/A | N/A | +// | local | MNT_LOCAL | MNT_LOCAL | MNT_LOCAL | N/A | N/A | +// | quota | MNT_QUOTA | MNT_QUOTA | MNT_QUOTA | N/A | N/A | +// | rootFileSystem | MNT_ROOTFS | MNT_ROOTFS | MNT_ROOTFS | N/A | N/A | +// | union | MNT_UNION | MNT_UNION | N/A | N/A | N/A | +// | automounted | MNT_AUTOMOUNTED | MNT_AUTOMOUNTED | N/A | N/A | N/A | +// | multiLabel | MNT_MULTILABEL | MNT_MULTILABEL | N/A | N/A | N/A | +// | exportedReadOnly | N/A | MNT_EXRDONLY | MNT_EXRDONLY | N/A | N/A | +// | exportedByDefault | N/A | MNT_DEFEXPORTED | MNT_DEFEXPORTED | N/A | N/A | +// | exportedAnonymously | N/A | MNT_EXPORTANON | MNT_EXPORTANON | N/A | N/A | +// | softUpdates | N/A | MNT_SOFTDEP | MNT_SOFTDEP | N/A | N/A | +// | contentProtection | MNT_CPROTECT | N/A | N/A | N/A | N/A | +// | removable | MNT_REMOVABLE | N/A | N/A | N/A | N/A | +// | quarantine | MNT_QUARANTINE | N/A | N/A | N/A | N/A | +// | volumeFileSystem | MNT_DOVOLFS | N/A | N/A | N/A | N/A | +// | noBrowsing | MNT_DONTBROWSE | N/A | N/A | N/A | N/A | +// | ignoreOwnership | MNT_IGNORE_OWNERSHIP | N/A | N/A | N/A | N/A | +// | journaled | MNT_JOURNALED | N/A | N/A | N/A | N/A | +// | noUserExtendedAttributes | MNT_NOUSERXATTR | N/A | N/A | N/A | N/A | +// | deferWrites | MNT_DEFWRITE | N/A | N/A | N/A | N/A | +// | noSymlinkFollowAtMountPoint | MNT_NOFOLLOW | N/A | N/A | N/A | N/A | +// | snapshot | MNT_SNAPSHOT | N/A | N/A | N/A | N/A | +// | strictAccessTime | MNT_STRICTATIME | N/A | N/A | N/A | N/A | +// | exportedKerberos | N/A | MNT_EXKERB | N/A | N/A | N/A | +// | exportedPublic | N/A | MNT_EXPUBLIC | N/A | N/A | N/A | +// | posixACLs | N/A | MNT_ACLS | N/A | N/A | N/A | +// | geomJournaled | N/A | MNT_GJOURNAL | N/A | N/A | N/A | +// | excludedFromDiskFreeReports | N/A | MNT_IGNORE | N/A | N/A | N/A | +// | nfs4ACLs | N/A | MNT_NFS4ACLS | N/A | N/A | N/A | +// | noClusterRead | N/A | MNT_NOCLUSTERR | N/A | N/A | N/A | +// | noClusterWrite | N/A | MNT_NOCLUSTERW | N/A | N/A | N/A | +// | setUserIDDirectory | N/A | MNT_SUIDDIR | N/A | N/A | N/A | +// | softUpdateJournaling | N/A | MNT_SUJ | N/A | N/A | N/A | +// | untrusted | N/A | MNT_UNTRUSTED | N/A | N/A | N/A | +// | mountedByUser | N/A | MNT_USER | N/A | N/A | N/A | +// | verified | N/A | MNT_VERIFIED | N/A | N/A | N/A | +// | noPermissionChecks | N/A | N/A | MNT_NOPERM | N/A | N/A | +// | writeExecuteAllowed | N/A | N/A | MNT_WXALLOWED | N/A | N/A | +// |--------------------------------------------------------------------------------------------------------------------------| -#if !os(Windows) +#if !os(Windows) && !os(WASI) -/// Options employed when mounting a file system. +/// Flags describing a mounted file system. /// -/// These are the flags reported in the `f_flags` field of a `statfs` struct on -/// Darwin and BSD, or the `f_flag` field of a `statvfs` struct on other -/// platforms. +/// These are the flags reported in the `f_flags` field of a `statfs` struct. +/// Some reflect options employed when mounting the file system, while others, +/// like `local` and `rootFileSystem`, describe state the kernel reports. /// -/// - Note: Only available on Unix-like platforms. +/// - Note: Not available on Windows or WASI. @frozen @available(System 199, *) public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @@ -121,10 +118,11 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// Access times are not updated on the file system. /// - /// The corresponding C constant is `MNT_NOATIME` on Darwin and BSD, - /// or `ST_NOATIME` otherwise. /// - Note: On OpenBSD, access time may still be updated when the /// modification or status-change time is also being updated. + /// + /// The corresponding C constant is `MNT_NOATIME` on Darwin and BSD, + /// or `ST_NOATIME` otherwise. @_alwaysEmitIntoClient public static var noAccessTime: MountFlags { MountFlags(rawValue: _MOUNT_NOATIME) } @@ -133,77 +131,56 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { #if !os(FreeBSD) /// Special files may not be interpreted on the file system. /// + /// - Note: Not available on FreeBSD. + /// /// The corresponding C constant is `MNT_NODEV` on Darwin and OpenBSD, /// or `ST_NODEV` otherwise. - /// - Note: Not available on FreeBSD. @_alwaysEmitIntoClient public static var noDevices: MountFlags { MountFlags(rawValue: _MOUNT_NODEV) } #endif - // MARK: Flags Available on Linux, WASI, and Android + // MARK: Flags Available on Linux and Android - #if os(Linux) || os(WASI) || os(Android) + // Glibc and musl also define `ST_WRITE`, `ST_APPEND`, and `ST_IMMUTABLE`, but + // Linux never reports them in `f_flags`, so they have no corresponding flag. + + #if os(Linux) || os(Android) /// The file system permits mandatory file locking. /// - /// The corresponding C constant is `ST_MANDLOCK`. - /// - Note: Only available on Linux, WASI, and Android. + /// - Note: Only available on Linux and Android. /// - Note: Mandatory locking was deprecated and removed in Linux 5.15. + /// + /// The corresponding C constant is `ST_MANDLOCK`. @_alwaysEmitIntoClient public static var mandatoryLockingPermitted: MountFlags { MountFlags(rawValue: _ST_MANDLOCK) } /// Directory access times are not updated on the file system. /// + /// - Note: Only available on Linux and Android. + /// /// The corresponding C constant is `ST_NODIRATIME`. - /// - Note: Only available on Linux, WASI, and Android. @_alwaysEmitIntoClient public static var noDirectoryAccessTime: MountFlags { MountFlags(rawValue: _ST_NODIRATIME) } /// The access time is only updated if it's earlier than or equal to the file's /// last modification or status-change time, or if it's more than a day old. /// + /// - Note: Only available on Linux and Android. + /// /// The corresponding C constant is `ST_RELATIME`. - /// - Note: Only available on Linux, WASI, and Android. @_alwaysEmitIntoClient public static var relativeAccessTime: MountFlags { MountFlags(rawValue: _ST_RELATIME) } #endif - // MARK: Flags Available on Linux and WASI Only - - #if os(Linux) || os(WASI) - /// Files, directories, and symbolic links on the file system are writable. - /// - /// The corresponding C constant is `ST_WRITE`. - /// - Note: Only available on Linux and WASI. - @_alwaysEmitIntoClient - public static var write: MountFlags { MountFlags(rawValue: _ST_WRITE) } - - /// Files on the file system are append-only. - /// - /// The corresponding C constant is `ST_APPEND`. - /// - Note: Only available on Linux and WASI. - @_alwaysEmitIntoClient - public static var appendOnly: MountFlags { MountFlags(rawValue: _ST_APPEND) } - - /// Files on the file system are immutable. - /// - /// The corresponding C constant is `ST_IMMUTABLE`. - /// - Note: Only available on Linux and WASI. - @_alwaysEmitIntoClient - public static var immutable: MountFlags { MountFlags(rawValue: _ST_IMMUTABLE) } - #endif - // MARK: Flags Available on Linux, Android, and FreeBSD #if os(Linux) || os(Android) || os(FreeBSD) /// Symbolic links are not followed when resolving paths on the file system. /// - /// Unlike Darwin's `noSymlinkFollowAtMountPoint`, this suppresses symlink - /// following for all path resolution on the mount, not just when resolving - /// the mount point. + /// - Note: Only available on Linux, Android, and FreeBSD. /// /// The corresponding C constant is `MNT_NOSYMFOLLOW` on FreeBSD, /// or `ST_NOSYMFOLLOW` on Linux and Android. - /// - Note: Only available on Linux, Android, and FreeBSD. @_alwaysEmitIntoClient public static var noSymlinkFollow: MountFlags { MountFlags(rawValue: _MOUNT_NOSYMFOLLOW) } #endif @@ -213,36 +190,41 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) /// The file system is written to asynchronously. /// - /// The corresponding C constant is `MNT_ASYNC`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C constant is `MNT_ASYNC`. @_alwaysEmitIntoClient public static var asynchronous: MountFlags { MountFlags(rawValue: _MNT_ASYNC) } /// The file system is exported for use over the network via NFS. /// - /// The corresponding C constant is `MNT_EXPORTED`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C constant is `MNT_EXPORTED`. @_alwaysEmitIntoClient public static var exported: MountFlags { MountFlags(rawValue: _MNT_EXPORTED) } /// The file system is stored locally, rather than being accessed over a network. /// - /// The corresponding C constant is `MNT_LOCAL`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C constant is `MNT_LOCAL`. @_alwaysEmitIntoClient public static var local: MountFlags { MountFlags(rawValue: _MNT_LOCAL) } /// Quotas are enabled on the file system. /// - /// The corresponding C constant is `MNT_QUOTA`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C constant is `MNT_QUOTA`. @_alwaysEmitIntoClient public static var quota: MountFlags { MountFlags(rawValue: _MNT_QUOTA) } /// The file system is the root file system. /// - /// The corresponding C constant is `MNT_ROOTFS`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C constant is `MNT_ROOTFS`. @_alwaysEmitIntoClient public static var rootFileSystem: MountFlags { MountFlags(rawValue: _MNT_ROOTFS) } #endif @@ -253,23 +235,26 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// The file system is unioned with the underlying file system, rather than /// obscuring it. /// - /// The corresponding C constant is `MNT_UNION`. /// - Note: Only available on Darwin and FreeBSD. + /// + /// The corresponding C constant is `MNT_UNION`. @_alwaysEmitIntoClient public static var union: MountFlags { MountFlags(rawValue: _MNT_UNION) } /// The file system was mounted by the automounter. /// + /// - Note: Only available on Darwin and FreeBSD. See `automount(8)`. + /// /// The corresponding C constant is `MNT_AUTOMOUNTED`. - /// - Note: Only available on Darwin and FreeBSD. See `autofs(4)`. @_alwaysEmitIntoClient public static var automounted: MountFlags { MountFlags(rawValue: _MNT_AUTOMOUNTED) } /// The file system supports Mandatory Access Control (MAC) labels for /// individual objects. /// - /// The corresponding C constant is `MNT_MULTILABEL`. /// - Note: Only available on Darwin and FreeBSD. + /// + /// The corresponding C constant is `MNT_MULTILABEL`. @_alwaysEmitIntoClient public static var multiLabel: MountFlags { MountFlags(rawValue: _MNT_MULTILABEL) } #endif @@ -279,30 +264,34 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { #if os(FreeBSD) || os(OpenBSD) /// The file system is exported for reading only. /// - /// The corresponding C constant is `MNT_EXRDONLY`. /// - Note: Only available on FreeBSD and OpenBSD. + /// + /// The corresponding C constant is `MNT_EXRDONLY`. @_alwaysEmitIntoClient public static var exportedReadOnly: MountFlags { MountFlags(rawValue: _MNT_EXRDONLY) } /// The file system is exported for reading and writing to any host by default. /// - /// The corresponding C constant is `MNT_DEFEXPORTED`. /// - Note: Only available on FreeBSD and OpenBSD. + /// + /// The corresponding C constant is `MNT_DEFEXPORTED`. @_alwaysEmitIntoClient public static var exportedByDefault: MountFlags { MountFlags(rawValue: _MNT_DEFEXPORTED) } /// The file system maps all remote users to the anonymous user account. /// - /// The corresponding C constant is `MNT_EXPORTANON`. /// - Note: Only available on FreeBSD and OpenBSD. + /// + /// The corresponding C constant is `MNT_EXPORTANON`. @_alwaysEmitIntoClient public static var exportedAnonymously: MountFlags { MountFlags(rawValue: _MNT_EXPORTANON) } /// The file system uses soft updates. /// - /// The corresponding C constant is `MNT_SOFTDEP`. /// - Note: Only available on FreeBSD and OpenBSD. Accepted for compatibility /// on OpenBSD, but has no effect there. + /// + /// The corresponding C constant is `MNT_SOFTDEP`. @_alwaysEmitIntoClient public static var softUpdates: MountFlags { MountFlags(rawValue: _MNT_SOFTDEP) } #endif @@ -312,88 +301,99 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { #if SYSTEM_PACKAGE_DARWIN /// The file system supports per-file encrypted data protection. /// - /// The corresponding C constant is `MNT_CPROTECT`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_CPROTECT`. @_alwaysEmitIntoClient public static var contentProtection: MountFlags { MountFlags(rawValue: _MNT_CPROTECT) } /// The file system resides on removable media. /// - /// The corresponding C constant is `MNT_REMOVABLE`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_REMOVABLE`. @_alwaysEmitIntoClient public static var removable: MountFlags { MountFlags(rawValue: _MNT_REMOVABLE) } /// The file system is quarantined. /// - /// The corresponding C constant is `MNT_QUARANTINE`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_QUARANTINE`. @_alwaysEmitIntoClient public static var quarantine: MountFlags { MountFlags(rawValue: _MNT_QUARANTINE) } /// The file system supports volfs. /// + /// - Note: Only available on Darwin. Deprecated since Mac OS X 10.5. + /// /// The corresponding C constant is `MNT_DOVOLFS`. - /// - Note: Only available on Darwin. Deprecated since Mac OS X 10.5 and - /// not set on modern systems. @_alwaysEmitIntoClient public static var volumeFileSystem: MountFlags { MountFlags(rawValue: _MNT_DOVOLFS) } /// The file system should not be presented to the user for browsing /// (e.g. hidden in Finder). /// - /// The corresponding C constant is `MNT_DONTBROWSE`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_DONTBROWSE`. @_alwaysEmitIntoClient public static var noBrowsing: MountFlags { MountFlags(rawValue: _MNT_DONTBROWSE) } /// Ownership information on the file system is ignored. /// - /// The corresponding C constant is `MNT_IGNORE_OWNERSHIP`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_IGNORE_OWNERSHIP`. @_alwaysEmitIntoClient public static var ignoreOwnership: MountFlags { MountFlags(rawValue: _MNT_IGNORE_OWNERSHIP) } /// The file system is journaled. /// - /// The corresponding C constant is `MNT_JOURNALED`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_JOURNALED`. @_alwaysEmitIntoClient public static var journaled: MountFlags { MountFlags(rawValue: _MNT_JOURNALED) } /// User extended attributes are not allowed on the file system. /// - /// The corresponding C constant is `MNT_NOUSERXATTR`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_NOUSERXATTR`. @_alwaysEmitIntoClient public static var noUserExtendedAttributes: MountFlags { MountFlags(rawValue: _MNT_NOUSERXATTR) } /// The file system defers writes. /// - /// The corresponding C constant is `MNT_DEFWRITE`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_DEFWRITE`. @_alwaysEmitIntoClient public static var deferWrites: MountFlags { MountFlags(rawValue: _MNT_DEFWRITE) } /// Symbolic links are not followed when resolving the mount point. /// - /// The corresponding C constant is `MNT_NOFOLLOW`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_NOFOLLOW`. @_alwaysEmitIntoClient public static var noSymlinkFollowAtMountPoint: MountFlags { MountFlags(rawValue: _MNT_NOFOLLOW) } /// The mount is a snapshot. /// - /// The corresponding C constant is `MNT_SNAPSHOT`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_SNAPSHOT`. @_alwaysEmitIntoClient public static var snapshot: MountFlags { MountFlags(rawValue: _MNT_SNAPSHOT) } /// Access times are always updated on access. Relatime-style optimizations /// are disabled. /// - /// The corresponding C constant is `MNT_STRICTATIME`. /// - Note: Only available on Darwin. + /// + /// The corresponding C constant is `MNT_STRICTATIME`. @_alwaysEmitIntoClient public static var strictAccessTime: MountFlags { MountFlags(rawValue: _MNT_STRICTATIME) } #endif @@ -403,95 +403,107 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { #if os(FreeBSD) /// The file system is exported with Kerberos user-ID mapping. /// - /// The corresponding C constant is `MNT_EXKERB`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_EXKERB`. @_alwaysEmitIntoClient public static var exportedKerberos: MountFlags { MountFlags(rawValue: _MNT_EXKERB) } /// The file system is exported publicly for WebNFS clients. /// - /// The corresponding C constant is `MNT_EXPUBLIC`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_EXPUBLIC`. @_alwaysEmitIntoClient public static var exportedPublic: MountFlags { MountFlags(rawValue: _MNT_EXPUBLIC) } /// The file system supports POSIX.1e ACLs. /// - /// The corresponding C constant is `MNT_ACLS`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_ACLS`. @_alwaysEmitIntoClient public static var posixACLs: MountFlags { MountFlags(rawValue: _MNT_ACLS) } /// The file system uses `gjournal`. /// - /// The corresponding C constant is `MNT_GJOURNAL`. /// - Note: Only available on FreeBSD. See `gjournal(8)`. + /// + /// The corresponding C constant is `MNT_GJOURNAL`. @_alwaysEmitIntoClient public static var geomJournaled: MountFlags { MountFlags(rawValue: _MNT_GJOURNAL) } /// The file system is omitted from `df(1)` listings. /// - /// The corresponding C constant is `MNT_IGNORE`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_IGNORE`. @_alwaysEmitIntoClient public static var excludedFromDiskFreeReports: MountFlags { MountFlags(rawValue: _MNT_IGNORE) } /// The file system supports NFSv4 ACLs. /// - /// The corresponding C constant is `MNT_NFS4ACLS`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_NFS4ACLS`. @_alwaysEmitIntoClient public static var nfs4ACLs: MountFlags { MountFlags(rawValue: _MNT_NFS4ACLS) } /// Clustered reads are disabled on the file system. /// - /// The corresponding C constant is `MNT_NOCLUSTERR`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_NOCLUSTERR`. @_alwaysEmitIntoClient public static var noClusterRead: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERR) } /// Clustered writes are disabled on the file system. /// - /// The corresponding C constant is `MNT_NOCLUSTERW`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_NOCLUSTERW`. @_alwaysEmitIntoClient public static var noClusterWrite: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERW) } /// Newly created files in a directory with the set-user-ID bit set are owned /// by that directory's owner, rather than by the creating user. /// - /// The corresponding C constant is `MNT_SUIDDIR`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_SUIDDIR`. @_alwaysEmitIntoClient public static var setUserIDDirectory: MountFlags { MountFlags(rawValue: _MNT_SUIDDIR) } /// The file system uses soft updates with journaling. /// + /// - Note: Only available on FreeBSD. + /// /// The corresponding C constant is `MNT_SUJ`. - /// - Note: Only available on FreeBSD. Combines `softUpdates` with a journal - /// for fast recovery. @_alwaysEmitIntoClient public static var softUpdateJournaling: MountFlags { MountFlags(rawValue: _MNT_SUJ) } /// The file system is untrusted, as the integrity of its media is unknown. /// - /// The corresponding C constant is `MNT_UNTRUSTED`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_UNTRUSTED`. @_alwaysEmitIntoClient public static var untrusted: MountFlags { MountFlags(rawValue: _MNT_UNTRUSTED) } /// The file system was mounted by a non-root user. /// - /// The corresponding C constant is `MNT_USER`. /// - Note: Only available on FreeBSD. + /// + /// The corresponding C constant is `MNT_USER`. @_alwaysEmitIntoClient public static var mountedByUser: MountFlags { MountFlags(rawValue: _MNT_USER) } /// The file system is marked as verified, so per-file integrity checks are /// skipped on execution. /// - /// The corresponding C constant is `MNT_VERIFIED`. /// - Note: Only available on FreeBSD. See `mac_veriexec(4)`. + /// + /// The corresponding C constant is `MNT_VERIFIED`. @_alwaysEmitIntoClient public static var verified: MountFlags { MountFlags(rawValue: _MNT_VERIFIED) } #endif @@ -501,8 +513,9 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { #if os(OpenBSD) /// File permissions are not checked on the file system (FFS only). /// - /// The corresponding C constant is `MNT_NOPERM`. /// - Note: Only available on OpenBSD. + /// + /// The corresponding C constant is `MNT_NOPERM`. @_alwaysEmitIntoClient public static var noPermissionChecks: MountFlags { MountFlags(rawValue: _MNT_NOPERM) } @@ -512,11 +525,124 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// By default, requesting such a mapping (via `mmap(2)` or `mprotect(2)`) /// kills the process. This flag lifts that restriction. /// - /// The corresponding C constant is `MNT_WXALLOWED`. /// - Note: Only available on OpenBSD. + /// + /// The corresponding C constant is `MNT_WXALLOWED`. @_alwaysEmitIntoClient public static var writeExecuteAllowed: MountFlags { MountFlags(rawValue: _MNT_WXALLOWED) } #endif } -#endif // !os(Windows) +@available(System 199, *) +extension MountFlags + : CustomStringConvertible, CustomDebugStringConvertible +{ + /// A textual representation of the mount flags. + @inline(never) + public var description: String { + #if SYSTEM_PACKAGE_DARWIN + let descriptions: [(Element, StaticString)] = [ + (.readOnly, ".readOnly"), + (.synchronous, ".synchronous"), + (.noExecution, ".noExecution"), + (.noSetUserID, ".noSetUserID"), + (.noAccessTime, ".noAccessTime"), + (.noDevices, ".noDevices"), + (.asynchronous, ".asynchronous"), + (.exported, ".exported"), + (.local, ".local"), + (.quota, ".quota"), + (.rootFileSystem, ".rootFileSystem"), + (.union, ".union"), + (.automounted, ".automounted"), + (.multiLabel, ".multiLabel"), + (.contentProtection, ".contentProtection"), + (.removable, ".removable"), + (.quarantine, ".quarantine"), + (.volumeFileSystem, ".volumeFileSystem"), + (.noBrowsing, ".noBrowsing"), + (.ignoreOwnership, ".ignoreOwnership"), + (.journaled, ".journaled"), + (.noUserExtendedAttributes, ".noUserExtendedAttributes"), + (.deferWrites, ".deferWrites"), + (.noSymlinkFollowAtMountPoint, ".noSymlinkFollowAtMountPoint"), + (.snapshot, ".snapshot"), + (.strictAccessTime, ".strictAccessTime"), + ] + #elseif os(FreeBSD) + let descriptions: [(Element, StaticString)] = [ + (.readOnly, ".readOnly"), + (.synchronous, ".synchronous"), + (.noExecution, ".noExecution"), + (.noSetUserID, ".noSetUserID"), + (.noAccessTime, ".noAccessTime"), + (.noSymlinkFollow, ".noSymlinkFollow"), + (.asynchronous, ".asynchronous"), + (.exported, ".exported"), + (.local, ".local"), + (.quota, ".quota"), + (.rootFileSystem, ".rootFileSystem"), + (.union, ".union"), + (.automounted, ".automounted"), + (.multiLabel, ".multiLabel"), + (.exportedReadOnly, ".exportedReadOnly"), + (.exportedByDefault, ".exportedByDefault"), + (.exportedAnonymously, ".exportedAnonymously"), + (.softUpdates, ".softUpdates"), + (.exportedKerberos, ".exportedKerberos"), + (.exportedPublic, ".exportedPublic"), + (.posixACLs, ".posixACLs"), + (.geomJournaled, ".geomJournaled"), + (.excludedFromDiskFreeReports, ".excludedFromDiskFreeReports"), + (.nfs4ACLs, ".nfs4ACLs"), + (.noClusterRead, ".noClusterRead"), + (.noClusterWrite, ".noClusterWrite"), + (.setUserIDDirectory, ".setUserIDDirectory"), + (.softUpdateJournaling, ".softUpdateJournaling"), + (.untrusted, ".untrusted"), + (.mountedByUser, ".mountedByUser"), + (.verified, ".verified"), + ] + #elseif os(OpenBSD) + let descriptions: [(Element, StaticString)] = [ + (.readOnly, ".readOnly"), + (.synchronous, ".synchronous"), + (.noExecution, ".noExecution"), + (.noSetUserID, ".noSetUserID"), + (.noAccessTime, ".noAccessTime"), + (.noDevices, ".noDevices"), + (.asynchronous, ".asynchronous"), + (.exported, ".exported"), + (.local, ".local"), + (.quota, ".quota"), + (.rootFileSystem, ".rootFileSystem"), + (.exportedReadOnly, ".exportedReadOnly"), + (.exportedByDefault, ".exportedByDefault"), + (.exportedAnonymously, ".exportedAnonymously"), + (.softUpdates, ".softUpdates"), + (.noPermissionChecks, ".noPermissionChecks"), + (.writeExecuteAllowed, ".writeExecuteAllowed"), + ] + #elseif os(Linux) || os(Android) + let descriptions: [(Element, StaticString)] = [ + (.readOnly, ".readOnly"), + (.synchronous, ".synchronous"), + (.noExecution, ".noExecution"), + (.noSetUserID, ".noSetUserID"), + (.noAccessTime, ".noAccessTime"), + (.noDevices, ".noDevices"), + (.mandatoryLockingPermitted, ".mandatoryLockingPermitted"), + (.noDirectoryAccessTime, ".noDirectoryAccessTime"), + (.relativeAccessTime, ".relativeAccessTime"), + (.noSymlinkFollow, ".noSymlinkFollow"), + ] + #endif + + return _buildDescription(descriptions) + } + + /// A textual representation of the mount flags, suitable for debugging. + public var debugDescription: String { self.description } +} + +#endif // !os(Windows) && !os(WASI) diff --git a/Sources/System/FileSystem/StatFS.swift b/Sources/System/FileSystem/StatFS.swift index 91618f1..e052bf3 100644 --- a/Sources/System/FileSystem/StatFS.swift +++ b/Sources/System/FileSystem/StatFS.swift @@ -11,17 +11,40 @@ #if os(Windows) -/// A Swift wrapper of the C `statfs` struct on Darwin and BSD operating -/// systems, or the standard `statvfs` otherwise. +/// A Swift wrapper of the C `statfs` struct. /// -/// - Note: Only available on Unix-like platforms. -@available(Windows, unavailable, message: "StatFS is unavailable on Windows. Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") -public struct StatFS {} +/// - Note: Not available on Windows or WASI. +@available(Windows, unavailable, message: "Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") +public struct StatFS { + /// Creates a `StatFS` from a `FilePath`. + public init( + _ path: FilePath, + retryOnInterrupt: Bool = true + ) throws(Errno) { + fatalError("StatFS is unavailable on Windows") + } + + /// Creates a `StatFS` from a null-terminated `UnsafePointer` path. + public init( + _ path: UnsafePointer, + retryOnInterrupt: Bool = true + ) throws(Errno) { + fatalError("StatFS is unavailable on Windows") + } + + /// Creates a `StatFS` from a `FileDescriptor`. + public init( + _ fd: FileDescriptor, + retryOnInterrupt: Bool = true + ) throws(Errno) { + fatalError("StatFS is unavailable on Windows") + } +} extension FileDescriptor { /// Creates a `StatFS` for the file system containing the file referenced by /// this `FileDescriptor`. - @available(Windows, unavailable, message: "StatFS is unavailable on Windows. Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") + @available(Windows, unavailable, message: "Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { fatalError("StatFS is unavailable on Windows") } @@ -30,27 +53,76 @@ extension FileDescriptor { extension FilePath { /// Creates a `StatFS` for the file system containing the file referenced by /// this `FilePath`. - @available(Windows, unavailable, message: "StatFS is unavailable on Windows. Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") + @available(Windows, unavailable, message: "Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { fatalError("StatFS is unavailable on Windows") } } +#elseif os(WASI) + +/// A Swift wrapper of the C `statfs` struct. +/// +/// - Note: Not available on Windows or WASI. +@available(*, unavailable, message: "wasi-libc doesn't implement statfs or statvfs.") +public struct StatFS { + /// Creates a `StatFS` from a `FilePath`. + public init( + _ path: FilePath, + retryOnInterrupt: Bool = true + ) throws(Errno) { + fatalError("StatFS is unavailable on WASI") + } + + /// Creates a `StatFS` from a null-terminated `UnsafePointer` path. + public init( + _ path: UnsafePointer, + retryOnInterrupt: Bool = true + ) throws(Errno) { + fatalError("StatFS is unavailable on WASI") + } + + /// Creates a `StatFS` from a `FileDescriptor`. + public init( + _ fd: FileDescriptor, + retryOnInterrupt: Bool = true + ) throws(Errno) { + fatalError("StatFS is unavailable on WASI") + } +} + +extension FileDescriptor { + /// Creates a `StatFS` for the file system containing the file referenced by + /// this `FileDescriptor`. + @available(*, unavailable, message: "wasi-libc doesn't implement statfs or statvfs.") + public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { + fatalError("StatFS is unavailable on WASI") + } +} + +extension FilePath { + /// Creates a `StatFS` for the file system containing the file referenced by + /// this `FilePath`. + @available(*, unavailable, message: "wasi-libc doesn't implement statfs or statvfs.") + public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { + fatalError("StatFS is unavailable on WASI") + } +} + #else -// Must import here to use C statfs/statvfs properties in -// @_alwaysEmitIntoClient APIs. +// Must import here to use C statfs properties in @_alwaysEmitIntoClient APIs. #if SYSTEM_PACKAGE_DARWIN import Darwin #elseif canImport(Glibc) import CSystem +#if os(Linux) +import CSystemStatFS +#endif import Glibc #elseif canImport(Musl) import CSystem import Musl -#elseif canImport(WASILibc) -import CSystem -import WASILibc #elseif canImport(Android) import CSystem import Android @@ -60,8 +132,10 @@ import Android // MARK: - FileSystemID -/// A Swift wrapper of the C `f_fsid` file system ID found in a `statfs` or -/// `statvfs` struct. +/// A Swift wrapper of the C `f_fsid` file system ID found in a `statfs` +/// struct. +/// +/// - Note: Not available on Windows or WASI. @frozen @available(System 199, *) public struct FileSystemID: RawRepresentable, Sendable { @@ -79,17 +153,34 @@ public struct FileSystemID: RawRepresentable, Sendable { public init(_ rawValue: CInterop.FileSystemID) { self.rawValue = rawValue } } -// On Darwin, FreeBSD, and OpenBSD, `CInterop.FileSystemID` is the C `fsid_t` -// struct (a fixed two-element `int32_t` array), which provides no synthesized -// conformances. Implement `Equatable`, `Hashable`, and `Codable` manually in -// terms of the underlying `val` members. On other platforms, the raw value is -// an integer, so the conformances are derived automatically. -#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) +// `CInterop.FileSystemID` is the C `fsid_t` struct (a fixed two-element +// `int32_t` array), which provides no synthesized conformances. +@available(System 199, *) +extension FileSystemID { + @_alwaysEmitIntoClient + internal var _words: (Int32, Int32) { + #if os(Linux) || os(Android) + rawValue.__val + #else + rawValue.val + #endif + } + + @_alwaysEmitIntoClient + internal init(_words words: (Int32, Int32)) { + #if os(Linux) || os(Android) + self.init(rawValue: CInterop.FileSystemID(__val: words)) + #else + self.init(rawValue: CInterop.FileSystemID(val: words)) + #endif + } +} + @available(System 199, *) extension FileSystemID: Equatable { @_alwaysEmitIntoClient public static func == (lhs: Self, rhs: Self) -> Bool { - lhs.rawValue.val.0 == rhs.rawValue.val.0 && lhs.rawValue.val.1 == rhs.rawValue.val.1 + lhs._words.0 == rhs._words.0 && lhs._words.1 == rhs._words.1 } } @@ -97,8 +188,8 @@ extension FileSystemID: Equatable { extension FileSystemID: Hashable { @_alwaysEmitIntoClient public func hash(into hasher: inout Hasher) { - hasher.combine(rawValue.val.0) - hasher.combine(rawValue.val.1) + hasher.combine(_words.0) + hasher.combine(_words.1) } } @@ -107,8 +198,8 @@ extension FileSystemID: Codable { @_alwaysEmitIntoClient public func encode(to encoder: any Encoder) throws { var container = encoder.unkeyedContainer() - try container.encode(rawValue.val.0) - try container.encode(rawValue.val.1) + try container.encode(_words.0) + try container.encode(_words.1) } @_alwaysEmitIntoClient @@ -116,21 +207,29 @@ extension FileSystemID: Codable { var container = try decoder.unkeyedContainer() let val0 = try container.decode(Int32.self) let val1 = try container.decode(Int32.self) - self.init(rawValue: CInterop.FileSystemID(val: (val0, val1))) + self.init(_words: (val0, val1)) } } -#else -@available(System 199, *) -extension FileSystemID: Equatable, Hashable, Codable {} -#endif -#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) +@available(System 199, *) +extension FileSystemID: CustomStringConvertible, CustomDebugStringConvertible { + /// A textual representation of the file system ID. + @inline(never) + public var description: String { + "FileSystemID(\(_words.0), \(_words.1))" + } + + /// A textual representation of the file system ID, suitable for debugging. + public var debugDescription: String { self.description } +} + +#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(Linux) || os(Android) // MARK: - FileSystemType /// A Swift wrapper of the C `f_type` file system type found in a `statfs` -/// struct on Darwin and FreeBSD. +/// struct. /// -/// - Note: Only available on Darwin and FreeBSD. +/// - Note: Only available on Darwin, FreeBSD, Linux, and Android. @frozen @available(System 199, *) public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable { @@ -147,7 +246,7 @@ public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public init(_ rawValue: UInt32) { self.rawValue = rawValue } } -#endif +#endif // SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(Linux) || os(Android) #if SYSTEM_PACKAGE_DARWIN // MARK: - FileSystemSubtype @@ -214,18 +313,16 @@ extension FilePath { } #endif -/// A Swift wrapper of the C `statfs` struct on Darwin and BSD operating -/// systems, or the standard `statvfs` otherwise. +/// A Swift wrapper of the C `statfs` struct. /// -/// - Note: Only available on Unix-like platforms. -/// - Note: The numeric properties clamp to the range of the underlying C -/// field in both directions. Use `rawValue` for exact, unclamped access. +/// - Note: Not available on Windows or WASI. +/// - Note: The numeric properties clamp when converting to or from the +/// underlying C field. Use `rawValue` for exact, unclamped access. @frozen @available(System 199, *) public struct StatFS: RawRepresentable, Sendable, Hashable { - /// The raw C `statfs` struct on Darwin and BSD, or the `statvfs` struct - /// otherwise. + /// The raw C `statfs` struct. @_alwaysEmitIntoClient public var rawValue: CInterop.StatFS @@ -237,8 +334,7 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// Creates a `StatFS` from a `FilePath`. /// - /// The corresponding C function is `statfs()` on Darwin and BSD, or - /// `statvfs()` otherwise. + /// The corresponding C function is `statfs()`. @_alwaysEmitIntoClient public init( _ path: FilePath, @@ -251,8 +347,7 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// Creates a `StatFS` from a null-terminated `UnsafePointer` path. /// - /// The corresponding C function is `statfs()` on Darwin and BSD, or - /// `statvfs()` otherwise. + /// The corresponding C function is `statfs()`. @_alwaysEmitIntoClient public init( _ path: UnsafePointer, @@ -270,18 +365,13 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { ) -> Result { var result = CInterop.StatFS() return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) { - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) system_statfs(path, &result) - #else - system_statvfs(path, &result) - #endif }.map { result } } /// Creates a `StatFS` from a `FileDescriptor`. /// - /// The corresponding C function is `fstatfs()` on Darwin and BSD, or - /// `fstatvfs()` otherwise. + /// The corresponding C function is `fstatfs()`. @_alwaysEmitIntoClient public init( _ fd: FileDescriptor, @@ -299,11 +389,7 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { ) -> Result { var result = CInterop.StatFS() return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) { - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) system_fstatfs(fd.rawValue, &result) - #else - system_fstatvfs(fd.rawValue, &result) - #endif }.map { result } } @@ -311,9 +397,10 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// File system block size, in bytes. /// - /// The corresponding C property is `f_bsize`. /// - Note: On Darwin and BSD, this is the fundamental size for block counts. - /// `statvfs` platforms use `fragmentSize` (`f_frsize`) instead. + /// Other platforms use `fragmentSize` (`f_frsize`) instead. + /// + /// The corresponding C property is `f_bsize`. @_alwaysEmitIntoClient public var blockSize: Int { get { Int(clamping: rawValue.f_bsize) } @@ -323,8 +410,9 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) /// Block size for optimal data transfer, in bytes. /// - /// The corresponding C property is `f_iosize`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C property is `f_iosize`. @_alwaysEmitIntoClient public var preferredIOBlockSize: Int { get { Int(clamping: rawValue.f_iosize) } @@ -333,9 +421,10 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { #else /// File system fragment size, in bytes. /// - /// The corresponding C property is `f_frsize`. - /// - Note: On `statvfs` platforms, this is the fundamental size for block + /// - Note: On Linux and Android, this is the fundamental size for block /// counts. Not present on Darwin or BSD, which use `blockSize` instead. + /// + /// The corresponding C property is `f_frsize`. @_alwaysEmitIntoClient public var fragmentSize: Int { get { Int(clamping: rawValue.f_frsize) } @@ -345,8 +434,7 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// The fundamental block size used for space calculations, in bytes. /// - /// This is `blockSize` on Darwin and BSD (`statfs`), or `fragmentSize` - /// otherwise (`statvfs`). + /// This is `blockSize` on Darwin and BSD, or `fragmentSize` otherwise. @_alwaysEmitIntoClient internal var _fundamentalBlockSize: UInt64 { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) @@ -356,8 +444,6 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { #endif } - /// Multiplies a block count by the fundamental block size, saturating to - /// `UInt64.max` on overflow. @_alwaysEmitIntoClient internal func _saturatingSpace(_ blocks: UInt64) -> UInt64 { let (result, overflow) = blocks.multipliedReportingOverflow(by: _fundamentalBlockSize) @@ -366,9 +452,10 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// Total number of blocks in the file system. /// + /// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize` + /// otherwise. + /// /// The corresponding C property is `f_blocks`. - /// - Note: In units of `blockSize` on Darwin and BSD (`statfs`), or - /// `fragmentSize` otherwise (`statvfs`). @_alwaysEmitIntoClient public var totalBlocks: UInt64 { get { UInt64(clamping: rawValue.f_blocks) } @@ -384,9 +471,10 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// Number of free blocks in the file system. /// + /// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize` + /// otherwise. + /// /// The corresponding C property is `f_bfree`. - /// - Note: In units of `blockSize` on Darwin and BSD (`statfs`), or - /// `fragmentSize` otherwise (`statvfs`). @_alwaysEmitIntoClient public var freeBlocks: UInt64 { get { UInt64(clamping: rawValue.f_bfree) } @@ -402,10 +490,11 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// Number of free blocks available to non-superuser. /// + /// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize` + /// otherwise. On FreeBSD and OpenBSD, the underlying C property is + /// signed; negative values are clamped to 0. + /// /// The corresponding C property is `f_bavail`. - /// - Note: In units of `blockSize` on Darwin and BSD (`statfs`), or - /// `fragmentSize` otherwise (`statvfs`). On FreeBSD and OpenBSD, the - /// underlying C property is signed; negative values are clamped to 0. @_alwaysEmitIntoClient public var availableBlocks: UInt64 { get { UInt64(clamping: rawValue.f_bavail) } @@ -430,24 +519,26 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// Number of free inodes in the file system. /// - /// The corresponding C property is `f_ffree`. /// - Note: On FreeBSD, this reports the inodes available to a non-superuser /// rather than the total free count, and the underlying C field is signed /// (negative values are clamped to 0); on other platforms, it is the total /// number of free inodes. + /// + /// The corresponding C property is `f_ffree`. @_alwaysEmitIntoClient public var freeInodes: UInt64 { get { UInt64(clamping: rawValue.f_ffree) } set { rawValue.f_ffree = .init(clamping: newValue) } } - #if !SYSTEM_PACKAGE_DARWIN && !os(FreeBSD) + #if os(OpenBSD) /// Number of free inodes available to non-superuser. /// - /// The corresponding C property is `f_favail`, reported on the `statvfs` - /// platforms and by OpenBSD's `statfs`. - /// - Note: Darwin and FreeBSD `statfs` do not report it. On OpenBSD, the - /// underlying C property is signed; negative values are clamped to 0. + /// - Note: Darwin, FreeBSD, Linux, and Android `statfs` do not report it. + /// On OpenBSD, the underlying C property is signed; negative values are + /// clamped to 0. + /// + /// The corresponding C property is `f_favail`. @_alwaysEmitIntoClient public var availableInodes: UInt64 { get { UInt64(clamping: rawValue.f_favail) } @@ -458,13 +549,26 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { #if !SYSTEM_PACKAGE_DARWIN /// Maximum length of a file name on the file system, in bytes. /// - /// The corresponding C property is `f_namemax`, reported on the `statvfs` - /// platforms and by FreeBSD and OpenBSD `statfs`. /// - Note: Darwin's `statfs` does not report it. + /// + /// The corresponding C property is `f_namelen` on Linux and Android, or + /// `f_namemax` otherwise. @_alwaysEmitIntoClient public var maximumNameLength: Int { - get { Int(clamping: rawValue.f_namemax) } - set { rawValue.f_namemax = .init(clamping: newValue) } + get { + #if os(Linux) || os(Android) + Int(clamping: rawValue.f_namelen) + #else + Int(clamping: rawValue.f_namemax) + #endif + } + set { + #if os(Linux) || os(Android) + rawValue.f_namelen = .init(clamping: newValue) + #else + rawValue.f_namemax = .init(clamping: newValue) + #endif + } } #endif @@ -477,61 +581,83 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { set { rawValue.f_fsid = newValue.rawValue } } - /// Mount flags indicating the options employed when mounting the file system. + /// Flags describing how the file system is mounted. /// - /// The corresponding C property is `f_flags` on Darwin and BSD, or `f_flag` - /// otherwise. + /// - Note: On Linux, the kernel also sets an `ST_VALID` bit in `f_flags` + /// to mark the field as filled in. It isn't a mount flag, so this + /// property omits it like glibc's `statvfs` and Bionic's `statfs` do. + /// The setter preserves it. + /// + /// The corresponding C property is `f_flags`. @_alwaysEmitIntoClient public var mountFlags: MountFlags { get { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) MountFlags(rawValue: rawValue.f_flags) - #else - MountFlags(rawValue: rawValue.f_flag) + #elseif os(Linux) || os(Android) + MountFlags(rawValue: CInterop.MountFlags(truncatingIfNeeded: rawValue.f_flags) & ~_ST_VALID_BIT) #endif } set { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) rawValue.f_flags = newValue.rawValue - #else - rawValue.f_flag = newValue.rawValue + #elseif os(Linux) || os(Android) + let valid = CInterop.MountFlags(truncatingIfNeeded: rawValue.f_flags) & _ST_VALID_BIT + rawValue.f_flags = .init(truncatingIfNeeded: newValue.rawValue | valid) #endif } } - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(Linux) || os(Android) /// File system type. /// + /// - Note: On Linux and Android, this is the file system's magic number, + /// such as `0xEF53` for ext4. On Darwin and FreeBSD, it's an internal, + /// kernel-assigned VFS type index with no stable, public constants; + /// prefer `typeName` to identify the file system in a readable format. + /// Not available on OpenBSD. + /// /// The corresponding C property is `f_type`. - /// - Note: Only available on Darwin and FreeBSD, where this is an internal, - /// kernel-assigned VFS type index with no stable, public constants; it is - /// *not* a filesystem magic number like those found in the Linux `statfs`. - /// Prefer `typeName` to identify the file system in a readable format. @_alwaysEmitIntoClient public var type: FileSystemType { - get { FileSystemType(rawValue: numericCast(rawValue.f_type)) } - set { rawValue.f_type = numericCast(newValue.rawValue) } + get { + #if os(Linux) || os(Android) + // glibc's `f_type` is a signed `long` and can be negative. + FileSystemType(rawValue: UInt32(truncatingIfNeeded: rawValue.f_type)) + #else + FileSystemType(rawValue: rawValue.f_type) + #endif + } + set { + #if os(Linux) || os(Android) + rawValue.f_type = .init(truncatingIfNeeded: newValue.rawValue) + #else + rawValue.f_type = newValue.rawValue + #endif + } } #endif #if SYSTEM_PACKAGE_DARWIN /// File system subtype. /// - /// The corresponding C property is `f_fssubtype`. /// - Note: Like `type`, this is a numeric value with no stable, public /// constants. Only available on Darwin. + /// + /// The corresponding C property is `f_fssubtype`. @_alwaysEmitIntoClient public var subtype: FileSystemSubtype { - get { FileSystemSubtype(rawValue: numericCast(rawValue.f_fssubtype)) } - set { rawValue.f_fssubtype = numericCast(newValue.rawValue) } + get { FileSystemSubtype(rawValue: rawValue.f_fssubtype) } + set { rawValue.f_fssubtype = newValue.rawValue } } #endif #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) /// User that mounted the file system. /// - /// The corresponding C property is `f_owner`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C property is `f_owner`. @_alwaysEmitIntoClient public var owner: UserID { get { UserID(rawValue: rawValue.f_owner) } @@ -540,8 +666,9 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// File system type name. /// - /// The corresponding C property is `f_fstypename`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C property is `f_fstypename`. @_alwaysEmitIntoClient public var typeName: String { withUnsafeBytes(of: rawValue.f_fstypename) { @@ -551,8 +678,9 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// Directory where the file system is mounted, such as "/System/Volumes/Data". /// - /// The corresponding C property is `f_mntonname`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C property is `f_mntonname`. @_alwaysEmitIntoClient public var mountPoint: FilePath { withUnsafeBytes(of: rawValue.f_mntonname) { @@ -562,8 +690,9 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { /// The source of the mounted file system, such as "/dev/disk3s7". /// - /// The corresponding C property is `f_mntfromname`. /// - Note: Only available on Darwin and BSD. + /// + /// The corresponding C property is `f_mntfromname`. @_alwaysEmitIntoClient public var mountSource: FilePath { withUnsafeBytes(of: rawValue.f_mntfromname) { @@ -577,58 +706,28 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { @available(System 199, *) extension StatFS { - /// Compares the meaningful file-system metadata fields of two `StatFS` values. + /// Compares the file system metadata fields of two `StatFS` values, + /// including fields not exposed as properties, such as `f_flags_ext` on + /// Darwin. /// - /// Reserved/"spare" fields are not compared, and name buffers are compared + /// Fields are compared by their raw C values. Reserved/"spare" fields and + /// OpenBSD's `mount_info` union are not compared. Name buffers are compared /// only up to their NUL terminators. public static func == (lhs: Self, rhs: Self) -> Bool { - guard lhs.blockSize == rhs.blockSize, - lhs.totalBlocks == rhs.totalBlocks, - lhs.freeBlocks == rhs.freeBlocks, - lhs.availableBlocks == rhs.availableBlocks, - lhs.totalInodes == rhs.totalInodes, - lhs.freeInodes == rhs.freeInodes, - lhs.fileSystemID == rhs.fileSystemID, - lhs.mountFlags == rhs.mountFlags else { + guard lhs.rawValue.f_bsize == rhs.rawValue.f_bsize, + lhs.rawValue.f_blocks == rhs.rawValue.f_blocks, + lhs.rawValue.f_bfree == rhs.rawValue.f_bfree, + lhs.rawValue.f_bavail == rhs.rawValue.f_bavail, + lhs.rawValue.f_files == rhs.rawValue.f_files, + lhs.rawValue.f_ffree == rhs.rawValue.f_ffree, + lhs.fileSystemID == rhs.fileSystemID else { return false } #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) - guard lhs.preferredIOBlockSize == rhs.preferredIOBlockSize else { - return false - } - #else - guard lhs.fragmentSize == rhs.fragmentSize else { - return false - } - #endif - - #if !SYSTEM_PACKAGE_DARWIN && !os(FreeBSD) - guard lhs.availableInodes == rhs.availableInodes else { - return false - } - #endif - - #if !SYSTEM_PACKAGE_DARWIN - guard lhs.maximumNameLength == rhs.maximumNameLength else { - return false - } - #endif - - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) - guard lhs.type == rhs.type else { - return false - } - #endif - - #if SYSTEM_PACKAGE_DARWIN - guard lhs.subtype == rhs.subtype else { - return false - } - #endif - - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) - guard lhs.owner == rhs.owner, + guard lhs.rawValue.f_iosize == rhs.rawValue.f_iosize, + lhs.rawValue.f_flags == rhs.rawValue.f_flags, + lhs.rawValue.f_owner == rhs.rawValue.f_owner, _nullTerminatedBytesEqual(lhs.rawValue.f_fstypename, rhs.rawValue.f_fstypename), _nullTerminatedBytesEqual(lhs.rawValue.f_mntonname, @@ -637,57 +736,99 @@ extension StatFS { rhs.rawValue.f_mntfromname) else { return false } + #elseif os(Linux) || os(Android) + guard lhs.rawValue.f_type == rhs.rawValue.f_type, + lhs.rawValue.f_frsize == rhs.rawValue.f_frsize, + lhs.rawValue.f_flags == rhs.rawValue.f_flags, + lhs.rawValue.f_namelen == rhs.rawValue.f_namelen else { + return false + } + #endif + + #if SYSTEM_PACKAGE_DARWIN + guard lhs.rawValue.f_type == rhs.rawValue.f_type, + lhs.rawValue.f_fssubtype == rhs.rawValue.f_fssubtype, + lhs.rawValue.f_flags_ext == rhs.rawValue.f_flags_ext else { + return false + } + #elseif os(FreeBSD) + guard lhs.rawValue.f_version == rhs.rawValue.f_version, + lhs.rawValue.f_type == rhs.rawValue.f_type, + lhs.rawValue.f_namemax == rhs.rawValue.f_namemax, + lhs.rawValue.f_syncwrites == rhs.rawValue.f_syncwrites, + lhs.rawValue.f_asyncwrites == rhs.rawValue.f_asyncwrites, + lhs.rawValue.f_syncreads == rhs.rawValue.f_syncreads, + lhs.rawValue.f_asyncreads == rhs.rawValue.f_asyncreads else { + return false + } + #elseif os(OpenBSD) + guard lhs.rawValue.f_favail == rhs.rawValue.f_favail, + lhs.rawValue.f_namemax == rhs.rawValue.f_namemax, + lhs.rawValue.f_syncwrites == rhs.rawValue.f_syncwrites, + lhs.rawValue.f_syncreads == rhs.rawValue.f_syncreads, + lhs.rawValue.f_asyncwrites == rhs.rawValue.f_asyncwrites, + lhs.rawValue.f_asyncreads == rhs.rawValue.f_asyncreads, + lhs.rawValue.f_ctime == rhs.rawValue.f_ctime, + _nullTerminatedBytesEqual(lhs.rawValue.f_mntfromspec, + rhs.rawValue.f_mntfromspec) else { + return false + } #endif return true } - /// Hashes the meaningful file-system metadata fields of a `StatFS` struct. + /// Hashes the file system metadata fields of a `StatFS` struct. /// /// These are the same fields compared by `==`. Reserved/"spare" fields are /// not hashed, and name buffers are hashed only up to their NUL terminators. public func hash(into hasher: inout Hasher) { - hasher.combine(blockSize) - hasher.combine(totalBlocks) - hasher.combine(freeBlocks) - hasher.combine(availableBlocks) - hasher.combine(totalInodes) - hasher.combine(freeInodes) + hasher.combine(rawValue.f_bsize) + hasher.combine(rawValue.f_blocks) + hasher.combine(rawValue.f_bfree) + hasher.combine(rawValue.f_bavail) + hasher.combine(rawValue.f_files) + hasher.combine(rawValue.f_ffree) hasher.combine(fileSystemID) - hasher.combine(mountFlags) #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) - hasher.combine(preferredIOBlockSize) - #else - hasher.combine(fragmentSize) - #endif - - #if !SYSTEM_PACKAGE_DARWIN && !os(FreeBSD) - hasher.combine(availableInodes) - #endif - - #if !SYSTEM_PACKAGE_DARWIN - hasher.combine(maximumNameLength) - #endif - - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) - hasher.combine(type) - #endif - - #if SYSTEM_PACKAGE_DARWIN - hasher.combine(subtype) - #endif - - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) - hasher.combine(owner) + hasher.combine(rawValue.f_iosize) + hasher.combine(rawValue.f_flags) + hasher.combine(rawValue.f_owner) Self._combineNullTerminatedBytes(rawValue.f_fstypename, into: &hasher) Self._combineNullTerminatedBytes(rawValue.f_mntonname, into: &hasher) Self._combineNullTerminatedBytes(rawValue.f_mntfromname, into: &hasher) + #elseif os(Linux) || os(Android) + hasher.combine(rawValue.f_type) + hasher.combine(rawValue.f_frsize) + hasher.combine(rawValue.f_flags) + hasher.combine(rawValue.f_namelen) + #endif + + #if SYSTEM_PACKAGE_DARWIN + hasher.combine(rawValue.f_type) + hasher.combine(rawValue.f_fssubtype) + hasher.combine(rawValue.f_flags_ext) + #elseif os(FreeBSD) + hasher.combine(rawValue.f_version) + hasher.combine(rawValue.f_type) + hasher.combine(rawValue.f_namemax) + hasher.combine(rawValue.f_syncwrites) + hasher.combine(rawValue.f_asyncwrites) + hasher.combine(rawValue.f_syncreads) + hasher.combine(rawValue.f_asyncreads) + #elseif os(OpenBSD) + hasher.combine(rawValue.f_favail) + hasher.combine(rawValue.f_namemax) + hasher.combine(rawValue.f_syncwrites) + hasher.combine(rawValue.f_syncreads) + hasher.combine(rawValue.f_asyncwrites) + hasher.combine(rawValue.f_asyncreads) + hasher.combine(rawValue.f_ctime) + Self._combineNullTerminatedBytes(rawValue.f_mntfromspec, into: &hasher) #endif } - // Compares two fixed-size, NUL-terminated C character buffers (such as - // `f_mntonname`) up to their first NUL terminator. @inline(__always) private static func _nullTerminatedBytesEqual(_ lhs: T, _ rhs: T) -> Bool { withUnsafeBytes(of: lhs) { lhsBytes in @@ -697,14 +838,14 @@ extension StatFS { } } - // Hashes a fixed-size, NUL-terminated C character buffer (such as - // `f_mntonname`) up to its first NUL terminator. + // Feeds the length first so adjacent buffers can't run together. @inline(__always) private static func _combineNullTerminatedBytes( _ value: T, into hasher: inout Hasher ) { withUnsafeBytes(of: value) { buffer in let bytes = buffer.prefix { $0 != 0 } + hasher.combine(bytes.count) hasher.combine(bytes: .init(rebasing: bytes)) } } @@ -718,8 +859,7 @@ extension FileDescriptor { /// Creates a `StatFS` for the file system containing the file referenced by /// this `FileDescriptor`. /// - /// The corresponding C function is `fstatfs()` on Darwin and BSD, or - /// `fstatvfs()` otherwise. + /// The corresponding C function is `fstatfs()`. @_alwaysEmitIntoClient public func statfs( retryOnInterrupt: Bool = true @@ -736,8 +876,7 @@ extension FilePath { /// Creates a `StatFS` for the file system containing the file referenced by /// this `FilePath`. /// - /// The corresponding C function is `statfs()` on Darwin and BSD, or - /// `statvfs()` otherwise. + /// The corresponding C function is `statfs()`. @_alwaysEmitIntoClient public func statfs( retryOnInterrupt: Bool = true @@ -746,4 +885,4 @@ extension FilePath { } } -#endif // !os(Windows) +#endif // !os(Windows) && !os(WASI) diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index 119b549..ccd115e 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -14,12 +14,16 @@ import CSystem import ucrt #elseif canImport(Glibc) import CSystem +#if os(Linux) +// SwiftGlibc doesn't export `struct statfs`, so re-export it for clients who +// need to use the fields of a `CInterop.StatFS`. +@_exported import CSystemStatFS +#endif import Glibc #elseif canImport(Musl) import CSystem import Musl #elseif canImport(WASILibc) -import CSystem import WASILibc #elseif canImport(Bionic) import CSystem @@ -105,6 +109,30 @@ extension CInterop { public static func stat(_ path: UnsafePointer, _ s: inout CInterop.Stat) -> Int32 { system_stat(path, &s) } + + #if !os(WASI) + /// The C `statfs` struct. + public typealias StatFS = statfs + + /// Calls the C `statfs()` function. + /// + /// This is a direct wrapper around the C system call. + /// For a more ergonomic Swift API, use `StatFS` instead. + /// + /// - Warning: This API is primarily intended for migration purposes when + /// supporting older deployment targets. If your deployment target supports + /// it, prefer using the `StatFS` API, which provides type-safe, ergonomic + /// access to file system metadata in Swift. + /// + /// - Parameters: + /// - path: A null-terminated C string representing the file path. + /// - s: An `inout` reference to a `CInterop.StatFS` struct to populate. + /// - Returns: 0 on success, -1 on error (check `errno`). + @_alwaysEmitIntoClient + public static func statfs(_ path: UnsafePointer, _ s: inout CInterop.StatFS) -> Int32 { + system_statfs(path, &s) + } + #endif } @available(System 1.7.0, *) @@ -118,14 +146,9 @@ extension CInterop { #endif } +#if !os(WASI) @available(System 199, *) extension CInterop { - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) - public typealias StatFS = statfs - #else - public typealias StatFS = statvfs - #endif - #if SYSTEM_PACKAGE_DARWIN || os(OpenBSD) public typealias MountFlags = UInt32 #elseif os(FreeBSD) @@ -134,10 +157,7 @@ extension CInterop { public typealias MountFlags = CUnsignedLong #endif - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) public typealias FileSystemID = fsid_t - #else - public typealias FileSystemID = CUnsignedLong - #endif } #endif +#endif diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 966d5ee..ba31929 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -23,7 +23,6 @@ import Musl #elseif canImport(WASILibc) import WASILibc #elseif canImport(Android) -import CSystem import Android #else #error("Unsupported Platform") @@ -797,11 +796,63 @@ internal var _UF_SYSTEM: UInt32 { UInt32(bitPattern: UF_SYSTEM) } internal var _SF_SNAPSHOT: UInt32 { UInt32(bitPattern: SF_SNAPSHOT) } #endif -// MARK: - statfs/statvfs Mount Flags +// MARK: - statfs Mount Flags -// Darwin and BSD (`statfs`) and other platforms (`statvfs`) use different C -// names (`MNT_*` vs `ST_*`) for the flags they share, so flags are exposed -// here under general `_MOUNT_*` names that resolve per platform. +// `_MOUNT_*` is `MNT_*` on Darwin and BSD, or `ST_*` on Linux and Android. + +#if !os(WASI) + +// MARK: ST_* bits on Linux and Android + +// Literal bits to keep `@_alwaysEmitIntoClient` semantics. Calling CSystem's +// `_system_get_ST_*` getters would put a CSystem symbol in every client, block +// constant folding, and fail to compile under an `internal import CSystem`. +// `StatFSTests.mountFlagBitsMatchLibc` checks the literals against libc. +#if os(Linux) || os(Android) +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_RDONLY_BIT: CInterop.MountFlags { 0x0001 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_NOSUID_BIT: CInterop.MountFlags { 0x0002 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_NODEV_BIT: CInterop.MountFlags { 0x0004 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_NOEXEC_BIT: CInterop.MountFlags { 0x0008 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_SYNCHRONOUS_BIT: CInterop.MountFlags { 0x0010 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_MANDLOCK_BIT: CInterop.MountFlags { 0x0040 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_NOATIME_BIT: CInterop.MountFlags { 0x0400 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_NODIRATIME_BIT: CInterop.MountFlags { 0x0800 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_RELATIME_BIT: CInterop.MountFlags { 0x1000 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_NOSYMFOLLOW_BIT: CInterop.MountFlags { 0x2000 } + +@available(System 199, *) +@_alwaysEmitIntoClient +internal var _ST_VALID_BIT: CInterop.MountFlags { 0x0020 } +#endif // MARK: Flags Available on All Platforms @@ -811,9 +862,7 @@ internal var _MOUNT_RDONLY: CInterop.MountFlags { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) CInterop.MountFlags(truncatingIfNeeded: MNT_RDONLY) #elseif os(Linux) || os(Android) - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_RDONLY()) - #else - CInterop.MountFlags(truncatingIfNeeded: ST_RDONLY) + _ST_RDONLY_BIT #endif } @@ -823,9 +872,7 @@ internal var _MOUNT_SYNCHRONOUS: CInterop.MountFlags { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) CInterop.MountFlags(truncatingIfNeeded: MNT_SYNCHRONOUS) #elseif os(Linux) || os(Android) - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_SYNCHRONOUS()) - #else - CInterop.MountFlags(truncatingIfNeeded: ST_SYNCHRONOUS) + _ST_SYNCHRONOUS_BIT #endif } @@ -835,9 +882,7 @@ internal var _MOUNT_NOEXEC: CInterop.MountFlags { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) CInterop.MountFlags(truncatingIfNeeded: MNT_NOEXEC) #elseif os(Linux) || os(Android) - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NOEXEC()) - #else - CInterop.MountFlags(truncatingIfNeeded: ST_NOEXEC) + _ST_NOEXEC_BIT #endif } @@ -847,9 +892,7 @@ internal var _MOUNT_NOSUID: CInterop.MountFlags { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) CInterop.MountFlags(truncatingIfNeeded: MNT_NOSUID) #elseif os(Linux) || os(Android) - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NOSUID()) - #else - CInterop.MountFlags(truncatingIfNeeded: ST_NOSUID) + _ST_NOSUID_BIT #endif } @@ -859,9 +902,7 @@ internal var _MOUNT_NOATIME: CInterop.MountFlags { #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) CInterop.MountFlags(truncatingIfNeeded: MNT_NOATIME) #elseif os(Linux) || os(Android) - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NOATIME()) - #else - CInterop.MountFlags(truncatingIfNeeded: ST_NOATIME) + _ST_NOATIME_BIT #endif } @@ -874,79 +915,25 @@ internal var _MOUNT_NODEV: CInterop.MountFlags { #if SYSTEM_PACKAGE_DARWIN || os(OpenBSD) CInterop.MountFlags(truncatingIfNeeded: MNT_NODEV) #elseif os(Linux) || os(Android) - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NODEV()) - #else - CInterop.MountFlags(truncatingIfNeeded: ST_NODEV) + _ST_NODEV_BIT #endif } #endif -// MARK: Flags Available on Linux, WASI, and Android +// MARK: Flags Available on Linux and Android -#if os(Linux) || os(WASI) || os(Android) +#if os(Linux) || os(Android) @available(System 199, *) @_alwaysEmitIntoClient -internal var _ST_MANDLOCK: CInterop.MountFlags { - #if os(WASI) - CInterop.MountFlags(truncatingIfNeeded: ST_MANDLOCK) - #else - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_MANDLOCK()) - #endif -} +internal var _ST_MANDLOCK: CInterop.MountFlags { _ST_MANDLOCK_BIT } @available(System 199, *) @_alwaysEmitIntoClient -internal var _ST_NODIRATIME: CInterop.MountFlags { - #if os(WASI) - CInterop.MountFlags(truncatingIfNeeded: ST_NODIRATIME) - #else - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NODIRATIME()) - #endif -} +internal var _ST_NODIRATIME: CInterop.MountFlags { _ST_NODIRATIME_BIT } @available(System 199, *) @_alwaysEmitIntoClient -internal var _ST_RELATIME: CInterop.MountFlags { - #if os(WASI) - CInterop.MountFlags(truncatingIfNeeded: ST_RELATIME) - #else - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_RELATIME()) - #endif -} -#endif - -// MARK: Flags Available on Linux and WASI Only - -#if os(Linux) || os(WASI) -@available(System 199, *) -@_alwaysEmitIntoClient -internal var _ST_WRITE: CInterop.MountFlags { - #if os(WASI) - CInterop.MountFlags(truncatingIfNeeded: ST_WRITE) - #else - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_WRITE()) - #endif -} - -@available(System 199, *) -@_alwaysEmitIntoClient -internal var _ST_APPEND: CInterop.MountFlags { - #if os(WASI) - CInterop.MountFlags(truncatingIfNeeded: ST_APPEND) - #else - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_APPEND()) - #endif -} - -@available(System 199, *) -@_alwaysEmitIntoClient -internal var _ST_IMMUTABLE: CInterop.MountFlags { - #if os(WASI) - CInterop.MountFlags(truncatingIfNeeded: ST_IMMUTABLE) - #else - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_IMMUTABLE()) - #endif -} +internal var _ST_RELATIME: CInterop.MountFlags { _ST_RELATIME_BIT } #endif // MARK: Flags Available on Linux, Android, and FreeBSD @@ -958,7 +945,7 @@ internal var _MOUNT_NOSYMFOLLOW: CInterop.MountFlags { #if os(FreeBSD) CInterop.MountFlags(truncatingIfNeeded: MNT_NOSYMFOLLOW) #else - CInterop.MountFlags(truncatingIfNeeded: _system_get_ST_NOSYMFOLLOW()) + _ST_NOSYMFOLLOW_BIT #endif } #endif @@ -1143,4 +1130,6 @@ internal var _MNT_NOPERM: CInterop.MountFlags { CInterop.MountFlags(truncatingIf internal var _MNT_WXALLOWED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_WXALLOWED) } #endif +#endif // !os(WASI) + #endif // !os(Windows) diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index 401dba2..76c7369 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -19,12 +19,14 @@ import CSystem import ucrt #elseif canImport(Glibc) import CSystem +#if os(Linux) +import CSystemStatFS +#endif import Glibc #elseif canImport(Musl) import CSystem import Musl #elseif canImport(WASILibc) -@_implementationOnly import CSystem import WASILibc #elseif canImport(Android) import CSystem @@ -110,8 +112,9 @@ internal func system_fstatat(_ fd: CInt, _ p: UnsafePointer, _ s: inout C fstatat(fd, p, &s, flags) } -#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) -@available(System 199, *) +#if !os(WASI) +@available(System 0.0.2, *) +@_alwaysEmitIntoClient internal func system_statfs(_ p: UnsafePointer, _ s: inout CInterop.StatFS) -> Int32 { statfs(p, &s) } @@ -119,15 +122,6 @@ internal func system_statfs(_ p: UnsafePointer, _ s: inout CInterop.StatF internal func system_fstatfs(_ fd: CInt, _ s: inout CInterop.StatFS) -> Int32 { fstatfs(fd, &s) } -#else -@available(System 199, *) -internal func system_statvfs(_ p: UnsafePointer, _ s: inout CInterop.StatFS) -> Int32 { - statvfs(p, &s) -} -@available(System 199, *) -internal func system_fstatvfs(_ fd: CInt, _ s: inout CInterop.StatFS) -> Int32 { - fstatvfs(fd, &s) -} #endif #endif diff --git a/Tests/MemberImportVisibility/Probe.swift b/Tests/MemberImportVisibility/Probe.swift index a27c836..4275fce 100644 --- a/Tests/MemberImportVisibility/Probe.swift +++ b/Tests/MemberImportVisibility/Probe.swift @@ -44,4 +44,26 @@ func _mivProbe(_ s: CInterop.Stat) { _ = s.st_mtim _ = s.st_ctim } + +// These are the Linux and Android field names. FreeBSD's libc module is also +// named Glibc, but its `statfs` and `fsid_t` use the BSD names. +#if os(Linux) || os(Android) +func _mivProbe(_ s: CInterop.StatFS) { + _ = s.f_type + _ = s.f_bsize + _ = s.f_blocks + _ = s.f_bfree + _ = s.f_bavail + _ = s.f_files + _ = s.f_ffree + _ = s.f_fsid + _ = s.f_namelen + _ = s.f_frsize + _ = s.f_flags +} + +func _mivProbe(_ id: CInterop.FileSystemID) { + _ = id.__val +} +#endif #endif diff --git a/Tests/SystemTests/StatFSTests.swift b/Tests/SystemTests/StatFSTests.swift index 84c7cfd..5146ec5 100644 --- a/Tests/SystemTests/StatFSTests.swift +++ b/Tests/SystemTests/StatFSTests.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -#if !os(Windows) +#if !os(Windows) && !os(WASI) import Testing @@ -25,10 +25,8 @@ import Glibc #elseif canImport(Musl) import CSystem import Musl -#elseif canImport(WASILibc) -import CSystem -import WASILibc #elseif canImport(Android) +import CSystem import Android #else #error("Unsupported Platform") @@ -43,11 +41,6 @@ import Android @Suite("StatFS") private struct StatFSTests { - // On WASI, statvfs/fstatvfs are unconditional stubs that set ENOSYS and - // return -1, so every StatFS initializer throws Errno.noFunction. Skip the - // behavioral tests there. - #if !os(WASI) - @available(System 199, *) @Test func initializersAgree() async throws { try withTemporaryFilePath(basename: "StatFS_initializersAgree") { tempDir in @@ -60,7 +53,6 @@ private struct StatFSTests { let fromFD = try StatFS(dirFD) let fromFDExt = try dirFD.statfs() - // All construction paths describe the same file system. #expect(fromFilePath.fileSystemID == fromCString.fileSystemID) #expect(fromFilePath.fileSystemID == fromFilePathExt.fileSystemID) #expect(fromFilePath.fileSystemID == fromFD.fileSystemID) @@ -79,48 +71,8 @@ private struct StatFSTests { #expect(statfs.blockSize > 0) #expect(statfs.totalBlocks > 0) - - // Free space cannot exceed the total, and available (non-superuser) - // cannot exceed the total free. #expect(statfs.freeBlocks <= statfs.totalBlocks) #expect(statfs.availableBlocks <= statfs.freeBlocks) - - // Computed sizes are the block count times the block-count unit. - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) - let unit = UInt64(statfs.blockSize) - #else - let unit = UInt64(statfs.fragmentSize) - #endif - #expect(statfs.totalSpace == statfs.totalBlocks * unit) - #expect(statfs.freeSpace == statfs.freeBlocks * unit) - #expect(statfs.availableSpace == statfs.availableBlocks * unit) - - #expect(statfs.totalSpace >= statfs.freeSpace) - #expect(statfs.freeSpace >= statfs.availableSpace) - } - } - - @available(System 199, *) - @Test func spaceSaturatesOnOverflow() async throws { - try withTemporaryFilePath(basename: "StatFS_saturates") { tempDir in - var statfs = try StatFS(tempDir) - statfs.totalBlocks = .max - #expect(statfs.blockSize > 1) - // Max blocks times a >1 unit overflows UInt64 and must saturate. - #expect(statfs.totalSpace == .max) - } - } - - @available(System 199, *) - @Test func inodes() async throws { - try withTemporaryFilePath(basename: "StatFS_inodes") { tempDir in - let statfs = try StatFS(tempDir) - // totalInodes can legitimately be 0 on file systems with dynamic inode - // allocation, so only assert the ordering when it is nonzero. - #expect(statfs.freeInodes <= statfs.totalInodes || statfs.totalInodes == 0) - #if !SYSTEM_PACKAGE_DARWIN && !os(FreeBSD) - #expect(statfs.availableInodes <= statfs.freeInodes) - #endif } } @@ -128,16 +80,6 @@ private struct StatFSTests { @Test func readOnlyFlagReflectsWritableFileSystem() async throws { try withTemporaryFilePath(basename: "StatFS_readOnly") { tempDir in let statfs = try StatFS(tempDir) - - // Create and write a file in the temp dir. If this succeeds, - // the file system is not read-only... - let probe = tempDir.appending("probe") - let fd = try FileDescriptor.open( - probe, .readWrite, options: .create, permissions: .ownerReadWrite) - defer { try? fd.close() } - try fd.writeAll("probe".utf8) - - // ...so the read-only mount flag must be clear. #expect(!statfs.mountFlags.contains(.readOnly)) } } @@ -148,18 +90,10 @@ private struct StatFSTests { try withTemporaryFilePath(basename: "StatFS_darwinBSD") { tempDir in let statfs = try StatFS(tempDir) #expect(statfs.preferredIOBlockSize > 0) - - // `typeName` is a non-empty, readable file system name. #expect(!statfs.typeName.isEmpty) - - // `mountPoint` is some absolute path, and `mountSource` is a non-empty - // device path. Note that on Darwin, firmlinks mean the temp dir path is - // not necessarily a lexical prefix of its mount point, so don't assert - // that relationship. #expect(statfs.mountPoint.isAbsolute) #expect(!statfs.mountSource.string.isEmpty) - // statfs of the mount point itself reports that same mount point. let mountStatFS = try StatFS(statfs.mountPoint) #expect(mountStatFS.mountPoint == statfs.mountPoint) #expect(mountStatFS.typeName == statfs.typeName) @@ -167,19 +101,6 @@ private struct StatFSTests { } #endif - #if SYSTEM_PACKAGE_DARWIN - @available(System 199, *) - @Test func typeAndSubtypeRoundTrip() throws { - // On Darwin, `type` and `subtype` are opaque kernel indices with no stable - // public constants, so we can only assert that mutation round-trips. - var statfs = StatFS(rawValue: CInterop.StatFS()) - statfs.type = FileSystemType(rawValue: 42) - #expect(statfs.type == FileSystemType(42)) - statfs.subtype = FileSystemSubtype(rawValue: 7) - #expect(statfs.subtype == FileSystemSubtype(7)) - } - #endif - @available(System 199, *) @Test func nonexistentPathThrows() async throws { #expect(throws: Errno.noSuchFileOrDirectory) { @@ -206,15 +127,10 @@ private struct StatFSTests { @available(System 199, *) @Test func propertiesMatchRawFields() async throws { - // Verify property mappings from the raw C struct try withTemporaryFilePath(basename: "StatFS_diff") { tempDir in var raw = CInterop.StatFS() try tempDir.withPlatformString { - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) try #require(statfs($0, &raw) == 0, "\(Errno.current)") - #else - try #require(statvfs($0, &raw) == 0, "\(Errno.current)") - #endif } let s = StatFS(rawValue: raw) @@ -229,8 +145,6 @@ private struct StatFSTests { #expect(s.preferredIOBlockSize == Int(raw.f_iosize)) #expect(s.owner.rawValue == raw.f_owner) #expect(s.mountFlags.rawValue == raw.f_flags) - // Decode independently with `String(cString:)`, not the implementation's - // own helper, so this checks the decode rather than restating it. #expect(s.typeName == withUnsafeBytes(of: raw.f_fstypename) { $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } }) @@ -240,59 +154,60 @@ private struct StatFSTests { #expect(s.mountSource.string == withUnsafeBytes(of: raw.f_mntfromname) { $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } }) + #if SYSTEM_PACKAGE_DARWIN + #expect(s.type.rawValue == raw.f_type) + #expect(s.subtype.rawValue == raw.f_fssubtype) + #elseif os(FreeBSD) + #expect(s.type.rawValue == raw.f_type) + #expect(s.maximumNameLength == Int(raw.f_namemax)) + #else // os(OpenBSD) + #expect(s.maximumNameLength == Int(raw.f_namemax)) + #expect(s.availableInodes == UInt64(clamping: raw.f_favail)) + #endif #else #expect(s.fragmentSize == Int(raw.f_frsize)) - #expect(s.availableInodes == UInt64(clamping: raw.f_favail)) - #expect(s.maximumNameLength == Int(raw.f_namemax)) - #expect(s.mountFlags.rawValue == raw.f_flag) + #expect(s.maximumNameLength == Int(raw.f_namelen)) + #expect(s.type.rawValue == UInt32(truncatingIfNeeded: raw.f_type)) + // `mountFlags` omits the kernel's ST_VALID (0x20) bookkeeping bit. + #expect(s.mountFlags.rawValue == CInterop.MountFlags(truncatingIfNeeded: raw.f_flags) & ~0x20) #endif } } - #endif // !os(WASI) - + // Each setter writes its own field, and clamps instead of trapping. @available(System 199, *) - @Test func propertiesAndRawValueRoundTrip() throws { - var raw = CInterop.StatFS() - raw.f_bsize = 4096 - var statfs = StatFS(rawValue: raw) - #expect(statfs.blockSize == 4096) + @Test func settersWriteRawFields() throws { + var s = StatFS(rawValue: CInterop.StatFS()) + s.blockSize = 1 + s.totalBlocks = 2 + s.freeBlocks = 3 + s.availableBlocks = 4 + s.totalInodes = 5 + s.freeInodes = 6 + #expect(s.rawValue.f_bsize == 1) + #expect(s.rawValue.f_blocks == 2) + #expect(s.rawValue.f_bfree == 3) + #expect(s.rawValue.f_bavail == 4) + #expect(s.rawValue.f_files == 5) + #expect(s.rawValue.f_ffree == 6) + #if SYSTEM_PACKAGE_DARWIN + s.type = FileSystemType(7) + s.subtype = FileSystemSubtype(8) + #expect(s.rawValue.f_type == 7) + #expect(s.rawValue.f_fssubtype == 8) + #endif - statfs.blockSize = 8192 - #expect(statfs.blockSize == 8192) - #expect(statfs.rawValue.f_bsize == 8192) + s.mountFlags.insert(.readOnly) + #expect(s.mountFlags.contains(.readOnly)) - statfs.totalBlocks = 123456 - #expect(statfs.totalBlocks == 123456) - #expect(statfs.rawValue.f_blocks == 123456) - - statfs.mountFlags.insert(.readOnly) - #expect(statfs.mountFlags.contains(.readOnly)) - } - - // Setters clamp to the field's range instead of trapping. If the field is - // 64-bit the write round-trips; if it's narrower the value clamps to the - // field's max. Either way, setting `UInt64.max` should never trap or wrap - // to a small value. - @available(System 199, *) - @Test func settersClamp() throws { - var statfs = StatFS(rawValue: CInterop.StatFS()) - - statfs.totalBlocks = .max - #expect(statfs.totalBlocks >= UInt64(UInt32.max)) - - statfs.blockSize = .max - #expect(statfs.blockSize > 0) - - // Writing 0 always fits and reads back exactly. - statfs.freeBlocks = 0 - #expect(statfs.freeBlocks == 0) + s.blockSize = .max + #expect(s.blockSize == Int(clamping: type(of: s.rawValue.f_bsize).max)) } @available(System 199, *) @Test func craftedStructComputesSpace() throws { var raw = CInterop.StatFS() - // The block-count unit is f_bsize on Darwin/BSD, f_frsize on statvfs. + // The block-count unit is f_bsize on Darwin/BSD, f_frsize elsewhere. #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) raw.f_bsize = 512 #else @@ -309,19 +224,51 @@ private struct StatFSTests { #expect(s.availableSpace == 100 * 512) } + @available(System 199, *) + @Test func spaceSaturatesOnOverflow() throws { + var raw = CInterop.StatFS() + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + raw.f_bsize = 512 + #else + raw.f_frsize = 512 + #endif + raw.f_blocks = .max + + let s = StatFS(rawValue: raw) + if MemoryLayout.size(ofValue: raw.f_blocks) == MemoryLayout.size { + #expect(s.totalSpace == .max) + } else { + #expect(s.totalSpace == UInt64(raw.f_blocks) * 512) + } + } + #if os(FreeBSD) || os(OpenBSD) - // The block/inode-count fields are signed here; negatives clamp to 0. @available(System 199, *) @Test func negativeCountsClampToZero() throws { var raw = CInterop.StatFS() raw.f_bsize = 512 raw.f_bavail = -1 + #if os(FreeBSD) raw.f_ffree = -1 + #else + raw.f_favail = -1 + #endif let s = StatFS(rawValue: raw) #expect(s.availableBlocks == 0) #expect(s.availableSpace == 0) + #if os(FreeBSD) #expect(s.freeInodes == 0) + #else + #expect(s.availableInodes == 0) + #endif + + // Distinct negative counts read the same through the clamped property, + // but they're still different values. + var other = raw + other.f_bavail = -2 + #expect(StatFS(rawValue: other).availableBlocks == s.availableBlocks) + #expect(StatFS(rawValue: other) != s) } #endif @@ -341,15 +288,11 @@ private struct StatFSTests { return String(decoding: result, as: UTF8.self) } - // Cross-check mountFlags against /proc/self/mounts, the kernel's textual view - // of the same flags produced by a different code path. @available(System 199, *) @Test func mountFlagsMatchProcMounts() throws { let contents = try _readEntireFile("/proc/self/mounts") - // Fields: device, mountPoint, fsType, options, dump, pass. A later entry - // shadows an earlier one at the same mount point, as statvfs also sees, so - // key on mount point to keep the effective options. + // Fields: device, mountPoint, fsType, options, dump, pass. var mounts: [String: Set] = [:] for line in contents.split(separator: "\n") { let fields = line.split(separator: " ") @@ -360,7 +303,6 @@ private struct StatFSTests { mounts[mountPoint] = Set(fields[3].split(separator: ",").map(String.init)) } - // Match whole options, so "errors=remount-ro" doesn't look like "ro". let checks: [(option: String, flag: MountFlags)] = [ ("ro", .readOnly), ("noexec", .noExecution), @@ -369,8 +311,12 @@ private struct StatFSTests { ("noatime", .noAccessTime), ] + // Only probe well-known local mounts. statfs on an arbitrary host mount + // can hang (e.g. a stale NFS mount). + let candidates: Set = ["/", "/proc", "/sys", "/dev", "/dev/shm", "/run"] + var verified = 0 - for (mountPoint, options) in mounts { + for (mountPoint, options) in mounts where candidates.contains(mountPoint) { guard let statfs = try? StatFS(FilePath(mountPoint)) else { continue } for (option, flag) in checks { #expect( @@ -386,51 +332,110 @@ private struct StatFSTests { } #endif - #if os(WASI) + #if os(Linux) || os(Android) @available(System 199, *) - @Test func wasiThrowsNoFunction() async throws { - // wasi-libc's statvfs is a stub that always fails with ENOSYS. - #expect(throws: Errno.noFunction) { - _ = try StatFS("/") + @Test func typeIsMagicNumber() throws { + // PROC_SUPER_MAGIC from . + #expect(try StatFS("/proc").type == FileSystemType(0x9FA0)) + + // Magic numbers from 0x80000000 up should round-trip correctly even + // on platforms where they're signed. + var statfs = StatFS(rawValue: CInterop.StatFS()) + statfs.type = FileSystemType(0x9123_683E) // BTRFS_SUPER_MAGIC + #expect(statfs.type == FileSystemType(0x9123_683E)) + } + + // The kernel sets ST_VALID (0x20) in every `f_flags` to mark the field as + // filled in, though Bionic's `statfs()` clears it. + @available(System 199, *) + @Test func mountFlagsOmitValidBit() throws { + var raw = CInterop.StatFS() + raw.f_flags = 0x20 | 0x01 // ST_VALID | ST_RDONLY + var statfs = StatFS(rawValue: raw) + #expect(statfs.mountFlags == .readOnly) + + statfs.mountFlags = .noExecution + #expect(statfs.rawValue.f_flags == 0x20 | 0x08) // ST_VALID | ST_NOEXEC + + let root = try StatFS("/") + #if os(Linux) + #expect(root.rawValue.f_flags & 0x20 != 0) + #endif + #expect(root.mountFlags.rawValue & 0x20 == 0) + } + #endif + + #if os(Linux) || os(Android) + @available(System 199, *) + @Test func mountFlagBitsMatchLibc() throws { + let expected: [(name: String, literal: CInterop.MountFlags, libc: UInt64)] = [ + ("ST_RDONLY", _ST_RDONLY_BIT, _system_get_ST_RDONLY()), + ("ST_NOSUID", _ST_NOSUID_BIT, _system_get_ST_NOSUID()), + ("ST_NODEV", _ST_NODEV_BIT, _system_get_ST_NODEV()), + ("ST_NOEXEC", _ST_NOEXEC_BIT, _system_get_ST_NOEXEC()), + ("ST_SYNCHRONOUS", _ST_SYNCHRONOUS_BIT, _system_get_ST_SYNCHRONOUS()), + ("ST_MANDLOCK", _ST_MANDLOCK_BIT, _system_get_ST_MANDLOCK()), + ("ST_NOATIME", _ST_NOATIME_BIT, _system_get_ST_NOATIME()), + ("ST_NODIRATIME", _ST_NODIRATIME_BIT, _system_get_ST_NODIRATIME()), + ("ST_RELATIME", _ST_RELATIME_BIT, _system_get_ST_RELATIME()), + ("ST_NOSYMFOLLOW", _ST_NOSYMFOLLOW_BIT, _system_get_ST_NOSYMFOLLOW()), + ] + + for (name, literal, libc) in expected { + #expect( + UInt64(literal) == libc, + "\(name): literal \(literal) disagrees with libc value \(libc)" + ) } } #endif @available(System 199, *) @Test func fileSystemIDConformances() throws { - let a = FileSystemID(rawValue: CInterop.FileSystemID()) - let b = FileSystemID(rawValue: CInterop.FileSystemID()) - #expect(a == b) - #expect(a.hashValue == b.hashValue) + let id = FileSystemID(_words: (1, 2)) + #expect(id == FileSystemID(_words: (1, 2))) + #expect(id != FileSystemID(_words: (1, 3))) + #expect(id != FileSystemID(_words: (3, 2))) + #expect(id.hashValue != FileSystemID(_words: (1, 3)).hashValue) - // Codable round-trips, including the manual fsid_t implementation on - // Darwin and BSD. #if canImport(Foundation) - let statfs = try? StatFS(FilePath("/")) - if let id = statfs?.fileSystemID { - let data = try JSONEncoder().encode(id) - let decoded = try JSONDecoder().decode(FileSystemID.self, from: data) - #expect(decoded == id) - #expect(decoded.hashValue == id.hashValue) - } + let data = try JSONEncoder().encode(id) + #expect(String(decoding: data, as: UTF8.self) == "[1,2]") + #expect(try JSONDecoder().decode(FileSystemID.self, from: data) == id) #endif } @available(System 199, *) - @Test func mountFlagsIsOptionSet() throws { - var flags: MountFlags = [.readOnly, .noExecution] - #expect(flags.contains(.readOnly)) - #expect(flags.contains(.noExecution)) - #expect(!flags.contains(.synchronous)) + @Test func descriptions() throws { + #expect(MountFlags.readOnly.description == "[.readOnly]") + let flags: MountFlags = [.readOnly, .noExecution] + #expect(flags.description == "[.readOnly, .noExecution]") + #expect(flags.debugDescription == flags.description) + #expect(MountFlags(rawValue: 0).description == "[]") - flags.remove(.readOnly) - #expect(!flags.contains(.readOnly)) - - let empty = MountFlags(rawValue: 0) - #expect(empty.isEmpty) + #expect(FileSystemID(_words: (1, 2)).description == "FileSystemID(1, 2)") } - #if !os(WASI) + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + // A name buffer with no NUL terminator (malformed) is read in full. + @available(System 199, *) + @Test func unterminatedNameBuffers() throws { + var raw = CInterop.StatFS() + withUnsafeMutableBytes(of: &raw.f_fstypename) { buffer in + for i in buffer.indices { buffer[i] = UInt8(ascii: "a") } + } + withUnsafeMutableBytes(of: &raw.f_mntonname) { buffer in + for i in buffer.indices { buffer[i] = UInt8(ascii: "b") } + } + + let s = StatFS(rawValue: raw) + let typeNameLength = MemoryLayout.size(ofValue: raw.f_fstypename) + let mountPointLength = MemoryLayout.size(ofValue: raw.f_mntonname) + #expect(s.typeName == String(repeating: "a", count: typeNameLength)) + #expect(s.mountPoint.string == String(repeating: "b", count: mountPointLength)) + } + #endif + @available(System 199, *) @Test func equalityAndHashing() throws { try withTemporaryFilePath(basename: "StatFS_equality") { tempDir in @@ -450,6 +455,11 @@ private struct StatFSTests { reserved.rawValue.f_reserved.0 &+= 1 #expect(statfs == reserved) #expect(statfs.hashValue == reserved.hashValue) + + // Fields without a property, like `f_flags_ext`, are. + var extended = statfs + extended.rawValue.f_flags_ext ^= 1 + #expect(statfs != extended) #endif // Name buffers are read only up to their NUL terminator, so bytes past @@ -468,7 +478,6 @@ private struct StatFSTests { #endif } } - #endif } From d27cb5275455cb29d0d890e4465c43e96e9a7e5e Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Wed, 7 Oct 2026 19:45:46 -0600 Subject: [PATCH 6/8] v3: Rename `MountFlags` constants for consistency, remove `type` on Darwin and FreeBSD, and remove the `statfs()` methods on `FilePath` and `FileDescriptor`, eliminating the need for `CInterop` back-deployment --- Sources/System/FileSystem/MountFlags.swift | 208 +++++++++++---------- Sources/System/FileSystem/StatFS.swift | 98 +--------- Sources/System/Internals/CInterop.swift | 27 +-- Sources/System/Internals/Exports.swift | 3 +- Tests/SystemTests/StatFSTests.swift | 14 -- 5 files changed, 118 insertions(+), 232 deletions(-) diff --git a/Sources/System/FileSystem/MountFlags.swift b/Sources/System/FileSystem/MountFlags.swift index eef4a3f..90a7f12 100644 --- a/Sources/System/FileSystem/MountFlags.swift +++ b/Sources/System/FileSystem/MountFlags.swift @@ -9,61 +9,61 @@ // //===----------------------------------------------------------------------===// -// |--------------------------------------------------------------------------------------------------------------------------| -// | Swift API to C Mapping | -// |--------------------------------------------------------------------------------------------------------------------------| -// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android | -// |-----------------------------|----------------------|-----------------|-----------------|----------------|----------------| -// | readOnly | MNT_RDONLY | MNT_RDONLY | MNT_RDONLY | ST_RDONLY | ST_RDONLY | -// | synchronous | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | ST_SYNCHRONOUS | ST_SYNCHRONOUS | -// | noExecution | MNT_NOEXEC | MNT_NOEXEC | MNT_NOEXEC | ST_NOEXEC | ST_NOEXEC | -// | noSetUserID | MNT_NOSUID | MNT_NOSUID | MNT_NOSUID | ST_NOSUID | ST_NOSUID | -// | noAccessTime | MNT_NOATIME | MNT_NOATIME | MNT_NOATIME | ST_NOATIME | ST_NOATIME | -// | noDevices | MNT_NODEV | N/A | MNT_NODEV | ST_NODEV | ST_NODEV | -// | mandatoryLockingPermitted | N/A | N/A | N/A | ST_MANDLOCK | ST_MANDLOCK | -// | noDirectoryAccessTime | N/A | N/A | N/A | ST_NODIRATIME | ST_NODIRATIME | -// | relativeAccessTime | N/A | N/A | N/A | ST_RELATIME | ST_RELATIME | -// | noSymlinkFollow | N/A | MNT_NOSYMFOLLOW | N/A | ST_NOSYMFOLLOW | ST_NOSYMFOLLOW | -// | asynchronous | MNT_ASYNC | MNT_ASYNC | MNT_ASYNC | N/A | N/A | -// | exported | MNT_EXPORTED | MNT_EXPORTED | MNT_EXPORTED | N/A | N/A | -// | local | MNT_LOCAL | MNT_LOCAL | MNT_LOCAL | N/A | N/A | -// | quota | MNT_QUOTA | MNT_QUOTA | MNT_QUOTA | N/A | N/A | -// | rootFileSystem | MNT_ROOTFS | MNT_ROOTFS | MNT_ROOTFS | N/A | N/A | -// | union | MNT_UNION | MNT_UNION | N/A | N/A | N/A | -// | automounted | MNT_AUTOMOUNTED | MNT_AUTOMOUNTED | N/A | N/A | N/A | -// | multiLabel | MNT_MULTILABEL | MNT_MULTILABEL | N/A | N/A | N/A | -// | exportedReadOnly | N/A | MNT_EXRDONLY | MNT_EXRDONLY | N/A | N/A | -// | exportedByDefault | N/A | MNT_DEFEXPORTED | MNT_DEFEXPORTED | N/A | N/A | -// | exportedAnonymously | N/A | MNT_EXPORTANON | MNT_EXPORTANON | N/A | N/A | -// | softUpdates | N/A | MNT_SOFTDEP | MNT_SOFTDEP | N/A | N/A | -// | contentProtection | MNT_CPROTECT | N/A | N/A | N/A | N/A | -// | removable | MNT_REMOVABLE | N/A | N/A | N/A | N/A | -// | quarantine | MNT_QUARANTINE | N/A | N/A | N/A | N/A | -// | volumeFileSystem | MNT_DOVOLFS | N/A | N/A | N/A | N/A | -// | noBrowsing | MNT_DONTBROWSE | N/A | N/A | N/A | N/A | -// | ignoreOwnership | MNT_IGNORE_OWNERSHIP | N/A | N/A | N/A | N/A | -// | journaled | MNT_JOURNALED | N/A | N/A | N/A | N/A | -// | noUserExtendedAttributes | MNT_NOUSERXATTR | N/A | N/A | N/A | N/A | -// | deferWrites | MNT_DEFWRITE | N/A | N/A | N/A | N/A | -// | noSymlinkFollowAtMountPoint | MNT_NOFOLLOW | N/A | N/A | N/A | N/A | -// | snapshot | MNT_SNAPSHOT | N/A | N/A | N/A | N/A | -// | strictAccessTime | MNT_STRICTATIME | N/A | N/A | N/A | N/A | -// | exportedKerberos | N/A | MNT_EXKERB | N/A | N/A | N/A | -// | exportedPublic | N/A | MNT_EXPUBLIC | N/A | N/A | N/A | -// | posixACLs | N/A | MNT_ACLS | N/A | N/A | N/A | -// | geomJournaled | N/A | MNT_GJOURNAL | N/A | N/A | N/A | -// | excludedFromDiskFreeReports | N/A | MNT_IGNORE | N/A | N/A | N/A | -// | nfs4ACLs | N/A | MNT_NFS4ACLS | N/A | N/A | N/A | -// | noClusterRead | N/A | MNT_NOCLUSTERR | N/A | N/A | N/A | -// | noClusterWrite | N/A | MNT_NOCLUSTERW | N/A | N/A | N/A | -// | setUserIDDirectory | N/A | MNT_SUIDDIR | N/A | N/A | N/A | -// | softUpdateJournaling | N/A | MNT_SUJ | N/A | N/A | N/A | -// | untrusted | N/A | MNT_UNTRUSTED | N/A | N/A | N/A | -// | mountedByUser | N/A | MNT_USER | N/A | N/A | N/A | -// | verified | N/A | MNT_VERIFIED | N/A | N/A | N/A | -// | noPermissionChecks | N/A | N/A | MNT_NOPERM | N/A | N/A | -// | writeExecuteAllowed | N/A | N/A | MNT_WXALLOWED | N/A | N/A | -// |--------------------------------------------------------------------------------------------------------------------------| +// |-----------------------------------------------------------------------------------------------------------------------------| +// | Swift API to C Mapping | +// |-----------------------------------------------------------------------------------------------------------------------------| +// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android | +// |--------------------------------|----------------------|-----------------|-----------------|----------------|----------------| +// | readOnly | MNT_RDONLY | MNT_RDONLY | MNT_RDONLY | ST_RDONLY | ST_RDONLY | +// | synchronous | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | ST_SYNCHRONOUS | ST_SYNCHRONOUS | +// | noExecution | MNT_NOEXEC | MNT_NOEXEC | MNT_NOEXEC | ST_NOEXEC | ST_NOEXEC | +// | noSetUserID | MNT_NOSUID | MNT_NOSUID | MNT_NOSUID | ST_NOSUID | ST_NOSUID | +// | noAccessTime | MNT_NOATIME | MNT_NOATIME | MNT_NOATIME | ST_NOATIME | ST_NOATIME | +// | noDevices | MNT_NODEV | N/A | MNT_NODEV | ST_NODEV | ST_NODEV | +// | mandatoryLocking | N/A | N/A | N/A | ST_MANDLOCK | ST_MANDLOCK | +// | noDirectoryAccessTime | N/A | N/A | N/A | ST_NODIRATIME | ST_NODIRATIME | +// | relativeAccessTime | N/A | N/A | N/A | ST_RELATIME | ST_RELATIME | +// | noSymlinkFollowing | N/A | MNT_NOSYMFOLLOW | N/A | ST_NOSYMFOLLOW | ST_NOSYMFOLLOW | +// | asynchronous | MNT_ASYNC | MNT_ASYNC | MNT_ASYNC | N/A | N/A | +// | exported | MNT_EXPORTED | MNT_EXPORTED | MNT_EXPORTED | N/A | N/A | +// | local | MNT_LOCAL | MNT_LOCAL | MNT_LOCAL | N/A | N/A | +// | quotasEnabled | MNT_QUOTA | MNT_QUOTA | MNT_QUOTA | N/A | N/A | +// | rootFileSystem | MNT_ROOTFS | MNT_ROOTFS | MNT_ROOTFS | N/A | N/A | +// | union | MNT_UNION | MNT_UNION | N/A | N/A | N/A | +// | automounted | MNT_AUTOMOUNTED | MNT_AUTOMOUNTED | N/A | N/A | N/A | +// | multiLabel | MNT_MULTILABEL | MNT_MULTILABEL | N/A | N/A | N/A | +// | exportedReadOnly | N/A | MNT_EXRDONLY | MNT_EXRDONLY | N/A | N/A | +// | exportedByDefault | N/A | MNT_DEFEXPORTED | MNT_DEFEXPORTED | N/A | N/A | +// | exportedAnonymously | N/A | MNT_EXPORTANON | MNT_EXPORTANON | N/A | N/A | +// | softUpdates | N/A | MNT_SOFTDEP | MNT_SOFTDEP | N/A | N/A | +// | contentProtection | MNT_CPROTECT | N/A | N/A | N/A | N/A | +// | removable | MNT_REMOVABLE | N/A | N/A | N/A | N/A | +// | quarantined | MNT_QUARANTINE | N/A | N/A | N/A | N/A | +// | supportsVolfs | MNT_DOVOLFS | N/A | N/A | N/A | N/A | +// | noBrowsing | MNT_DONTBROWSE | N/A | N/A | N/A | N/A | +// | ignoresOwnership | MNT_IGNORE_OWNERSHIP | N/A | N/A | N/A | N/A | +// | journaled | MNT_JOURNALED | N/A | N/A | N/A | N/A | +// | noUserExtendedAttributes | MNT_NOUSERXATTR | N/A | N/A | N/A | N/A | +// | defersWrites | MNT_DEFWRITE | N/A | N/A | N/A | N/A | +// | noSymlinkFollowingAtMountPoint | MNT_NOFOLLOW | N/A | N/A | N/A | N/A | +// | snapshot | MNT_SNAPSHOT | N/A | N/A | N/A | N/A | +// | strictAccessTime | MNT_STRICTATIME | N/A | N/A | N/A | N/A | +// | exportedWithKerberos | N/A | MNT_EXKERB | N/A | N/A | N/A | +// | exportedPublicly | N/A | MNT_EXPUBLIC | N/A | N/A | N/A | +// | posixACLs | N/A | MNT_ACLS | N/A | N/A | N/A | +// | geomJournaled | N/A | MNT_GJOURNAL | N/A | N/A | N/A | +// | excludedFromDiskFreeReports | N/A | MNT_IGNORE | N/A | N/A | N/A | +// | nfs4ACLs | N/A | MNT_NFS4ACLS | N/A | N/A | N/A | +// | noClusteredReads | N/A | MNT_NOCLUSTERR | N/A | N/A | N/A | +// | noClusteredWrites | N/A | MNT_NOCLUSTERW | N/A | N/A | N/A | +// | setUserIDDirectories | N/A | MNT_SUIDDIR | N/A | N/A | N/A | +// | softUpdatesJournaling | N/A | MNT_SUJ | N/A | N/A | N/A | +// | untrusted | N/A | MNT_UNTRUSTED | N/A | N/A | N/A | +// | userMounted | N/A | MNT_USER | N/A | N/A | N/A | +// | verified | N/A | MNT_VERIFIED | N/A | N/A | N/A | +// | noPermissionChecks | N/A | N/A | MNT_NOPERM | N/A | N/A | +// | writeExecuteAllowed | N/A | N/A | MNT_WXALLOWED | N/A | N/A | +// |-----------------------------------------------------------------------------------------------------------------------------| #if !os(Windows) && !os(WASI) @@ -109,7 +109,8 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public static var noExecution: MountFlags { MountFlags(rawValue: _MOUNT_NOEXEC) } - /// Set-user-ID and set-group-ID bits are not honored on the file system. + /// Set-user-ID and set-group-ID (setuid and setgid) bits are not honored on + /// the file system. /// /// The corresponding C constant is `MNT_NOSUID` on Darwin and BSD, /// or `ST_NOSUID` otherwise. @@ -145,14 +146,14 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { // Linux never reports them in `f_flags`, so they have no corresponding flag. #if os(Linux) || os(Android) - /// The file system permits mandatory file locking. + /// Mandatory file locking is enabled on the file system. /// /// - Note: Only available on Linux and Android. /// - Note: Mandatory locking was deprecated and removed in Linux 5.15. /// /// The corresponding C constant is `ST_MANDLOCK`. @_alwaysEmitIntoClient - public static var mandatoryLockingPermitted: MountFlags { MountFlags(rawValue: _ST_MANDLOCK) } + public static var mandatoryLocking: MountFlags { MountFlags(rawValue: _ST_MANDLOCK) } /// Directory access times are not updated on the file system. /// @@ -182,7 +183,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// The corresponding C constant is `MNT_NOSYMFOLLOW` on FreeBSD, /// or `ST_NOSYMFOLLOW` on Linux and Android. @_alwaysEmitIntoClient - public static var noSymlinkFollow: MountFlags { MountFlags(rawValue: _MOUNT_NOSYMFOLLOW) } + public static var noSymlinkFollowing: MountFlags { MountFlags(rawValue: _MOUNT_NOSYMFOLLOW) } #endif // MARK: Flags Available on Darwin, FreeBSD, and OpenBSD @@ -218,7 +219,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_QUOTA`. @_alwaysEmitIntoClient - public static var quota: MountFlags { MountFlags(rawValue: _MNT_QUOTA) } + public static var quotasEnabled: MountFlags { MountFlags(rawValue: _MNT_QUOTA) } /// The file system is the root file system. /// @@ -249,7 +250,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public static var automounted: MountFlags { MountFlags(rawValue: _MNT_AUTOMOUNTED) } - /// The file system supports Mandatory Access Control (MAC) labels for + /// The file system maintains Mandatory Access Control (MAC) labels for /// individual objects. /// /// - Note: Only available on Darwin and FreeBSD. @@ -270,7 +271,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public static var exportedReadOnly: MountFlags { MountFlags(rawValue: _MNT_EXRDONLY) } - /// The file system is exported for reading and writing to any host by default. + /// The file system is exported to any host by default. /// /// - Note: Only available on FreeBSD and OpenBSD. /// @@ -278,7 +279,8 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public static var exportedByDefault: MountFlags { MountFlags(rawValue: _MNT_DEFEXPORTED) } - /// The file system maps all remote users to the anonymous user account. + /// The file system is exported with all remote users mapped to the + /// anonymous user account. /// /// - Note: Only available on FreeBSD and OpenBSD. /// @@ -286,7 +288,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public static var exportedAnonymously: MountFlags { MountFlags(rawValue: _MNT_EXPORTANON) } - /// The file system uses soft updates. + /// Soft updates are enabled on the file system. /// /// - Note: Only available on FreeBSD and OpenBSD. Accepted for compatibility /// on OpenBSD, but has no effect there. @@ -299,7 +301,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { // MARK: Flags Available on Darwin Only #if SYSTEM_PACKAGE_DARWIN - /// The file system supports per-file encrypted data protection. + /// Per-file encrypted data protection is enabled on the file system. /// /// - Note: Only available on Darwin. /// @@ -321,7 +323,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_QUARANTINE`. @_alwaysEmitIntoClient - public static var quarantine: MountFlags { MountFlags(rawValue: _MNT_QUARANTINE) } + public static var quarantined: MountFlags { MountFlags(rawValue: _MNT_QUARANTINE) } /// The file system supports volfs. /// @@ -329,7 +331,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_DOVOLFS`. @_alwaysEmitIntoClient - public static var volumeFileSystem: MountFlags { MountFlags(rawValue: _MNT_DOVOLFS) } + public static var supportsVolfs: MountFlags { MountFlags(rawValue: _MNT_DOVOLFS) } /// The file system should not be presented to the user for browsing /// (e.g. hidden in Finder). @@ -340,13 +342,13 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public static var noBrowsing: MountFlags { MountFlags(rawValue: _MNT_DONTBROWSE) } - /// Ownership information on the file system is ignored. + /// The file system ignores ownership information. /// /// - Note: Only available on Darwin. /// /// The corresponding C constant is `MNT_IGNORE_OWNERSHIP`. @_alwaysEmitIntoClient - public static var ignoreOwnership: MountFlags { MountFlags(rawValue: _MNT_IGNORE_OWNERSHIP) } + public static var ignoresOwnership: MountFlags { MountFlags(rawValue: _MNT_IGNORE_OWNERSHIP) } /// The file system is journaled. /// @@ -370,7 +372,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_DEFWRITE`. @_alwaysEmitIntoClient - public static var deferWrites: MountFlags { MountFlags(rawValue: _MNT_DEFWRITE) } + public static var defersWrites: MountFlags { MountFlags(rawValue: _MNT_DEFWRITE) } /// Symbolic links are not followed when resolving the mount point. /// @@ -378,9 +380,9 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_NOFOLLOW`. @_alwaysEmitIntoClient - public static var noSymlinkFollowAtMountPoint: MountFlags { MountFlags(rawValue: _MNT_NOFOLLOW) } + public static var noSymlinkFollowingAtMountPoint: MountFlags { MountFlags(rawValue: _MNT_NOFOLLOW) } - /// The mount is a snapshot. + /// The file system is a snapshot. /// /// - Note: Only available on Darwin. /// @@ -388,8 +390,8 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public static var snapshot: MountFlags { MountFlags(rawValue: _MNT_SNAPSHOT) } - /// Access times are always updated on access. Relatime-style optimizations - /// are disabled. + /// Access times are always updated when files are read. Without this flag, + /// the file system may skip some access time updates for performance. /// /// - Note: Only available on Darwin. /// @@ -407,7 +409,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_EXKERB`. @_alwaysEmitIntoClient - public static var exportedKerberos: MountFlags { MountFlags(rawValue: _MNT_EXKERB) } + public static var exportedWithKerberos: MountFlags { MountFlags(rawValue: _MNT_EXKERB) } /// The file system is exported publicly for WebNFS clients. /// @@ -415,9 +417,9 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_EXPUBLIC`. @_alwaysEmitIntoClient - public static var exportedPublic: MountFlags { MountFlags(rawValue: _MNT_EXPUBLIC) } + public static var exportedPublicly: MountFlags { MountFlags(rawValue: _MNT_EXPUBLIC) } - /// The file system supports POSIX.1e ACLs. + /// POSIX.1e ACLs are enabled on the file system. /// /// - Note: Only available on FreeBSD. /// @@ -425,7 +427,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public static var posixACLs: MountFlags { MountFlags(rawValue: _MNT_ACLS) } - /// The file system uses `gjournal`. + /// The file system is journaled by `gjournal`. /// /// - Note: Only available on FreeBSD. See `gjournal(8)`. /// @@ -441,7 +443,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public static var excludedFromDiskFreeReports: MountFlags { MountFlags(rawValue: _MNT_IGNORE) } - /// The file system supports NFSv4 ACLs. + /// NFSv4 ACLs are enabled on the file system. /// /// - Note: Only available on FreeBSD. /// @@ -455,7 +457,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_NOCLUSTERR`. @_alwaysEmitIntoClient - public static var noClusterRead: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERR) } + public static var noClusteredReads: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERR) } /// Clustered writes are disabled on the file system. /// @@ -463,7 +465,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_NOCLUSTERW`. @_alwaysEmitIntoClient - public static var noClusterWrite: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERW) } + public static var noClusteredWrites: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERW) } /// Newly created files in a directory with the set-user-ID bit set are owned /// by that directory's owner, rather than by the creating user. @@ -472,15 +474,15 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_SUIDDIR`. @_alwaysEmitIntoClient - public static var setUserIDDirectory: MountFlags { MountFlags(rawValue: _MNT_SUIDDIR) } + public static var setUserIDDirectories: MountFlags { MountFlags(rawValue: _MNT_SUIDDIR) } - /// The file system uses soft updates with journaling. + /// Soft updates journaling is enabled on the file system. /// /// - Note: Only available on FreeBSD. /// /// The corresponding C constant is `MNT_SUJ`. @_alwaysEmitIntoClient - public static var softUpdateJournaling: MountFlags { MountFlags(rawValue: _MNT_SUJ) } + public static var softUpdatesJournaling: MountFlags { MountFlags(rawValue: _MNT_SUJ) } /// The file system is untrusted, as the integrity of its media is unknown. /// @@ -496,7 +498,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { /// /// The corresponding C constant is `MNT_USER`. @_alwaysEmitIntoClient - public static var mountedByUser: MountFlags { MountFlags(rawValue: _MNT_USER) } + public static var userMounted: MountFlags { MountFlags(rawValue: _MNT_USER) } /// The file system is marked as verified, so per-file integrity checks are /// skipped on execution. @@ -551,21 +553,21 @@ extension MountFlags (.asynchronous, ".asynchronous"), (.exported, ".exported"), (.local, ".local"), - (.quota, ".quota"), + (.quotasEnabled, ".quotasEnabled"), (.rootFileSystem, ".rootFileSystem"), (.union, ".union"), (.automounted, ".automounted"), (.multiLabel, ".multiLabel"), (.contentProtection, ".contentProtection"), (.removable, ".removable"), - (.quarantine, ".quarantine"), - (.volumeFileSystem, ".volumeFileSystem"), + (.quarantined, ".quarantined"), + (.supportsVolfs, ".supportsVolfs"), (.noBrowsing, ".noBrowsing"), - (.ignoreOwnership, ".ignoreOwnership"), + (.ignoresOwnership, ".ignoresOwnership"), (.journaled, ".journaled"), (.noUserExtendedAttributes, ".noUserExtendedAttributes"), - (.deferWrites, ".deferWrites"), - (.noSymlinkFollowAtMountPoint, ".noSymlinkFollowAtMountPoint"), + (.defersWrites, ".defersWrites"), + (.noSymlinkFollowingAtMountPoint, ".noSymlinkFollowingAtMountPoint"), (.snapshot, ".snapshot"), (.strictAccessTime, ".strictAccessTime"), ] @@ -576,11 +578,11 @@ extension MountFlags (.noExecution, ".noExecution"), (.noSetUserID, ".noSetUserID"), (.noAccessTime, ".noAccessTime"), - (.noSymlinkFollow, ".noSymlinkFollow"), + (.noSymlinkFollowing, ".noSymlinkFollowing"), (.asynchronous, ".asynchronous"), (.exported, ".exported"), (.local, ".local"), - (.quota, ".quota"), + (.quotasEnabled, ".quotasEnabled"), (.rootFileSystem, ".rootFileSystem"), (.union, ".union"), (.automounted, ".automounted"), @@ -589,18 +591,18 @@ extension MountFlags (.exportedByDefault, ".exportedByDefault"), (.exportedAnonymously, ".exportedAnonymously"), (.softUpdates, ".softUpdates"), - (.exportedKerberos, ".exportedKerberos"), - (.exportedPublic, ".exportedPublic"), + (.exportedWithKerberos, ".exportedWithKerberos"), + (.exportedPublicly, ".exportedPublicly"), (.posixACLs, ".posixACLs"), (.geomJournaled, ".geomJournaled"), (.excludedFromDiskFreeReports, ".excludedFromDiskFreeReports"), (.nfs4ACLs, ".nfs4ACLs"), - (.noClusterRead, ".noClusterRead"), - (.noClusterWrite, ".noClusterWrite"), - (.setUserIDDirectory, ".setUserIDDirectory"), - (.softUpdateJournaling, ".softUpdateJournaling"), + (.noClusteredReads, ".noClusteredReads"), + (.noClusteredWrites, ".noClusteredWrites"), + (.setUserIDDirectories, ".setUserIDDirectories"), + (.softUpdatesJournaling, ".softUpdatesJournaling"), (.untrusted, ".untrusted"), - (.mountedByUser, ".mountedByUser"), + (.userMounted, ".userMounted"), (.verified, ".verified"), ] #elseif os(OpenBSD) @@ -614,7 +616,7 @@ extension MountFlags (.asynchronous, ".asynchronous"), (.exported, ".exported"), (.local, ".local"), - (.quota, ".quota"), + (.quotasEnabled, ".quotasEnabled"), (.rootFileSystem, ".rootFileSystem"), (.exportedReadOnly, ".exportedReadOnly"), (.exportedByDefault, ".exportedByDefault"), @@ -631,10 +633,10 @@ extension MountFlags (.noSetUserID, ".noSetUserID"), (.noAccessTime, ".noAccessTime"), (.noDevices, ".noDevices"), - (.mandatoryLockingPermitted, ".mandatoryLockingPermitted"), + (.mandatoryLocking, ".mandatoryLocking"), (.noDirectoryAccessTime, ".noDirectoryAccessTime"), (.relativeAccessTime, ".relativeAccessTime"), - (.noSymlinkFollow, ".noSymlinkFollow"), + (.noSymlinkFollowing, ".noSymlinkFollowing"), ] #endif diff --git a/Sources/System/FileSystem/StatFS.swift b/Sources/System/FileSystem/StatFS.swift index e052bf3..57f6f87 100644 --- a/Sources/System/FileSystem/StatFS.swift +++ b/Sources/System/FileSystem/StatFS.swift @@ -41,24 +41,6 @@ public struct StatFS { } } -extension FileDescriptor { - /// Creates a `StatFS` for the file system containing the file referenced by - /// this `FileDescriptor`. - @available(Windows, unavailable, message: "Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") - public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { - fatalError("StatFS is unavailable on Windows") - } -} - -extension FilePath { - /// Creates a `StatFS` for the file system containing the file referenced by - /// this `FilePath`. - @available(Windows, unavailable, message: "Consider using a Win32 API such as GetVolumeInformationW or GetDiskFreeSpaceExW instead.") - public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { - fatalError("StatFS is unavailable on Windows") - } -} - #elseif os(WASI) /// A Swift wrapper of the C `statfs` struct. @@ -91,24 +73,6 @@ public struct StatFS { } } -extension FileDescriptor { - /// Creates a `StatFS` for the file system containing the file referenced by - /// this `FileDescriptor`. - @available(*, unavailable, message: "wasi-libc doesn't implement statfs or statvfs.") - public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { - fatalError("StatFS is unavailable on WASI") - } -} - -extension FilePath { - /// Creates a `StatFS` for the file system containing the file referenced by - /// this `FilePath`. - @available(*, unavailable, message: "wasi-libc doesn't implement statfs or statvfs.") - public func statfs(retryOnInterrupt: Bool = true) throws(Errno) -> StatFS { - fatalError("StatFS is unavailable on WASI") - } -} - #else // Must import here to use C statfs properties in @_alwaysEmitIntoClient APIs. @@ -223,13 +187,13 @@ extension FileSystemID: CustomStringConvertible, CustomDebugStringConvertible { public var debugDescription: String { self.description } } -#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(Linux) || os(Android) +#if os(Linux) || os(Android) // MARK: - FileSystemType /// A Swift wrapper of the C `f_type` file system type found in a `statfs` /// struct. /// -/// - Note: Only available on Darwin, FreeBSD, Linux, and Android. +/// - Note: Only available on Linux and Android. @frozen @available(System 199, *) public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable { @@ -246,7 +210,7 @@ public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable { @_alwaysEmitIntoClient public init(_ rawValue: UInt32) { self.rawValue = rawValue } } -#endif // SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(Linux) || os(Android) +#endif // os(Linux) || os(Android) #if SYSTEM_PACKAGE_DARWIN // MARK: - FileSystemSubtype @@ -608,32 +572,22 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { } } - #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(Linux) || os(Android) + #if os(Linux) || os(Android) /// File system type. /// - /// - Note: On Linux and Android, this is the file system's magic number, - /// such as `0xEF53` for ext4. On Darwin and FreeBSD, it's an internal, - /// kernel-assigned VFS type index with no stable, public constants; - /// prefer `typeName` to identify the file system in a readable format. - /// Not available on OpenBSD. + /// - Note: This is the file system's magic number, such as `0xEF53` for + /// ext4. Only available on Linux and Android. On Darwin and BSD, use + /// `typeName` to identify the file system. /// /// The corresponding C property is `f_type`. @_alwaysEmitIntoClient public var type: FileSystemType { get { - #if os(Linux) || os(Android) // glibc's `f_type` is a signed `long` and can be negative. FileSystemType(rawValue: UInt32(truncatingIfNeeded: rawValue.f_type)) - #else - FileSystemType(rawValue: rawValue.f_type) - #endif } set { - #if os(Linux) || os(Android) rawValue.f_type = .init(truncatingIfNeeded: newValue.rawValue) - #else - rawValue.f_type = newValue.rawValue - #endif } } #endif @@ -641,8 +595,8 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { #if SYSTEM_PACKAGE_DARWIN /// File system subtype. /// - /// - Note: Like `type`, this is a numeric value with no stable, public - /// constants. Only available on Darwin. + /// - Note: This is a numeric value whose meaning depends on `typeName`, + /// with no stable, public constants. Only available on Darwin. /// /// The corresponding C property is `f_fssubtype`. @_alwaysEmitIntoClient @@ -851,38 +805,4 @@ extension StatFS { } } -// MARK: - FileDescriptor Extensions - -@available(System 199, *) -extension FileDescriptor { - - /// Creates a `StatFS` for the file system containing the file referenced by - /// this `FileDescriptor`. - /// - /// The corresponding C function is `fstatfs()`. - @_alwaysEmitIntoClient - public func statfs( - retryOnInterrupt: Bool = true - ) throws(Errno) -> StatFS { - try StatFS(self, retryOnInterrupt: retryOnInterrupt) - } -} - -// MARK: - FilePath Extensions - -@available(System 199, *) -extension FilePath { - - /// Creates a `StatFS` for the file system containing the file referenced by - /// this `FilePath`. - /// - /// The corresponding C function is `statfs()`. - @_alwaysEmitIntoClient - public func statfs( - retryOnInterrupt: Bool = true - ) throws(Errno) -> StatFS { - try StatFS(self, retryOnInterrupt: retryOnInterrupt) - } -} - #endif // !os(Windows) && !os(WASI) diff --git a/Sources/System/Internals/CInterop.swift b/Sources/System/Internals/CInterop.swift index ccd115e..c3b1aa3 100644 --- a/Sources/System/Internals/CInterop.swift +++ b/Sources/System/Internals/CInterop.swift @@ -109,30 +109,6 @@ extension CInterop { public static func stat(_ path: UnsafePointer, _ s: inout CInterop.Stat) -> Int32 { system_stat(path, &s) } - - #if !os(WASI) - /// The C `statfs` struct. - public typealias StatFS = statfs - - /// Calls the C `statfs()` function. - /// - /// This is a direct wrapper around the C system call. - /// For a more ergonomic Swift API, use `StatFS` instead. - /// - /// - Warning: This API is primarily intended for migration purposes when - /// supporting older deployment targets. If your deployment target supports - /// it, prefer using the `StatFS` API, which provides type-safe, ergonomic - /// access to file system metadata in Swift. - /// - /// - Parameters: - /// - path: A null-terminated C string representing the file path. - /// - s: An `inout` reference to a `CInterop.StatFS` struct to populate. - /// - Returns: 0 on success, -1 on error (check `errno`). - @_alwaysEmitIntoClient - public static func statfs(_ path: UnsafePointer, _ s: inout CInterop.StatFS) -> Int32 { - system_statfs(path, &s) - } - #endif } @available(System 1.7.0, *) @@ -149,6 +125,9 @@ extension CInterop { #if !os(WASI) @available(System 199, *) extension CInterop { + /// The C `statfs` struct. + public typealias StatFS = statfs + #if SYSTEM_PACKAGE_DARWIN || os(OpenBSD) public typealias MountFlags = UInt32 #elseif os(FreeBSD) diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index 76c7369..b2b5da5 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -113,8 +113,7 @@ internal func system_fstatat(_ fd: CInt, _ p: UnsafePointer, _ s: inout C } #if !os(WASI) -@available(System 0.0.2, *) -@_alwaysEmitIntoClient +@available(System 199, *) internal func system_statfs(_ p: UnsafePointer, _ s: inout CInterop.StatFS) -> Int32 { statfs(p, &s) } diff --git a/Tests/SystemTests/StatFSTests.swift b/Tests/SystemTests/StatFSTests.swift index 5146ec5..5ecdbc1 100644 --- a/Tests/SystemTests/StatFSTests.swift +++ b/Tests/SystemTests/StatFSTests.swift @@ -46,17 +46,13 @@ private struct StatFSTests { try withTemporaryFilePath(basename: "StatFS_initializersAgree") { tempDir in let fromFilePath = try StatFS(tempDir) let fromCString = try tempDir.withPlatformString { try StatFS($0) } - let fromFilePathExt = try tempDir.statfs() let dirFD = try FileDescriptor.open(tempDir, .readOnly) defer { try? dirFD.close() } let fromFD = try StatFS(dirFD) - let fromFDExt = try dirFD.statfs() #expect(fromFilePath.fileSystemID == fromCString.fileSystemID) - #expect(fromFilePath.fileSystemID == fromFilePathExt.fileSystemID) #expect(fromFilePath.fileSystemID == fromFD.fileSystemID) - #expect(fromFilePath.fileSystemID == fromFDExt.fileSystemID) #expect(fromFilePath.blockSize == fromFD.blockSize) #expect(fromFilePath.totalBlocks == fromFD.totalBlocks) @@ -109,9 +105,6 @@ private struct StatFSTests { #expect(throws: Errno.noSuchFileOrDirectory) { _ = try StatFS(FilePath("/var/empty/definitely/does/not/exist")) } - #expect(throws: Errno.noSuchFileOrDirectory) { - _ = try FilePath("/var/empty/definitely/does/not/exist").statfs() - } } @available(System 199, *) @@ -120,9 +113,6 @@ private struct StatFSTests { #expect(throws: Errno.badFileDescriptor) { _ = try StatFS(badFD) } - #expect(throws: Errno.badFileDescriptor) { - _ = try badFD.statfs() - } } @available(System 199, *) @@ -155,10 +145,8 @@ private struct StatFSTests { $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } }) #if SYSTEM_PACKAGE_DARWIN - #expect(s.type.rawValue == raw.f_type) #expect(s.subtype.rawValue == raw.f_fssubtype) #elseif os(FreeBSD) - #expect(s.type.rawValue == raw.f_type) #expect(s.maximumNameLength == Int(raw.f_namemax)) #else // os(OpenBSD) #expect(s.maximumNameLength == Int(raw.f_namemax)) @@ -191,9 +179,7 @@ private struct StatFSTests { #expect(s.rawValue.f_files == 5) #expect(s.rawValue.f_ffree == 6) #if SYSTEM_PACKAGE_DARWIN - s.type = FileSystemType(7) s.subtype = FileSystemSubtype(8) - #expect(s.rawValue.f_type == 7) #expect(s.rawValue.f_fssubtype == 8) #endif From 9bf5df3d10e22a0f109528ecb6aa36a19c87c3a7 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Mon, 12 Oct 2026 16:59:19 -0600 Subject: [PATCH 7/8] v4: Add `FileSystemTypeName` wrapper --- Sources/System/FileSystem/StatFS.swift | 69 ++++++++++++++++++++++++-- Tests/SystemTests/StatFSTests.swift | 35 +++++++++++-- 2 files changed, 97 insertions(+), 7 deletions(-) diff --git a/Sources/System/FileSystem/StatFS.swift b/Sources/System/FileSystem/StatFS.swift index 57f6f87..01cf9fd 100644 --- a/Sources/System/FileSystem/StatFS.swift +++ b/Sources/System/FileSystem/StatFS.swift @@ -237,6 +237,67 @@ public struct FileSystemSubtype: RawRepresentable, Sendable, Hashable, Codable { } #endif +#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) +// MARK: - FileSystemTypeName + +/// A Swift wrapper of the C `f_fstypename` file system type name found in a +/// `statfs` struct. +/// +/// - Note: Only available on Darwin and BSD. +@frozen +@available(System 199, *) +public struct FileSystemTypeName + : RawRepresentable, Sendable, Hashable, Codable, ExpressibleByStringLiteral +{ + + /// The raw file system type name. + @_alwaysEmitIntoClient + public var rawValue: String + + /// Creates a strongly-typed `FileSystemTypeName` from the raw name. + @_alwaysEmitIntoClient + public init(rawValue: String) { self.rawValue = rawValue } + + /// Creates a strongly-typed `FileSystemTypeName` from the raw name. + @_alwaysEmitIntoClient + public init(_ rawValue: String) { self.rawValue = rawValue } + + /// Creates a `FileSystemTypeName` from a string literal, such as `"apfs"`. + @_alwaysEmitIntoClient + public init(stringLiteral value: String) { self.rawValue = value } + + // MARK: Type Names Available on Darwin Only + + #if SYSTEM_PACKAGE_DARWIN + /// The Apple File System (APFS). + /// + /// - Note: Only available on Darwin. + /// + /// The corresponding `f_fstypename` value is `"apfs"`. + @_alwaysEmitIntoClient + public static var apfs: FileSystemTypeName { FileSystemTypeName(rawValue: "apfs") } + + /// The Mac OS Extended file system (HFS Plus). + /// + /// - Note: Only available on Darwin. + /// + /// The corresponding `f_fstypename` value is `"hfs"`. + @_alwaysEmitIntoClient + public static var hfs: FileSystemTypeName { FileSystemTypeName(rawValue: "hfs") } + #endif +} + +@available(System 199, *) +extension FileSystemTypeName: CustomStringConvertible, CustomDebugStringConvertible { + /// The file system type name, such as `apfs`. + @inline(never) + public var description: String { rawValue } + + /// The file system type name as a quoted string, such as `"apfs"`. + public var debugDescription: String { description.debugDescription } +} +#endif // SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + // MARK: - StatFS #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) @@ -618,16 +679,16 @@ public struct StatFS: RawRepresentable, Sendable, Hashable { set { rawValue.f_owner = newValue.rawValue } } - /// File system type name. + /// File system type name, such as "apfs". /// /// - Note: Only available on Darwin and BSD. /// /// The corresponding C property is `f_fstypename`. @_alwaysEmitIntoClient - public var typeName: String { - withUnsafeBytes(of: rawValue.f_fstypename) { + public var typeName: FileSystemTypeName { + FileSystemTypeName(rawValue: withUnsafeBytes(of: rawValue.f_fstypename) { String(_nullTerminatedBytes: $0) - } + }) } /// Directory where the file system is mounted, such as "/System/Volumes/Data". diff --git a/Tests/SystemTests/StatFSTests.swift b/Tests/SystemTests/StatFSTests.swift index 5ecdbc1..e07f15d 100644 --- a/Tests/SystemTests/StatFSTests.swift +++ b/Tests/SystemTests/StatFSTests.swift @@ -86,7 +86,7 @@ private struct StatFSTests { try withTemporaryFilePath(basename: "StatFS_darwinBSD") { tempDir in let statfs = try StatFS(tempDir) #expect(statfs.preferredIOBlockSize > 0) - #expect(!statfs.typeName.isEmpty) + #expect(!statfs.typeName.rawValue.isEmpty) #expect(statfs.mountPoint.isAbsolute) #expect(!statfs.mountSource.string.isEmpty) @@ -135,7 +135,7 @@ private struct StatFSTests { #expect(s.preferredIOBlockSize == Int(raw.f_iosize)) #expect(s.owner.rawValue == raw.f_owner) #expect(s.mountFlags.rawValue == raw.f_flags) - #expect(s.typeName == withUnsafeBytes(of: raw.f_fstypename) { + #expect(s.typeName.rawValue == withUnsafeBytes(of: raw.f_fstypename) { $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } }) #expect(s.mountPoint.string == withUnsafeBytes(of: raw.f_mntonname) { @@ -391,6 +391,35 @@ private struct StatFSTests { #endif } + #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD) + @available(System 199, *) + @Test func fileSystemTypeNameConformances() throws { + let name: FileSystemTypeName = "apfs" + #expect(name == FileSystemTypeName(rawValue: "apfs")) + #expect(name == FileSystemTypeName("apfs")) + #expect(name != "hfs") + #expect(name.hashValue == FileSystemTypeName("apfs").hashValue) + #expect(name.description == "apfs") + #expect(name.debugDescription == #""apfs""#) + + #if canImport(Foundation) + let data = try JSONEncoder().encode(name) + #expect(String(decoding: data, as: UTF8.self) == #""apfs""#) + #expect(try JSONDecoder().decode(FileSystemTypeName.self, from: data) == name) + #endif + } + #endif + + #if SYSTEM_PACKAGE_DARWIN + @available(System 199, *) + @Test func fileSystemTypeNameConstants() throws { + #expect(FileSystemTypeName.apfs.rawValue == "apfs") + #expect(FileSystemTypeName.hfs.rawValue == "hfs") + // The root volume is APFS on every supported Apple platform. + #expect(try StatFS("/").typeName == .apfs) + } + #endif + @available(System 199, *) @Test func descriptions() throws { #expect(MountFlags.readOnly.description == "[.readOnly]") @@ -417,7 +446,7 @@ private struct StatFSTests { let s = StatFS(rawValue: raw) let typeNameLength = MemoryLayout.size(ofValue: raw.f_fstypename) let mountPointLength = MemoryLayout.size(ofValue: raw.f_mntonname) - #expect(s.typeName == String(repeating: "a", count: typeNameLength)) + #expect(s.typeName.rawValue == String(repeating: "a", count: typeNameLength)) #expect(s.mountPoint.string == String(repeating: "b", count: mountPointLength)) } #endif From b1f3496e3130b761906f425b175f9632feb8a73a Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Wed, 21 Oct 2026 13:49:53 -0600 Subject: [PATCH 8/8] Move table to doc comment, other comment updates --- Sources/CSystem/include/CSystemLinux.h | 3 +- Sources/System/FileSystem/MountFlags.swift | 113 ++++++++++----------- Sources/System/Internals/Constants.swift | 6 +- 3 files changed, 59 insertions(+), 63 deletions(-) diff --git a/Sources/CSystem/include/CSystemLinux.h b/Sources/CSystem/include/CSystemLinux.h index b7665de..35d0372 100644 --- a/Sources/CSystem/include/CSystemLinux.h +++ b/Sources/CSystem/include/CSystemLinux.h @@ -12,8 +12,7 @@ // Glibc doesn't export eventfd, which the tests use. #include -// Test-only: libc's `ST_*` values, which glibc gates on _GNU_SOURCE. Defining -// that here would clash with SwiftGlibc, so shims.c defines it instead. +// Test-only getters for constants that require _GNU_SOURCE. unsigned long long _system_get_ST_RDONLY(void); unsigned long long _system_get_ST_NOSUID(void); unsigned long long _system_get_ST_NODEV(void); diff --git a/Sources/System/FileSystem/MountFlags.swift b/Sources/System/FileSystem/MountFlags.swift index 90a7f12..5053130 100644 --- a/Sources/System/FileSystem/MountFlags.swift +++ b/Sources/System/FileSystem/MountFlags.swift @@ -9,62 +9,6 @@ // //===----------------------------------------------------------------------===// -// |-----------------------------------------------------------------------------------------------------------------------------| -// | Swift API to C Mapping | -// |-----------------------------------------------------------------------------------------------------------------------------| -// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android | -// |--------------------------------|----------------------|-----------------|-----------------|----------------|----------------| -// | readOnly | MNT_RDONLY | MNT_RDONLY | MNT_RDONLY | ST_RDONLY | ST_RDONLY | -// | synchronous | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | MNT_SYNCHRONOUS | ST_SYNCHRONOUS | ST_SYNCHRONOUS | -// | noExecution | MNT_NOEXEC | MNT_NOEXEC | MNT_NOEXEC | ST_NOEXEC | ST_NOEXEC | -// | noSetUserID | MNT_NOSUID | MNT_NOSUID | MNT_NOSUID | ST_NOSUID | ST_NOSUID | -// | noAccessTime | MNT_NOATIME | MNT_NOATIME | MNT_NOATIME | ST_NOATIME | ST_NOATIME | -// | noDevices | MNT_NODEV | N/A | MNT_NODEV | ST_NODEV | ST_NODEV | -// | mandatoryLocking | N/A | N/A | N/A | ST_MANDLOCK | ST_MANDLOCK | -// | noDirectoryAccessTime | N/A | N/A | N/A | ST_NODIRATIME | ST_NODIRATIME | -// | relativeAccessTime | N/A | N/A | N/A | ST_RELATIME | ST_RELATIME | -// | noSymlinkFollowing | N/A | MNT_NOSYMFOLLOW | N/A | ST_NOSYMFOLLOW | ST_NOSYMFOLLOW | -// | asynchronous | MNT_ASYNC | MNT_ASYNC | MNT_ASYNC | N/A | N/A | -// | exported | MNT_EXPORTED | MNT_EXPORTED | MNT_EXPORTED | N/A | N/A | -// | local | MNT_LOCAL | MNT_LOCAL | MNT_LOCAL | N/A | N/A | -// | quotasEnabled | MNT_QUOTA | MNT_QUOTA | MNT_QUOTA | N/A | N/A | -// | rootFileSystem | MNT_ROOTFS | MNT_ROOTFS | MNT_ROOTFS | N/A | N/A | -// | union | MNT_UNION | MNT_UNION | N/A | N/A | N/A | -// | automounted | MNT_AUTOMOUNTED | MNT_AUTOMOUNTED | N/A | N/A | N/A | -// | multiLabel | MNT_MULTILABEL | MNT_MULTILABEL | N/A | N/A | N/A | -// | exportedReadOnly | N/A | MNT_EXRDONLY | MNT_EXRDONLY | N/A | N/A | -// | exportedByDefault | N/A | MNT_DEFEXPORTED | MNT_DEFEXPORTED | N/A | N/A | -// | exportedAnonymously | N/A | MNT_EXPORTANON | MNT_EXPORTANON | N/A | N/A | -// | softUpdates | N/A | MNT_SOFTDEP | MNT_SOFTDEP | N/A | N/A | -// | contentProtection | MNT_CPROTECT | N/A | N/A | N/A | N/A | -// | removable | MNT_REMOVABLE | N/A | N/A | N/A | N/A | -// | quarantined | MNT_QUARANTINE | N/A | N/A | N/A | N/A | -// | supportsVolfs | MNT_DOVOLFS | N/A | N/A | N/A | N/A | -// | noBrowsing | MNT_DONTBROWSE | N/A | N/A | N/A | N/A | -// | ignoresOwnership | MNT_IGNORE_OWNERSHIP | N/A | N/A | N/A | N/A | -// | journaled | MNT_JOURNALED | N/A | N/A | N/A | N/A | -// | noUserExtendedAttributes | MNT_NOUSERXATTR | N/A | N/A | N/A | N/A | -// | defersWrites | MNT_DEFWRITE | N/A | N/A | N/A | N/A | -// | noSymlinkFollowingAtMountPoint | MNT_NOFOLLOW | N/A | N/A | N/A | N/A | -// | snapshot | MNT_SNAPSHOT | N/A | N/A | N/A | N/A | -// | strictAccessTime | MNT_STRICTATIME | N/A | N/A | N/A | N/A | -// | exportedWithKerberos | N/A | MNT_EXKERB | N/A | N/A | N/A | -// | exportedPublicly | N/A | MNT_EXPUBLIC | N/A | N/A | N/A | -// | posixACLs | N/A | MNT_ACLS | N/A | N/A | N/A | -// | geomJournaled | N/A | MNT_GJOURNAL | N/A | N/A | N/A | -// | excludedFromDiskFreeReports | N/A | MNT_IGNORE | N/A | N/A | N/A | -// | nfs4ACLs | N/A | MNT_NFS4ACLS | N/A | N/A | N/A | -// | noClusteredReads | N/A | MNT_NOCLUSTERR | N/A | N/A | N/A | -// | noClusteredWrites | N/A | MNT_NOCLUSTERW | N/A | N/A | N/A | -// | setUserIDDirectories | N/A | MNT_SUIDDIR | N/A | N/A | N/A | -// | softUpdatesJournaling | N/A | MNT_SUJ | N/A | N/A | N/A | -// | untrusted | N/A | MNT_UNTRUSTED | N/A | N/A | N/A | -// | userMounted | N/A | MNT_USER | N/A | N/A | N/A | -// | verified | N/A | MNT_VERIFIED | N/A | N/A | N/A | -// | noPermissionChecks | N/A | N/A | MNT_NOPERM | N/A | N/A | -// | writeExecuteAllowed | N/A | N/A | MNT_WXALLOWED | N/A | N/A | -// |-----------------------------------------------------------------------------------------------------------------------------| - #if !os(Windows) && !os(WASI) /// Flags describing a mounted file system. @@ -74,6 +18,60 @@ /// like `local` and `rootFileSystem`, describe state the kernel reports. /// /// - Note: Not available on Windows or WASI. +/// +/// The corresponding C constants available on each platform: +/// +/// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android | +/// |----------------------------------|------------------------|-------------------|-------------------|------------------|------------------| +/// | `readOnly` | `MNT_RDONLY` | `MNT_RDONLY` | `MNT_RDONLY` | `ST_RDONLY` | `ST_RDONLY` | +/// | `synchronous` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `ST_SYNCHRONOUS` | `ST_SYNCHRONOUS` | +/// | `noExecution` | `MNT_NOEXEC` | `MNT_NOEXEC` | `MNT_NOEXEC` | `ST_NOEXEC` | `ST_NOEXEC` | +/// | `noSetUserID` | `MNT_NOSUID` | `MNT_NOSUID` | `MNT_NOSUID` | `ST_NOSUID` | `ST_NOSUID` | +/// | `noAccessTime` | `MNT_NOATIME` | `MNT_NOATIME` | `MNT_NOATIME` | `ST_NOATIME` | `ST_NOATIME` | +/// | `noDevices` | `MNT_NODEV` | N/A | `MNT_NODEV` | `ST_NODEV` | `ST_NODEV` | +/// | `mandatoryLocking` | N/A | N/A | N/A | `ST_MANDLOCK` | `ST_MANDLOCK` | +/// | `noDirectoryAccessTime` | N/A | N/A | N/A | `ST_NODIRATIME` | `ST_NODIRATIME` | +/// | `relativeAccessTime` | N/A | N/A | N/A | `ST_RELATIME` | `ST_RELATIME` | +/// | `noSymlinkFollowing` | N/A | `MNT_NOSYMFOLLOW` | N/A | `ST_NOSYMFOLLOW` | `ST_NOSYMFOLLOW` | +/// | `asynchronous` | `MNT_ASYNC` | `MNT_ASYNC` | `MNT_ASYNC` | N/A | N/A | +/// | `exported` | `MNT_EXPORTED` | `MNT_EXPORTED` | `MNT_EXPORTED` | N/A | N/A | +/// | `local` | `MNT_LOCAL` | `MNT_LOCAL` | `MNT_LOCAL` | N/A | N/A | +/// | `quotasEnabled` | `MNT_QUOTA` | `MNT_QUOTA` | `MNT_QUOTA` | N/A | N/A | +/// | `rootFileSystem` | `MNT_ROOTFS` | `MNT_ROOTFS` | `MNT_ROOTFS` | N/A | N/A | +/// | `union` | `MNT_UNION` | `MNT_UNION` | N/A | N/A | N/A | +/// | `automounted` | `MNT_AUTOMOUNTED` | `MNT_AUTOMOUNTED` | N/A | N/A | N/A | +/// | `multiLabel` | `MNT_MULTILABEL` | `MNT_MULTILABEL` | N/A | N/A | N/A | +/// | `exportedReadOnly` | N/A | `MNT_EXRDONLY` | `MNT_EXRDONLY` | N/A | N/A | +/// | `exportedByDefault` | N/A | `MNT_DEFEXPORTED` | `MNT_DEFEXPORTED` | N/A | N/A | +/// | `exportedAnonymously` | N/A | `MNT_EXPORTANON` | `MNT_EXPORTANON` | N/A | N/A | +/// | `softUpdates` | N/A | `MNT_SOFTDEP` | `MNT_SOFTDEP` | N/A | N/A | +/// | `contentProtection` | `MNT_CPROTECT` | N/A | N/A | N/A | N/A | +/// | `removable` | `MNT_REMOVABLE` | N/A | N/A | N/A | N/A | +/// | `quarantined` | `MNT_QUARANTINE` | N/A | N/A | N/A | N/A | +/// | `supportsVolfs` | `MNT_DOVOLFS` | N/A | N/A | N/A | N/A | +/// | `noBrowsing` | `MNT_DONTBROWSE` | N/A | N/A | N/A | N/A | +/// | `ignoresOwnership` | `MNT_IGNORE_OWNERSHIP` | N/A | N/A | N/A | N/A | +/// | `journaled` | `MNT_JOURNALED` | N/A | N/A | N/A | N/A | +/// | `noUserExtendedAttributes` | `MNT_NOUSERXATTR` | N/A | N/A | N/A | N/A | +/// | `defersWrites` | `MNT_DEFWRITE` | N/A | N/A | N/A | N/A | +/// | `noSymlinkFollowingAtMountPoint` | `MNT_NOFOLLOW` | N/A | N/A | N/A | N/A | +/// | `snapshot` | `MNT_SNAPSHOT` | N/A | N/A | N/A | N/A | +/// | `strictAccessTime` | `MNT_STRICTATIME` | N/A | N/A | N/A | N/A | +/// | `exportedWithKerberos` | N/A | `MNT_EXKERB` | N/A | N/A | N/A | +/// | `exportedPublicly` | N/A | `MNT_EXPUBLIC` | N/A | N/A | N/A | +/// | `posixACLs` | N/A | `MNT_ACLS` | N/A | N/A | N/A | +/// | `geomJournaled` | N/A | `MNT_GJOURNAL` | N/A | N/A | N/A | +/// | `excludedFromDiskFreeReports` | N/A | `MNT_IGNORE` | N/A | N/A | N/A | +/// | `nfs4ACLs` | N/A | `MNT_NFS4ACLS` | N/A | N/A | N/A | +/// | `noClusteredReads` | N/A | `MNT_NOCLUSTERR` | N/A | N/A | N/A | +/// | `noClusteredWrites` | N/A | `MNT_NOCLUSTERW` | N/A | N/A | N/A | +/// | `setUserIDDirectories` | N/A | `MNT_SUIDDIR` | N/A | N/A | N/A | +/// | `softUpdatesJournaling` | N/A | `MNT_SUJ` | N/A | N/A | N/A | +/// | `untrusted` | N/A | `MNT_UNTRUSTED` | N/A | N/A | N/A | +/// | `userMounted` | N/A | `MNT_USER` | N/A | N/A | N/A | +/// | `verified` | N/A | `MNT_VERIFIED` | N/A | N/A | N/A | +/// | `noPermissionChecks` | N/A | N/A | `MNT_NOPERM` | N/A | N/A | +/// | `writeExecuteAllowed` | N/A | N/A | `MNT_WXALLOWED` | N/A | N/A | @frozen @available(System 199, *) public struct MountFlags: OptionSet, Sendable, Hashable, Codable { @@ -233,8 +231,7 @@ public struct MountFlags: OptionSet, Sendable, Hashable, Codable { // MARK: Flags Available on Darwin and FreeBSD #if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) - /// The file system is unioned with the underlying file system, rather than - /// obscuring it. + /// The file system is unioned with the underlying file system. /// /// - Note: Only available on Darwin and FreeBSD. /// diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 3a03dc1..4db4aea 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -809,9 +809,9 @@ internal var _SF_SNAPSHOT: UInt32 { UInt32(bitPattern: SF_SNAPSHOT) } // MARK: ST_* bits on Linux and Android -// Literal bits to keep `@_alwaysEmitIntoClient` semantics. Calling CSystem's -// `_system_get_ST_*` getters would put a CSystem symbol in every client, block -// constant folding, and fail to compile under an `internal import CSystem`. +// Literal bits to keep our `@_alwaysEmitIntoClient` semantics. Calling +// CSystem's `_system_get_ST_*` getters would put a CSystem symbol in every +// client, block constant folding, and require a public `import CSystem`. // `StatFSTests.mountFlagBitsMatchLibc` checks the literals against libc. #if os(Linux) || os(Android) @available(System 199, *)