Get the amount of free space of an unmounted storage device in Swift

Hi, i am working on a swift package library that gets information about all the disks connected to the mac and displays it organised into a tree structure, including the non-mounted storage devices attached to the machine.

My question is how can i get informations about unmounted devices like:

  • The amount of free space (when possible) of a partition or an APFS container
  • The space occupied by a single APFS volume

I am already using a combination of IOKit and Disk Arbitration for my library and i don't see this information anywhere in those frameworks, including the description dictionaries provided by Disk Arbitration.

Instead the terminal command diskutil info -plist [volume/partition BSD name here] gives me this info, but i can't just use it's output in my swift program (and obtaining it via a process object for example) since it doesn't work with the app sandbox, so i am looking for a sandbox-friendly way using just the API.

I hope you can help me figure this out, really any help is appreciated, thank you for your attention.

Hi,

Similar to your previous question, this would be worth talking about in a DTS incident (you can just file one to talk about all of this).

In terms of the specific question, I don't think you really can. The concept of "Free Space" is something that's exclusively defined by the volume format, so determining "free space" basically involves the same process as mounting a volume (that is, the volume structures need to be parsed and interpreted). Strictly speaking, you COULD determine the free space of an unmounted volume, but architecturally the system tends to avoid that. DiskArbitration is the lowest level API that "understands" volumes (IOKit doesn't), which is how it can return the volume name of unmounted volumes, but if it doesn't have that information then the info isn't really there.

Commenting on this point:

Instead the terminal command diskutil info -plist [volume/partition BSD name here] gives me this info,

I only looked at this very briefly, but the unmounted APFS volumes I tested all returned "0" for "FreeSpace". Looking at our code, I believe we're actually returning "NULL" for volumes where the free space can't be determined (generally because they're unmounted), which then gets turned into "0".

The other warning here is that APFS makes the concept of "volume free space" very vague, since the system is designed to try and cache as much as possible, then delete data a necessary. Those issue are what drove this article:

https://developer.apple.com/documentation/foundation/nsurlresourcekey/checking_volume_storage_capacity

-Kevin Elliott DTS Engineer, CoreOS/Hardware

Get the amount of free space of an unmounted storage device in Swift
 
 
Q