From cf36a2fe7bfce5a41d12db16003e6d02796a0773 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Wed, 30 Sep 2026 15:30:18 -0600 Subject: [PATCH] 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 }