Merge pull request #361 from jrflat/statfs-implementation

[Implementation] StatFS and supporting types
This commit is contained in:
Jonathan Flat authored and GitHub committed 2026-11-04 12:54:26 -07:00
commit 90a005db2f
15 files changed
+2496 -3

No files matched your search

+7 -1
View File
@@ -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,
+3
View File
@@ -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)
+12
View File
@@ -12,6 +12,18 @@
// Glibc doesn't export eventfd, which the tests use.
#include <sys/eventfd.h>
// Test-only getters for constants that require _GNU_SOURCE.
unsigned long long _system_get_ST_RDONLY(void);
unsigned long long _system_get_ST_NOSUID(void);
unsigned long long _system_get_ST_NODEV(void);
unsigned long long _system_get_ST_NOEXEC(void);
unsigned long long _system_get_ST_SYNCHRONOUS(void);
unsigned long long _system_get_ST_MANDLOCK(void);
unsigned long long _system_get_ST_NOATIME(void);
unsigned long long _system_get_ST_NODIRATIME(void);
unsigned long long _system_get_ST_RELATIME(void);
unsigned long long _system_get_ST_NOSYMFOLLOW(void);
#if !defined(__ANDROID__)
#include <stddef.h>
#include "io_uring.h"
+18
View File
@@ -17,9 +17,27 @@
#ifdef __linux__
#define _GNU_SOURCE
#include <signal.h>
#include <sys/statvfs.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <CSystemLinux.h>
unsigned long long _system_get_ST_RDONLY(void) { return ST_RDONLY; }
unsigned long long _system_get_ST_NOSUID(void) { return ST_NOSUID; }
unsigned long long _system_get_ST_NODEV(void) { return ST_NODEV; }
unsigned long long _system_get_ST_NOEXEC(void) { return ST_NOEXEC; }
unsigned long long _system_get_ST_SYNCHRONOUS(void) { return ST_SYNCHRONOUS; }
unsigned long long _system_get_ST_MANDLOCK(void) { return ST_MANDLOCK; }
unsigned long long _system_get_ST_NOATIME(void) { return ST_NOATIME; }
unsigned long long _system_get_ST_NODIRATIME(void) { return ST_NODIRATIME; }
unsigned long long _system_get_ST_RELATIME(void) { return ST_RELATIME; }
// ST_NOSYMFOLLOW wasn't defined until glibc 2.34. 0x2000 is the bit the
// kernel's internal <linux/statfs.h> and newer glibc both use.
#ifndef ST_NOSYMFOLLOW
#define ST_NOSYMFOLLOW 0x2000
#endif
unsigned long long _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; }
#endif
#include <errno.h>
+19
View File
@@ -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
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>"
$<INSTALL_INTERFACE:include/CSystemStatFS>)
install(FILES
CSystemStatFS.h
module.modulemap
DESTINATION include/CSystemStatFS)
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystemStatFS)
+18
View File
@@ -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 <sys/vfs.h>,
// 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 <sys/vfs.h>
#endif
+4
View File
@@ -0,0 +1,4 @@
module CSystemStatFS [system] {
header "CSystemStatFS.h"
export *
}
+8 -2
View File
@@ -1,7 +1,7 @@
#[[
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
@@ -61,7 +61,9 @@ target_sources(SystemPackage PRIVATE
FileSystem/FileMode.swift
FileSystem/FileType.swift
FileSystem/Identifiers.swift
FileSystem/Stat.swift)
FileSystem/MountFlags.swift
FileSystem/Stat.swift
FileSystem/StatFS.swift)
if(CMAKE_SYSTEM_NAME STREQUAL Linux)
target_sources(SystemPackage PRIVATE
IORing/IOCompletion.swift
@@ -82,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)
+647
View File
@@ -0,0 +1,647 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if !os(Windows) && !os(WASI)
/// Flags describing a mounted file system.
///
/// 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: Not available on Windows or WASI.
///
/// The corresponding C constants available on each platform:
///
/// | MountFlags | Darwin | FreeBSD | OpenBSD | Linux | Android |
/// |----------------------------------|------------------------|-------------------|-------------------|------------------|------------------|
/// | `readOnly` | `MNT_RDONLY` | `MNT_RDONLY` | `MNT_RDONLY` | `ST_RDONLY` | `ST_RDONLY` |
/// | `synchronous` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `MNT_SYNCHRONOUS` | `ST_SYNCHRONOUS` | `ST_SYNCHRONOUS` |
/// | `noExecution` | `MNT_NOEXEC` | `MNT_NOEXEC` | `MNT_NOEXEC` | `ST_NOEXEC` | `ST_NOEXEC` |
/// | `noSetUserID` | `MNT_NOSUID` | `MNT_NOSUID` | `MNT_NOSUID` | `ST_NOSUID` | `ST_NOSUID` |
/// | `noAccessTime` | `MNT_NOATIME` | `MNT_NOATIME` | `MNT_NOATIME` | `ST_NOATIME` | `ST_NOATIME` |
/// | `noDevices` | `MNT_NODEV` | N/A | `MNT_NODEV` | `ST_NODEV` | `ST_NODEV` |
/// | `mandatoryLocking` | N/A | N/A | N/A | `ST_MANDLOCK` | `ST_MANDLOCK` |
/// | `noDirectoryAccessTime` | N/A | N/A | N/A | `ST_NODIRATIME` | `ST_NODIRATIME` |
/// | `relativeAccessTime` | N/A | N/A | N/A | `ST_RELATIME` | `ST_RELATIME` |
/// | `noSymlinkFollowing` | N/A | `MNT_NOSYMFOLLOW` | N/A | `ST_NOSYMFOLLOW` | `ST_NOSYMFOLLOW` |
/// | `asynchronous` | `MNT_ASYNC` | `MNT_ASYNC` | `MNT_ASYNC` | N/A | N/A |
/// | `exported` | `MNT_EXPORTED` | `MNT_EXPORTED` | `MNT_EXPORTED` | N/A | N/A |
/// | `local` | `MNT_LOCAL` | `MNT_LOCAL` | `MNT_LOCAL` | N/A | N/A |
/// | `quotasEnabled` | `MNT_QUOTA` | `MNT_QUOTA` | `MNT_QUOTA` | N/A | N/A |
/// | `rootFileSystem` | `MNT_ROOTFS` | `MNT_ROOTFS` | `MNT_ROOTFS` | N/A | N/A |
/// | `union` | `MNT_UNION` | `MNT_UNION` | N/A | N/A | N/A |
/// | `automounted` | `MNT_AUTOMOUNTED` | `MNT_AUTOMOUNTED` | N/A | N/A | N/A |
/// | `multiLabel` | `MNT_MULTILABEL` | `MNT_MULTILABEL` | N/A | N/A | N/A |
/// | `exportedReadOnly` | N/A | `MNT_EXRDONLY` | `MNT_EXRDONLY` | N/A | N/A |
/// | `exportedByDefault` | N/A | `MNT_DEFEXPORTED` | `MNT_DEFEXPORTED` | N/A | N/A |
/// | `exportedAnonymously` | N/A | `MNT_EXPORTANON` | `MNT_EXPORTANON` | N/A | N/A |
/// | `softUpdates` | N/A | `MNT_SOFTDEP` | `MNT_SOFTDEP` | N/A | N/A |
/// | `contentProtection` | `MNT_CPROTECT` | N/A | N/A | N/A | N/A |
/// | `removable` | `MNT_REMOVABLE` | N/A | N/A | N/A | N/A |
/// | `quarantined` | `MNT_QUARANTINE` | N/A | N/A | N/A | N/A |
/// | `supportsVolfs` | `MNT_DOVOLFS` | N/A | N/A | N/A | N/A |
/// | `noBrowsing` | `MNT_DONTBROWSE` | N/A | N/A | N/A | N/A |
/// | `ignoresOwnership` | `MNT_IGNORE_OWNERSHIP` | N/A | N/A | N/A | N/A |
/// | `journaled` | `MNT_JOURNALED` | N/A | N/A | N/A | N/A |
/// | `noUserExtendedAttributes` | `MNT_NOUSERXATTR` | N/A | N/A | N/A | N/A |
/// | `defersWrites` | `MNT_DEFWRITE` | N/A | N/A | N/A | N/A |
/// | `noSymlinkFollowingAtMountPoint` | `MNT_NOFOLLOW` | N/A | N/A | N/A | N/A |
/// | `snapshot` | `MNT_SNAPSHOT` | N/A | N/A | N/A | N/A |
/// | `strictAccessTime` | `MNT_STRICTATIME` | N/A | N/A | N/A | N/A |
/// | `exportedWithKerberos` | N/A | `MNT_EXKERB` | N/A | N/A | N/A |
/// | `exportedPublicly` | N/A | `MNT_EXPUBLIC` | N/A | N/A | N/A |
/// | `posixACLs` | N/A | `MNT_ACLS` | N/A | N/A | N/A |
/// | `geomJournaled` | N/A | `MNT_GJOURNAL` | N/A | N/A | N/A |
/// | `excludedFromDiskFreeReports` | N/A | `MNT_IGNORE` | N/A | N/A | N/A |
/// | `nfs4ACLs` | N/A | `MNT_NFS4ACLS` | N/A | N/A | N/A |
/// | `noClusteredReads` | N/A | `MNT_NOCLUSTERR` | N/A | N/A | N/A |
/// | `noClusteredWrites` | N/A | `MNT_NOCLUSTERW` | N/A | N/A | N/A |
/// | `setUserIDDirectories` | N/A | `MNT_SUIDDIR` | N/A | N/A | N/A |
/// | `softUpdatesJournaling` | N/A | `MNT_SUJ` | N/A | N/A | N/A |
/// | `untrusted` | N/A | `MNT_UNTRUSTED` | N/A | N/A | N/A |
/// | `userMounted` | N/A | `MNT_USER` | N/A | N/A | N/A |
/// | `verified` | N/A | `MNT_VERIFIED` | N/A | N/A | N/A |
/// | `noPermissionChecks` | N/A | N/A | `MNT_NOPERM` | N/A | N/A |
/// | `writeExecuteAllowed` | N/A | N/A | `MNT_WXALLOWED` | N/A | N/A |
@frozen
@available(System 199, *)
public struct MountFlags: OptionSet, Sendable, Hashable, Codable {
/// The raw C flags.
@_alwaysEmitIntoClient
public let rawValue: CInterop.MountFlags
/// Creates a strongly-typed `MountFlags` from the raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.MountFlags) { self.rawValue = rawValue }
// MARK: Flags Available on All Platforms
/// The file system is mounted read-only, even for the super-user.
///
/// The corresponding C constant is `MNT_RDONLY` on Darwin and BSD,
/// or `ST_RDONLY` otherwise.
@_alwaysEmitIntoClient
public static var readOnly: MountFlags { MountFlags(rawValue: _MOUNT_RDONLY) }
/// The file system is written to synchronously.
///
/// The corresponding C constant is `MNT_SYNCHRONOUS` on Darwin and BSD,
/// or `ST_SYNCHRONOUS` otherwise.
@_alwaysEmitIntoClient
public static var synchronous: MountFlags { MountFlags(rawValue: _MOUNT_SYNCHRONOUS) }
/// Programs may not be executed from the file system.
///
/// The corresponding C constant is `MNT_NOEXEC` on Darwin and BSD,
/// or `ST_NOEXEC` otherwise.
@_alwaysEmitIntoClient
public static var noExecution: MountFlags { MountFlags(rawValue: _MOUNT_NOEXEC) }
/// Set-user-ID and set-group-ID (setuid and setgid) bits are not honored on
/// the file system.
///
/// The corresponding C constant is `MNT_NOSUID` on Darwin and BSD,
/// or `ST_NOSUID` otherwise.
@_alwaysEmitIntoClient
public static var noSetUserID: MountFlags { MountFlags(rawValue: _MOUNT_NOSUID) }
/// Access times are not updated on the file system.
///
/// - 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) }
// MARK: Flags Available on All Platforms Except FreeBSD
#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.
@_alwaysEmitIntoClient
public static var noDevices: MountFlags { MountFlags(rawValue: _MOUNT_NODEV) }
#endif
// MARK: Flags Available on Linux and 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)
/// Mandatory file locking is enabled on the file system.
///
/// - Note: Only available on Linux and Android.
/// - Note: Mandatory locking was deprecated and removed in Linux 5.15.
///
/// The corresponding C constant is `ST_MANDLOCK`.
@_alwaysEmitIntoClient
public static var mandatoryLocking: 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`.
@_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`.
@_alwaysEmitIntoClient
public static var relativeAccessTime: MountFlags { MountFlags(rawValue: _ST_RELATIME) }
#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.
///
/// - Note: Only available on Linux, Android, and FreeBSD.
///
/// The corresponding C constant is `MNT_NOSYMFOLLOW` on FreeBSD,
/// or `ST_NOSYMFOLLOW` on Linux and Android.
@_alwaysEmitIntoClient
public static var noSymlinkFollowing: MountFlags { MountFlags(rawValue: _MOUNT_NOSYMFOLLOW) }
#endif
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
/// The file system is written to asynchronously.
///
/// - 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.
///
/// - 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.
///
/// - 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.
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C constant is `MNT_QUOTA`.
@_alwaysEmitIntoClient
public static var quotasEnabled: MountFlags { MountFlags(rawValue: _MNT_QUOTA) }
/// The file system is the root file system.
///
/// - 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
// MARK: Flags Available on Darwin and FreeBSD
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
/// The file system is unioned with the underlying file system.
///
/// - 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`.
@_alwaysEmitIntoClient
public static var automounted: MountFlags { MountFlags(rawValue: _MNT_AUTOMOUNTED) }
/// The file system maintains Mandatory Access Control (MAC) labels for
/// individual objects.
///
/// - 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
// MARK: Flags Available on FreeBSD and OpenBSD
#if os(FreeBSD) || os(OpenBSD)
/// The file system is exported for reading only.
///
/// - 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 to any host by default.
///
/// - 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 is exported with all remote users mapped to the
/// anonymous user account.
///
/// - Note: Only available on FreeBSD and OpenBSD.
///
/// The corresponding C constant is `MNT_EXPORTANON`.
@_alwaysEmitIntoClient
public static var exportedAnonymously: MountFlags { MountFlags(rawValue: _MNT_EXPORTANON) }
/// Soft updates are enabled on the file system.
///
/// - Note: Only available on FreeBSD and OpenBSD. Accepted for compatibility
/// on OpenBSD, but has no effect there.
///
/// The corresponding C constant is `MNT_SOFTDEP`.
@_alwaysEmitIntoClient
public static var softUpdates: MountFlags { MountFlags(rawValue: _MNT_SOFTDEP) }
#endif
// MARK: Flags Available on Darwin Only
#if SYSTEM_PACKAGE_DARWIN
/// Per-file encrypted data protection is enabled on the file system.
///
/// - 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.
///
/// - 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.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_QUARANTINE`.
@_alwaysEmitIntoClient
public static var quarantined: 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`.
@_alwaysEmitIntoClient
public static var supportsVolfs: MountFlags { MountFlags(rawValue: _MNT_DOVOLFS) }
/// The file system should not be presented to the user for browsing
/// (e.g. hidden in Finder).
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_DONTBROWSE`.
@_alwaysEmitIntoClient
public static var noBrowsing: MountFlags { MountFlags(rawValue: _MNT_DONTBROWSE) }
/// The file system ignores ownership information.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_IGNORE_OWNERSHIP`.
@_alwaysEmitIntoClient
public static var ignoresOwnership: MountFlags { MountFlags(rawValue: _MNT_IGNORE_OWNERSHIP) }
/// The file system is 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.
///
/// - 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.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_DEFWRITE`.
@_alwaysEmitIntoClient
public static var defersWrites: MountFlags { MountFlags(rawValue: _MNT_DEFWRITE) }
/// Symbolic links are not followed when resolving the mount point.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_NOFOLLOW`.
@_alwaysEmitIntoClient
public static var noSymlinkFollowingAtMountPoint: MountFlags { MountFlags(rawValue: _MNT_NOFOLLOW) }
/// The file system is a 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 when files are read. Without this flag,
/// the file system may skip some access time updates for performance.
///
/// - Note: Only available on Darwin.
///
/// The corresponding C constant is `MNT_STRICTATIME`.
@_alwaysEmitIntoClient
public static var strictAccessTime: MountFlags { MountFlags(rawValue: _MNT_STRICTATIME) }
#endif
// MARK: Flags Available on FreeBSD Only
#if os(FreeBSD)
/// The file system is exported with Kerberos user-ID mapping.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_EXKERB`.
@_alwaysEmitIntoClient
public static var exportedWithKerberos: MountFlags { MountFlags(rawValue: _MNT_EXKERB) }
/// The file system is exported publicly for WebNFS clients.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_EXPUBLIC`.
@_alwaysEmitIntoClient
public static var exportedPublicly: MountFlags { MountFlags(rawValue: _MNT_EXPUBLIC) }
/// POSIX.1e ACLs are enabled on the file system.
///
/// - 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 is journaled by `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.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_IGNORE`.
@_alwaysEmitIntoClient
public static var excludedFromDiskFreeReports: MountFlags { MountFlags(rawValue: _MNT_IGNORE) }
/// NFSv4 ACLs are enabled on the file system.
///
/// - 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.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_NOCLUSTERR`.
@_alwaysEmitIntoClient
public static var noClusteredReads: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERR) }
/// Clustered writes are disabled on the file system.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_NOCLUSTERW`.
@_alwaysEmitIntoClient
public static var noClusteredWrites: MountFlags { MountFlags(rawValue: _MNT_NOCLUSTERW) }
/// Newly created files in a directory with the set-user-ID bit set are owned
/// by that directory's owner, rather than by the creating user.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_SUIDDIR`.
@_alwaysEmitIntoClient
public static var setUserIDDirectories: MountFlags { MountFlags(rawValue: _MNT_SUIDDIR) }
/// Soft updates journaling is enabled on the file system.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_SUJ`.
@_alwaysEmitIntoClient
public static var softUpdatesJournaling: MountFlags { MountFlags(rawValue: _MNT_SUJ) }
/// The file system is untrusted, as the integrity of its media is unknown.
///
/// - 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.
///
/// - Note: Only available on FreeBSD.
///
/// The corresponding C constant is `MNT_USER`.
@_alwaysEmitIntoClient
public static var userMounted: MountFlags { MountFlags(rawValue: _MNT_USER) }
/// The file system is marked as verified, so per-file integrity checks are
/// skipped on execution.
///
/// - 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
// MARK: Flags Available on OpenBSD Only
#if os(OpenBSD)
/// File permissions are not checked on the file system (FFS only).
///
/// - Note: Only available on OpenBSD.
///
/// The corresponding C constant is `MNT_NOPERM`.
@_alwaysEmitIntoClient
public static var noPermissionChecks: MountFlags { MountFlags(rawValue: _MNT_NOPERM) }
/// Programs residing on the file system may create memory mappings that are
/// both writable and executable.
///
/// By default, requesting such a mapping (via `mmap(2)` or `mprotect(2)`)
/// kills the process. This flag lifts that restriction.
///
/// - Note: Only available on OpenBSD.
///
/// The corresponding C constant is `MNT_WXALLOWED`.
@_alwaysEmitIntoClient
public static var writeExecuteAllowed: MountFlags { MountFlags(rawValue: _MNT_WXALLOWED) }
#endif
}
@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"),
(.quotasEnabled, ".quotasEnabled"),
(.rootFileSystem, ".rootFileSystem"),
(.union, ".union"),
(.automounted, ".automounted"),
(.multiLabel, ".multiLabel"),
(.contentProtection, ".contentProtection"),
(.removable, ".removable"),
(.quarantined, ".quarantined"),
(.supportsVolfs, ".supportsVolfs"),
(.noBrowsing, ".noBrowsing"),
(.ignoresOwnership, ".ignoresOwnership"),
(.journaled, ".journaled"),
(.noUserExtendedAttributes, ".noUserExtendedAttributes"),
(.defersWrites, ".defersWrites"),
(.noSymlinkFollowingAtMountPoint, ".noSymlinkFollowingAtMountPoint"),
(.snapshot, ".snapshot"),
(.strictAccessTime, ".strictAccessTime"),
]
#elseif os(FreeBSD)
let descriptions: [(Element, StaticString)] = [
(.readOnly, ".readOnly"),
(.synchronous, ".synchronous"),
(.noExecution, ".noExecution"),
(.noSetUserID, ".noSetUserID"),
(.noAccessTime, ".noAccessTime"),
(.noSymlinkFollowing, ".noSymlinkFollowing"),
(.asynchronous, ".asynchronous"),
(.exported, ".exported"),
(.local, ".local"),
(.quotasEnabled, ".quotasEnabled"),
(.rootFileSystem, ".rootFileSystem"),
(.union, ".union"),
(.automounted, ".automounted"),
(.multiLabel, ".multiLabel"),
(.exportedReadOnly, ".exportedReadOnly"),
(.exportedByDefault, ".exportedByDefault"),
(.exportedAnonymously, ".exportedAnonymously"),
(.softUpdates, ".softUpdates"),
(.exportedWithKerberos, ".exportedWithKerberos"),
(.exportedPublicly, ".exportedPublicly"),
(.posixACLs, ".posixACLs"),
(.geomJournaled, ".geomJournaled"),
(.excludedFromDiskFreeReports, ".excludedFromDiskFreeReports"),
(.nfs4ACLs, ".nfs4ACLs"),
(.noClusteredReads, ".noClusteredReads"),
(.noClusteredWrites, ".noClusteredWrites"),
(.setUserIDDirectories, ".setUserIDDirectories"),
(.softUpdatesJournaling, ".softUpdatesJournaling"),
(.untrusted, ".untrusted"),
(.userMounted, ".userMounted"),
(.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"),
(.quotasEnabled, ".quotasEnabled"),
(.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"),
(.mandatoryLocking, ".mandatoryLocking"),
(.noDirectoryAccessTime, ".noDirectoryAccessTime"),
(.relativeAccessTime, ".relativeAccessTime"),
(.noSymlinkFollowing, ".noSymlinkFollowing"),
]
#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)
+866
View File
@@ -0,0 +1,866 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if os(Windows)
/// A Swift wrapper of the C `statfs` struct.
///
/// - 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<CChar>` path.
public init(
_ path: UnsafePointer<CChar>,
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")
}
}
#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<CChar>` path.
public init(
_ path: UnsafePointer<CChar>,
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")
}
}
#else
// Must import here to use C statfs properties in @_alwaysEmitIntoClient APIs.
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
#if os(Linux)
import CSystemStatFS
#endif
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Android)
import Android
#else
#error("Unsupported Platform")
#endif
// MARK: - FileSystemID
/// 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 {
/// The raw C file system ID.
@_alwaysEmitIntoClient
public var rawValue: CInterop.FileSystemID
/// Creates a strongly-typed `FileSystemID` from the raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.FileSystemID) { self.rawValue = rawValue }
/// Creates a strongly-typed `FileSystemID` from the raw C value.
@_alwaysEmitIntoClient
public init(_ rawValue: CInterop.FileSystemID) { self.rawValue = rawValue }
}
// `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._words.0 == rhs._words.0 && lhs._words.1 == rhs._words.1
}
}
@available(System 199, *)
extension FileSystemID: Hashable {
@_alwaysEmitIntoClient
public func hash(into hasher: inout Hasher) {
hasher.combine(_words.0)
hasher.combine(_words.1)
}
}
@available(System 199, *)
extension FileSystemID: Codable {
@_alwaysEmitIntoClient
public func encode(to encoder: any Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(_words.0)
try container.encode(_words.1)
}
@_alwaysEmitIntoClient
public init(from decoder: any Decoder) throws {
var container = try decoder.unkeyedContainer()
let val0 = try container.decode(Int32.self)
let val1 = try container.decode(Int32.self)
self.init(_words: (val0, val1))
}
}
@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 os(Linux) || os(Android)
// MARK: - FileSystemType
/// A Swift wrapper of the C `f_type` file system type found in a `statfs`
/// struct.
///
/// - Note: Only available on Linux and Android.
@frozen
@available(System 199, *)
public struct FileSystemType: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C file system type.
@_alwaysEmitIntoClient
public var rawValue: UInt32
/// Creates a strongly-typed `FileSystemType` from the raw C value.
@_alwaysEmitIntoClient
public init(rawValue: UInt32) { self.rawValue = rawValue }
/// Creates a strongly-typed `FileSystemType` from the raw C value.
@_alwaysEmitIntoClient
public init(_ rawValue: UInt32) { self.rawValue = rawValue }
}
#endif // os(Linux) || os(Android)
#if SYSTEM_PACKAGE_DARWIN
// MARK: - FileSystemSubtype
/// A Swift wrapper of the C `f_fssubtype` file system subtype found in a
/// `statfs` struct on Darwin.
///
/// - Note: Only available on Darwin.
@frozen
@available(System 199, *)
public struct FileSystemSubtype: RawRepresentable, Sendable, Hashable, Codable {
/// The raw C file system subtype.
@_alwaysEmitIntoClient
public var rawValue: UInt32
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
@_alwaysEmitIntoClient
public init(rawValue: UInt32) { self.rawValue = rawValue }
/// Creates a strongly-typed `FileSystemSubtype` from the raw C value.
@_alwaysEmitIntoClient
public init(_ rawValue: UInt32) { self.rawValue = rawValue }
}
#endif
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
// MARK: - FileSystemTypeName
/// A Swift wrapper of the C `f_fstypename` file system type name found in a
/// `statfs` struct.
///
/// - Note: Only available on Darwin and BSD.
@frozen
@available(System 199, *)
public struct FileSystemTypeName
: RawRepresentable, Sendable, Hashable, Codable, ExpressibleByStringLiteral
{
/// The raw file system type name.
@_alwaysEmitIntoClient
public var rawValue: String
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
@_alwaysEmitIntoClient
public init(rawValue: String) { self.rawValue = rawValue }
/// Creates a strongly-typed `FileSystemTypeName` from the raw name.
@_alwaysEmitIntoClient
public init(_ rawValue: String) { self.rawValue = rawValue }
/// Creates a `FileSystemTypeName` from a string literal, such as `"apfs"`.
@_alwaysEmitIntoClient
public init(stringLiteral value: String) { self.rawValue = value }
// MARK: Type Names Available on Darwin Only
#if SYSTEM_PACKAGE_DARWIN
/// The Apple File System (APFS).
///
/// - Note: Only available on Darwin.
///
/// The corresponding `f_fstypename` value is `"apfs"`.
@_alwaysEmitIntoClient
public static var apfs: FileSystemTypeName { FileSystemTypeName(rawValue: "apfs") }
/// The Mac OS Extended file system (HFS Plus).
///
/// - Note: Only available on Darwin.
///
/// The corresponding `f_fstypename` value is `"hfs"`.
@_alwaysEmitIntoClient
public static var hfs: FileSystemTypeName { FileSystemTypeName(rawValue: "hfs") }
#endif
}
@available(System 199, *)
extension FileSystemTypeName: CustomStringConvertible, CustomDebugStringConvertible {
/// The file system type name, such as `apfs`.
@inline(never)
public var description: String { rawValue }
/// The file system type name as a quoted string, such as `"apfs"`.
public var debugDescription: String { description.debugDescription }
}
#endif // SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
// MARK: - StatFS
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
// Helpers for reading the fixed-size, NUL-terminated C character buffers
// (`f_fstypename`, `f_mntonname`, `f_mntfromname`) in Darwin/BSD `statfs`.
// If the buffer has no NUL (malformed), the entire buffer is used.
@available(System 199, *)
extension String {
@usableFromInline
internal init(_nullTerminatedBytes buffer: UnsafeRawBufferPointer) {
let bytes = buffer.prefix { $0 != 0 }
self = String(decoding: bytes, as: CInterop.PlatformUnicodeEncoding.self)
}
}
@available(System 199, *)
extension FilePath {
@usableFromInline
internal init(_nullTerminatedBytes buffer: UnsafeRawBufferPointer) {
let chars = buffer.bindMemory(to: CInterop.PlatformChar.self)
guard let base = chars.baseAddress else {
self = FilePath()
return
}
self = if chars.firstIndex(of: 0) != nil {
FilePath(platformString: base)
} else {
withUnsafeTemporaryAllocation(
of: CInterop.PlatformChar.self,
capacity: chars.count + 1
) { terminatedBuffer in
terminatedBuffer.baseAddress!.initialize(from: base, count: chars.count)
terminatedBuffer[chars.count] = 0
return FilePath(platformString: terminatedBuffer.baseAddress!)
}
}
}
}
#endif
/// A Swift wrapper of the C `statfs` struct.
///
/// - 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.
@_alwaysEmitIntoClient
public var rawValue: CInterop.StatFS
/// Creates a Swift `StatFS` from the raw C struct.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.StatFS) { self.rawValue = rawValue }
// MARK: Initializers
/// Creates a `StatFS` from a `FilePath`.
///
/// The corresponding C function is `statfs()`.
@_alwaysEmitIntoClient
public init(
_ path: FilePath,
retryOnInterrupt: Bool = true
) throws(Errno) {
self.rawValue = try path.withPlatformString {
Self._statfs($0, retryOnInterrupt: retryOnInterrupt)
}.get()
}
/// Creates a `StatFS` from a null-terminated `UnsafePointer<CChar>` path.
///
/// The corresponding C function is `statfs()`.
@_alwaysEmitIntoClient
public init(
_ path: UnsafePointer<CChar>,
retryOnInterrupt: Bool = true
) throws(Errno) {
self.rawValue = try Self._statfs(
path, retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal static func _statfs(
_ path: UnsafePointer<CChar>,
retryOnInterrupt: Bool
) -> Result<CInterop.StatFS, Errno> {
var result = CInterop.StatFS()
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_statfs(path, &result)
}.map { result }
}
/// Creates a `StatFS` from a `FileDescriptor`.
///
/// The corresponding C function is `fstatfs()`.
@_alwaysEmitIntoClient
public init(
_ fd: FileDescriptor,
retryOnInterrupt: Bool = true
) throws(Errno) {
self.rawValue = try Self._fstatfs(
fd, retryOnInterrupt: retryOnInterrupt
).get()
}
@usableFromInline
internal static func _fstatfs(
_ fd: FileDescriptor,
retryOnInterrupt: Bool
) -> Result<CInterop.StatFS, Errno> {
var result = CInterop.StatFS()
return nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
system_fstatfs(fd.rawValue, &result)
}.map { result }
}
// MARK: Properties
/// File system block size, in bytes.
///
/// - Note: On Darwin and BSD, this is the fundamental size for block counts.
/// 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) }
set { rawValue.f_bsize = .init(clamping: newValue) }
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
/// Block size for optimal data transfer, in bytes.
///
/// - 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) }
set { rawValue.f_iosize = .init(clamping: newValue) }
}
#else
/// File system fragment size, in bytes.
///
/// - 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) }
set { rawValue.f_frsize = .init(clamping: newValue) }
}
#endif
/// The fundamental block size used for space calculations, in bytes.
///
/// This is `blockSize` on Darwin and BSD, or `fragmentSize` otherwise.
@_alwaysEmitIntoClient
internal var _fundamentalBlockSize: UInt64 {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
UInt64(clamping: rawValue.f_bsize)
#else
UInt64(clamping: rawValue.f_frsize)
#endif
}
@_alwaysEmitIntoClient
internal func _saturatingSpace(_ blocks: UInt64) -> UInt64 {
let (result, overflow) = blocks.multipliedReportingOverflow(by: _fundamentalBlockSize)
return overflow ? .max : result
}
/// Total number of blocks in the file system.
///
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
/// otherwise.
///
/// The corresponding C property is `f_blocks`.
@_alwaysEmitIntoClient
public var totalBlocks: UInt64 {
get { UInt64(clamping: rawValue.f_blocks) }
set { rawValue.f_blocks = .init(clamping: newValue) }
}
/// Total size of the file system, in bytes.
///
/// - Note: Computed for convenience as `totalBlocks` times the fundamental
/// block size (see `totalBlocks`). Saturates to `UInt64.max` on overflow.
@_alwaysEmitIntoClient
public var totalSpace: UInt64 { _saturatingSpace(totalBlocks) }
/// Number of free blocks in the file system.
///
/// - Note: In units of `blockSize` on Darwin and BSD, or `fragmentSize`
/// otherwise.
///
/// The corresponding C property is `f_bfree`.
@_alwaysEmitIntoClient
public var freeBlocks: UInt64 {
get { UInt64(clamping: rawValue.f_bfree) }
set { rawValue.f_bfree = .init(clamping: newValue) }
}
/// Free space in the file system, in bytes.
///
/// - Note: Computed for convenience as `freeBlocks` times the fundamental
/// block size (see `freeBlocks`). Saturates to `UInt64.max` on overflow.
@_alwaysEmitIntoClient
public var freeSpace: UInt64 { _saturatingSpace(freeBlocks) }
/// Number of free blocks available to non-superuser.
///
/// - 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`.
@_alwaysEmitIntoClient
public var availableBlocks: UInt64 {
get { UInt64(clamping: rawValue.f_bavail) }
set { rawValue.f_bavail = .init(clamping: newValue) }
}
/// Available space in the file system for non-superuser, in bytes.
///
/// - Note: Computed for convenience as `availableBlocks` times the fundamental
/// block size (see `availableBlocks`). Saturates to `UInt64.max` on overflow.
@_alwaysEmitIntoClient
public var availableSpace: UInt64 { _saturatingSpace(availableBlocks) }
/// Total number of inodes in the file system.
///
/// The corresponding C property is `f_files`.
@_alwaysEmitIntoClient
public var totalInodes: UInt64 {
get { UInt64(clamping: rawValue.f_files) }
set { rawValue.f_files = .init(clamping: newValue) }
}
/// Number of free inodes in the file system.
///
/// - 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 os(OpenBSD)
/// Number of free inodes available to non-superuser.
///
/// - 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) }
set { rawValue.f_favail = .init(clamping: newValue) }
}
#endif
#if !SYSTEM_PACKAGE_DARWIN
/// Maximum length of a file name on the file system, in bytes.
///
/// - 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 {
#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
/// File system ID.
///
/// The corresponding C property is `f_fsid`.
@_alwaysEmitIntoClient
public var fileSystemID: FileSystemID {
get { FileSystemID(rawValue: rawValue.f_fsid) }
set { rawValue.f_fsid = newValue.rawValue }
}
/// Flags describing how the file system is mounted.
///
/// - 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)
#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
#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 os(Linux) || os(Android)
/// File system type.
///
/// - Note: This is the file system's magic number, such as `0xEF53` for
/// ext4. Only available on Linux and Android. On Darwin and BSD, use
/// `typeName` to identify the file system.
///
/// The corresponding C property is `f_type`.
@_alwaysEmitIntoClient
public var type: FileSystemType {
get {
// glibc's `f_type` is a signed `long` and can be negative.
FileSystemType(rawValue: UInt32(truncatingIfNeeded: rawValue.f_type))
}
set {
rawValue.f_type = .init(truncatingIfNeeded: newValue.rawValue)
}
}
#endif
#if SYSTEM_PACKAGE_DARWIN
/// File system subtype.
///
/// - Note: This is a numeric value whose meaning depends on `typeName`,
/// with no stable, public constants. Only available on Darwin.
///
/// The corresponding C property is `f_fssubtype`.
@_alwaysEmitIntoClient
public var subtype: FileSystemSubtype {
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.
///
/// - 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) }
set { rawValue.f_owner = newValue.rawValue }
}
/// File system type name, such as "apfs".
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_fstypename`.
@_alwaysEmitIntoClient
public var typeName: FileSystemTypeName {
FileSystemTypeName(rawValue: withUnsafeBytes(of: rawValue.f_fstypename) {
String(_nullTerminatedBytes: $0)
})
}
/// Directory where the file system is mounted, such as "/System/Volumes/Data".
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_mntonname`.
@_alwaysEmitIntoClient
public var mountPoint: FilePath {
withUnsafeBytes(of: rawValue.f_mntonname) {
FilePath(_nullTerminatedBytes: $0)
}
}
/// The source of the mounted file system, such as "/dev/disk3s7".
///
/// - Note: Only available on Darwin and BSD.
///
/// The corresponding C property is `f_mntfromname`.
@_alwaysEmitIntoClient
public var mountSource: FilePath {
withUnsafeBytes(of: rawValue.f_mntfromname) {
FilePath(_nullTerminatedBytes: $0)
}
}
#endif
}
// MARK: - StatFS Equatable & Hashable
@available(System 199, *)
extension StatFS {
/// Compares the file system metadata fields of two `StatFS` values,
/// including fields not exposed as properties, such as `f_flags_ext` on
/// Darwin.
///
/// 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.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.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,
rhs.rawValue.f_mntonname),
_nullTerminatedBytesEqual(lhs.rawValue.f_mntfromname,
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 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(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)
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
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
}
@inline(__always)
private static func _nullTerminatedBytesEqual<T>(_ lhs: T, _ rhs: T) -> Bool {
withUnsafeBytes(of: lhs) { lhsBytes in
withUnsafeBytes(of: rhs) { rhsBytes in
lhsBytes.prefix { $0 != 0 }.elementsEqual(rhsBytes.prefix { $0 != 0 })
}
}
}
// Feeds the length first so adjacent buffers can't run together.
@inline(__always)
private static func _combineNullTerminatedBytes<T>(
_ 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))
}
}
}
#endif // !os(Windows) && !os(WASI)
+23
View File
@@ -12,6 +12,11 @@ import Darwin
#elseif os(Windows)
import ucrt
#elseif canImport(Glibc)
#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 Musl
@@ -112,4 +117,22 @@ extension CInterop {
public typealias FileFlags = UInt32
#endif
}
#if !os(WASI)
@available(System 199, *)
extension CInterop {
/// The C `statfs` struct.
public typealias StatFS = statfs
#if SYSTEM_PACKAGE_DARWIN || os(OpenBSD)
public typealias MountFlags = UInt32
#elseif os(FreeBSD)
public typealias MountFlags = UInt64
#else
public typealias MountFlags = CUnsignedLong
#endif
public typealias FileSystemID = fsid_t
}
#endif
#endif
+336
View File
@@ -801,4 +801,340 @@ internal var _UF_SYSTEM: UInt32 { UInt32(bitPattern: UF_SYSTEM) }
internal var _SF_SNAPSHOT: UInt32 { UInt32(bitPattern: SF_SNAPSHOT) }
#endif
// MARK: - statfs Mount Flags
// `_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 our `@_alwaysEmitIntoClient` semantics. Calling
// CSystem's `_system_get_ST_*` getters would put a CSystem symbol in every
// client, block constant folding, and require a public `import CSystem`.
// `StatFSTests.mountFlagBitsMatchLibc` checks the literals against libc.
#if os(Linux) || os(Android)
@available(System 199, *)
@_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
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MOUNT_RDONLY: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_RDONLY)
#elseif os(Linux) || os(Android)
_ST_RDONLY_BIT
#endif
}
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MOUNT_SYNCHRONOUS: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_SYNCHRONOUS)
#elseif os(Linux) || os(Android)
_ST_SYNCHRONOUS_BIT
#endif
}
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NOEXEC: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NOEXEC)
#elseif os(Linux) || os(Android)
_ST_NOEXEC_BIT
#endif
}
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NOSUID: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NOSUID)
#elseif os(Linux) || os(Android)
_ST_NOSUID_BIT
#endif
}
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NOATIME: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NOATIME)
#elseif os(Linux) || os(Android)
_ST_NOATIME_BIT
#endif
}
// MARK: Flags Available on All Platforms Except FreeBSD
#if !os(FreeBSD)
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NODEV: CInterop.MountFlags {
#if SYSTEM_PACKAGE_DARWIN || os(OpenBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NODEV)
#elseif os(Linux) || os(Android)
_ST_NODEV_BIT
#endif
}
#endif
// MARK: Flags Available on Linux and Android
#if os(Linux) || os(Android)
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _ST_MANDLOCK: CInterop.MountFlags { _ST_MANDLOCK_BIT }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _ST_NODIRATIME: CInterop.MountFlags { _ST_NODIRATIME_BIT }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _ST_RELATIME: CInterop.MountFlags { _ST_RELATIME_BIT }
#endif
// MARK: Flags Available on Linux, Android, and FreeBSD
#if os(Linux) || os(Android) || os(FreeBSD)
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MOUNT_NOSYMFOLLOW: CInterop.MountFlags {
#if os(FreeBSD)
CInterop.MountFlags(truncatingIfNeeded: MNT_NOSYMFOLLOW)
#else
_ST_NOSYMFOLLOW_BIT
#endif
}
#endif
// MARK: Flags Available on Darwin, FreeBSD, and OpenBSD
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_ASYNC: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ASYNC) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_EXPORTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPORTED) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_LOCAL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_LOCAL) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_QUOTA: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_QUOTA) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_ROOTFS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ROOTFS) }
#endif
// MARK: Flags Available on Darwin and FreeBSD
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD)
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_UNION: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_UNION) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_AUTOMOUNTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_AUTOMOUNTED) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_MULTILABEL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_MULTILABEL) }
#endif
// MARK: Flags Available on FreeBSD and OpenBSD
#if os(FreeBSD) || os(OpenBSD)
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_EXRDONLY: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXRDONLY) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_DEFEXPORTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DEFEXPORTED) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_EXPORTANON: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPORTANON) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_SOFTDEP: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SOFTDEP) }
#endif
// MARK: Flags Available on Darwin Only
#if SYSTEM_PACKAGE_DARWIN
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_CPROTECT: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_CPROTECT) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_REMOVABLE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_REMOVABLE) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_QUARANTINE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_QUARANTINE) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_DOVOLFS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DOVOLFS) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_DONTBROWSE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DONTBROWSE) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_IGNORE_OWNERSHIP: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_IGNORE_OWNERSHIP) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_JOURNALED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_JOURNALED) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_NOUSERXATTR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOUSERXATTR) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_DEFWRITE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_DEFWRITE) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_NOFOLLOW: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOFOLLOW) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_SNAPSHOT: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SNAPSHOT) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_STRICTATIME: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_STRICTATIME) }
#endif
// MARK: Flags Available on FreeBSD Only
#if os(FreeBSD)
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_EXKERB: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXKERB) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_EXPUBLIC: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_EXPUBLIC) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_ACLS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_ACLS) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_GJOURNAL: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_GJOURNAL) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_IGNORE: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_IGNORE) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_NFS4ACLS: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NFS4ACLS) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_NOCLUSTERR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOCLUSTERR) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_NOCLUSTERW: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOCLUSTERW) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_SUIDDIR: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SUIDDIR) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_SUJ: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_SUJ) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_UNTRUSTED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_UNTRUSTED) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_USER: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_USER) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_VERIFIED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_VERIFIED) }
#endif
// MARK: Flags Available on OpenBSD Only
#if os(OpenBSD)
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_NOPERM: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_NOPERM) }
@available(System 199, *)
@_alwaysEmitIntoClient
internal var _MNT_WXALLOWED: CInterop.MountFlags { CInterop.MountFlags(truncatingIfNeeded: MNT_WXALLOWED) }
#endif
#endif // !os(WASI)
#endif // !os(Windows)
+14
View File
@@ -16,6 +16,9 @@ import Darwin
import ucrt
import WinSDK
#elseif canImport(Glibc)
#if os(Linux)
import CSystemStatFS
#endif
import Glibc
#elseif canImport(Musl)
import Musl
@@ -103,6 +106,17 @@ internal func system_fstat(_ fd: CInt, _ s: inout CInterop.Stat) -> Int32 {
internal func system_fstatat(_ fd: CInt, _ p: UnsafePointer<CChar>, _ s: inout CInterop.Stat, _ flags: CInt) -> Int32 {
fstatat(fd, p, &s, flags)
}
#if !os(WASI)
@available(System 199, *)
internal func system_statfs(_ p: UnsafePointer<CChar>, _ s: inout CInterop.StatFS) -> Int32 {
statfs(p, &s)
}
@available(System 199, *)
internal func system_fstatfs(_ fd: CInt, _ s: inout CInterop.StatFS) -> Int32 {
fstatfs(fd, &s)
}
#endif
#endif
// Convention: `system_platform_foo` is a
+22
View File
@@ -47,4 +47,26 @@ func _mivProbe(_ s: CInterop.Stat) {
_ = s.st_atim.tv_sec
_ = s.st_atim.tv_nsec
}
// 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
+499
View File
@@ -0,0 +1,499 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift System open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift System project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if !os(Windows) && !os(WASI)
import Testing
#if canImport(Foundation)
import Foundation
#endif
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif canImport(Glibc)
import CSystem
import Glibc
#elseif canImport(Musl)
import CSystem
import Musl
#elseif canImport(Android)
import CSystem
import Android
#else
#error("Unsupported Platform")
#endif
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
@Suite("StatFS")
private struct StatFSTests {
@available(System 199, *)
@Test func initializersAgree() async throws {
try withTemporaryFilePath(basename: "StatFS_initializersAgree") { tempDir in
let fromFilePath = try StatFS(tempDir)
let fromCString = try tempDir.withPlatformString { try StatFS($0) }
let dirFD = try FileDescriptor.open(tempDir, .readOnly)
defer { try? dirFD.close() }
let fromFD = try StatFS(dirFD)
#expect(fromFilePath.fileSystemID == fromCString.fileSystemID)
#expect(fromFilePath.fileSystemID == fromFD.fileSystemID)
#expect(fromFilePath.blockSize == fromFD.blockSize)
#expect(fromFilePath.totalBlocks == fromFD.totalBlocks)
#expect(fromFilePath.mountFlags == fromFD.mountFlags)
}
}
@available(System 199, *)
@Test func spaceAndBlocks() async throws {
try withTemporaryFilePath(basename: "StatFS_spaceAndBlocks") { tempDir in
let statfs = try StatFS(tempDir)
#expect(statfs.blockSize > 0)
#expect(statfs.totalBlocks > 0)
#expect(statfs.freeBlocks <= statfs.totalBlocks)
#expect(statfs.availableBlocks <= statfs.freeBlocks)
}
}
@available(System 199, *)
@Test func readOnlyFlagReflectsWritableFileSystem() async throws {
try withTemporaryFilePath(basename: "StatFS_readOnly") { tempDir in
let statfs = try StatFS(tempDir)
#expect(!statfs.mountFlags.contains(.readOnly))
}
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
@available(System 199, *)
@Test func darwinAndBSDFields() async throws {
try withTemporaryFilePath(basename: "StatFS_darwinBSD") { tempDir in
let statfs = try StatFS(tempDir)
#expect(statfs.preferredIOBlockSize > 0)
#expect(!statfs.typeName.rawValue.isEmpty)
#expect(statfs.mountPoint.isAbsolute)
#expect(!statfs.mountSource.string.isEmpty)
let mountStatFS = try StatFS(statfs.mountPoint)
#expect(mountStatFS.mountPoint == statfs.mountPoint)
#expect(mountStatFS.typeName == statfs.typeName)
}
}
#endif
@available(System 199, *)
@Test func nonexistentPathThrows() async throws {
#expect(throws: Errno.noSuchFileOrDirectory) {
_ = try StatFS("/var/empty/definitely/does/not/exist")
}
#expect(throws: Errno.noSuchFileOrDirectory) {
_ = try StatFS(FilePath("/var/empty/definitely/does/not/exist"))
}
}
@available(System 199, *)
@Test func badFileDescriptorThrows() async throws {
let badFD = FileDescriptor(rawValue: -1)
#expect(throws: Errno.badFileDescriptor) {
_ = try StatFS(badFD)
}
}
@available(System 199, *)
@Test func propertiesMatchRawFields() async throws {
try withTemporaryFilePath(basename: "StatFS_diff") { tempDir in
var raw = CInterop.StatFS()
try tempDir.withPlatformString {
try #require(statfs($0, &raw) == 0, "\(Errno.current)")
}
let s = StatFS(rawValue: raw)
#expect(s.blockSize == Int(raw.f_bsize))
#expect(s.totalBlocks == UInt64(clamping: raw.f_blocks))
#expect(s.freeBlocks == UInt64(clamping: raw.f_bfree))
#expect(s.availableBlocks == UInt64(clamping: raw.f_bavail))
#expect(s.totalInodes == UInt64(clamping: raw.f_files))
#expect(s.freeInodes == UInt64(clamping: raw.f_ffree))
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
#expect(s.preferredIOBlockSize == Int(raw.f_iosize))
#expect(s.owner.rawValue == raw.f_owner)
#expect(s.mountFlags.rawValue == raw.f_flags)
#expect(s.typeName.rawValue == withUnsafeBytes(of: raw.f_fstypename) {
$0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) }
})
#expect(s.mountPoint.string == withUnsafeBytes(of: raw.f_mntonname) {
$0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) }
})
#expect(s.mountSource.string == withUnsafeBytes(of: raw.f_mntfromname) {
$0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) }
})
#if SYSTEM_PACKAGE_DARWIN
#expect(s.subtype.rawValue == raw.f_fssubtype)
#elseif os(FreeBSD)
#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.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
}
}
// Each setter writes its own field, and clamps instead of trapping.
@available(System 199, *)
@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.subtype = FileSystemSubtype(8)
#expect(s.rawValue.f_fssubtype == 8)
#endif
s.mountFlags.insert(.readOnly)
#expect(s.mountFlags.contains(.readOnly))
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 elsewhere.
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
raw.f_bsize = 512
#else
raw.f_bsize = 4096 // Should not be used in calculations
raw.f_frsize = 512
#endif
raw.f_blocks = 1000
raw.f_bfree = 400
raw.f_bavail = 100
let s = StatFS(rawValue: raw)
#expect(s.totalSpace == 1000 * 512)
#expect(s.freeSpace == 400 * 512)
#expect(s.availableSpace == 100 * 512)
}
@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<UInt64>.size {
#expect(s.totalSpace == .max)
} else {
#expect(s.totalSpace == UInt64(raw.f_blocks) * 512)
}
}
#if os(FreeBSD) || os(OpenBSD)
@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
#if os(Linux)
// /proc files report size 0 via stat, so read until EOF instead of getting
// the size up front.
private func _readEntireFile(_ path: String) throws -> String {
let fd = try FileDescriptor.open(FilePath(path), .readOnly)
defer { try? fd.close() }
var result = [UInt8]()
var chunk = [UInt8](repeating: 0, count: 64 * 1024)
while true {
let n = try chunk.withUnsafeMutableBytes { try fd.read(into: $0) }
if n == 0 { break }
result.append(contentsOf: chunk[..<n])
}
return String(decoding: result, as: UTF8.self)
}
@available(System 199, *)
@Test func mountFlagsMatchProcMounts() throws {
let contents = try _readEntireFile("/proc/self/mounts")
// Fields: device, mountPoint, fsType, options, dump, pass.
var mounts: [String: Set<String>] = [:]
for line in contents.split(separator: "\n") {
let fields = line.split(separator: " ")
guard fields.count >= 4 else { continue }
let mountPoint = String(fields[1])
// Skip octal-escaped paths (spaces, tabs, etc.).
if mountPoint.contains(where: { $0 == "\\" }) { continue }
mounts[mountPoint] = Set(fields[3].split(separator: ",").map(String.init))
}
let checks: [(option: String, flag: MountFlags)] = [
("ro", .readOnly),
("noexec", .noExecution),
("nosuid", .noSetUserID),
("nodev", .noDevices),
("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<String> = ["/", "/proc", "/sys", "/dev", "/dev/shm", "/run"]
var verified = 0
for (mountPoint, options) in mounts where candidates.contains(mountPoint) {
guard let statfs = try? StatFS(FilePath(mountPoint)) else { continue }
for (option, flag) in checks {
#expect(
statfs.mountFlags.contains(flag) == options.contains(option),
"\(mountPoint): flag \(flag) disagrees with options \(options)"
)
}
verified += 1
}
// Guard against a parser that silently matched nothing: "/" always works.
#expect(verified > 0)
}
#endif
#if os(Linux) || os(Android)
@available(System 199, *)
@Test func typeIsMagicNumber() throws {
// PROC_SUPER_MAGIC from <linux/magic.h>.
#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 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)
#if canImport(Foundation)
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
}
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
@available(System 199, *)
@Test func fileSystemTypeNameConformances() throws {
let name: FileSystemTypeName = "apfs"
#expect(name == FileSystemTypeName(rawValue: "apfs"))
#expect(name == FileSystemTypeName("apfs"))
#expect(name != "hfs")
#expect(name.hashValue == FileSystemTypeName("apfs").hashValue)
#expect(name.description == "apfs")
#expect(name.debugDescription == #""apfs""#)
#if canImport(Foundation)
let data = try JSONEncoder().encode(name)
#expect(String(decoding: data, as: UTF8.self) == #""apfs""#)
#expect(try JSONDecoder().decode(FileSystemTypeName.self, from: data) == name)
#endif
}
#endif
#if SYSTEM_PACKAGE_DARWIN
@available(System 199, *)
@Test func fileSystemTypeNameConstants() throws {
#expect(FileSystemTypeName.apfs.rawValue == "apfs")
#expect(FileSystemTypeName.hfs.rawValue == "hfs")
// The root volume is APFS on every supported Apple platform.
#expect(try StatFS("/").typeName == .apfs)
}
#endif
@available(System 199, *)
@Test func descriptions() throws {
#expect(MountFlags.readOnly.description == "[.readOnly]")
let flags: MountFlags = [.readOnly, .noExecution]
#expect(flags.description == "[.readOnly, .noExecution]")
#expect(flags.debugDescription == flags.description)
#expect(MountFlags(rawValue: 0).description == "[]")
#expect(FileSystemID(_words: (1, 2)).description == "FileSystemID(1, 2)")
}
#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.rawValue == 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
let statfs = try StatFS(tempDir)
let copy = statfs
#expect(statfs == copy)
#expect(statfs.hashValue == copy.hashValue)
#expect(Set([statfs, copy]).count == 1)
var mutated = statfs
mutated.totalBlocks &+= 1
#expect(statfs != mutated)
// Reserved fields are not part of the value.
#if SYSTEM_PACKAGE_DARWIN
var reserved = statfs
reserved.rawValue.f_reserved.0 &+= 1
#expect(statfs == reserved)
#expect(statfs.hashValue == reserved.hashValue)
// 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
// it don't affect the value.
#if SYSTEM_PACKAGE_DARWIN || os(FreeBSD) || os(OpenBSD)
var trailing = statfs
try withUnsafeMutableBytes(of: &trailing.rawValue.f_mntonname) { buffer in
// The kernel always NUL-terminates the name buffers.
let terminator = try #require(buffer.firstIndex(of: 0))
if terminator + 1 < buffer.count {
buffer[terminator + 1] &+= 1
}
}
#expect(statfs == trailing)
#expect(statfs.hashValue == trailing.hashValue)
#endif
}
}
}
#endif