DEV Community

Darkø Tasevski
Darkø Tasevski

Posted on Edited on Originally published at darkotasevski.dev

Hashing an open file in Rust without /dev/fd

/dev/fd/<n> does at least three different things on Apple platforms, and I covered two of them in an earlier post (on iOS it doesn't exist, and on macOS opening it is a dup that shares the descriptor's offset), so this one is about the third, which I hit in a Mac app that runs in the App Sandbox, where opening that path asks for Full Disk Access and waits in the kernel for an answer to a consent dialog. The app ships on iOS and Mac Catalyst with its core in Rust, so fixing it meant hashing the descriptor from Swift into a Rust hasher, and the first version of that was more than twice as slow as the old path-based hash because of how UniFFI passes a Vec<u8>, and I'll go through both the hang and the slowdown.

A test suite that hangs on the Mac

The app checks whether two copies of a file are the same before it deletes one of them. It opens the file, verifies that the open file is the one it looked at a moment ago, keeps that descriptor open so that a rename or a replace at that path can't change which file it reads, hashes it with BLAKE3, and checks the file again afterwards, since an open descriptor doesn't stop anyone from writing to the file while it's being hashed. The BLAKE3 code lives in the app's Rust core and only took a path, so the Swift side handed it the descriptor as a path (the names in these samples are a bit simplified):

let fingerprint = try withExtendedLifetime(pin) {
    try checksum.fingerprint(ofFile: URL(fileURLWithPath: "/dev/fd/\(pin.fileDescriptor)"))
}
Enter fullscreen mode Exit fullscreen mode

On macOS that open is a dup of the descriptor, so the Rust side reads the same file that was verified, and since nothing had read from the freshly opened descriptor yet, the offset it shares with the copy was still at the start (the shared offset the previous post was about). When the code was written, just before the Mac build moved into the App Sandbox, it worked. A couple of weeks later, when the tests ran as the Mac Catalyst app, five of the 79 cases in the suite that covers this check started running into the 10-minute execution time allowance the app's test plan sets, while the iOS simulator passed them. Which case hung changed from run to run, because the test order is shuffled, and after one timeout, when XCTest had relaunched the test host, another case took 183 seconds and then passed, which I can't explain from the logs. The first guesses were a recent change on the main branch or something wrong with the machine's file daemons, and a small unsandboxed program that made the same file coordination calls answered in a few milliseconds, which made the daemons look healthy.

The spindump in the result bundle

When a test case runs past its time allowance, XCTest takes a spindump and attaches it to the result bundle, while the test log only says the case timed out. XCTest only enforces the allowance when test timeouts are turned on, in the test plan or with -test-timeouts-enabled YES, and without that a hang like this one just blocks. We can get the attachments out with:

xcrun xcresulttool export attachments --path Test.xcresult --output-path attachments
Enter fullscreen mode Exit fullscreen mode

The one stuck thread spent all 353 samples in the same place, inside Rust's File::open on /dev/fd/<n>, and the kernel frames under it were:

std::fs::File::open -> __open
  mac_vnode_check_open
    hook_vnode_check_open
      sb_evaluate_internal
        sandcastle_apply_approval_modifier
          approval_solicit
            approval_response_wait
              __WAITING_ON_APPROVAL_FROM_SANDBOXD__
Enter fullscreen mode Exit fullscreen mode

The thread was waiting on the sandbox to approve the open, and to see what the approval was for, the unified log for the same second, filtered to the sandbox daemon and TCC's authorization requests, is enough (with the full path, since zsh has a log builtin of its own):

/usr/bin/log show --start '<t0>' --end '<t1>' \
  --predicate 'process == "sandboxd" OR (process == "tccd" AND eventMessage CONTAINS "AUTHREQ")'
Enter fullscreen mode Exit fullscreen mode

At that second sandboxd logged a request approval, tccd evaluated kTCCServiceSystemPolicyAllFiles for the test host (the service behind Full Disk Access) with authValue=0, and the notification center brought up what looked like a consent dialog. The open waits on that answer, which nobody gives during an unattended test run. My guess is that TCC remembers an answer for that build's identity, which would explain why the hang came and went between runs and checkouts, and why an earlier run of the same tests had passed. Opening the same files by their real paths inside the app's container never prompted, only the /dev/fd open did, and as far as I can tell the sandbox doesn't treat /dev/fd/<n> as the file the descriptor points to but as a path outside the container, which needs Full Disk Access.

On an iPhone the same line can't work, because iOS has no /dev/fd at all (the previous post was about that, and the simulator only has one because it runs on the Mac's kernel), so on a device the check would never prove a duplicate and the copy would never be removed, although I haven't run it on a phone.

Hashing the descriptor instead

The descriptor is already open and verified, so the obvious fix is to read it rather than any path that leads to it. There were two ways to get its bytes into the Rust BLAKE3 hasher (CryptoKit has no BLAKE3, and the digest has to match the checksums the app already stores):

  • pass the raw descriptor to Rust and let Rust read it, which needs unsafe (BorrowedFd::borrow_raw) and makes Rust's correctness depend on Swift keeping that descriptor open for the whole call,
  • or export an incremental hasher from Rust and let Swift read the descriptor with pread and feed it chunk by chunk.

I went with the second one, and its Rust side is a small UniFFI object:

use std::sync::Mutex;

uniffi::setup_scaffolding!(); // once per crate, in lib.rs

#[derive(uniffi::Object)]
pub struct ChecksumHasher {
    state: Mutex<blake3::Hasher>,
}

#[uniffi::export]
impl ChecksumHasher {
    #[uniffi::constructor]
    pub fn new() -> Self {
        Self { state: Mutex::new(blake3::Hasher::new()) }
    }

    pub fn update(&self, data: &[u8]) {
        self.state.lock().unwrap().update(data);
    }

    pub fn finalize_hex(&self) -> String {
        self.state.lock().unwrap().finalize().to_hex().to_string()
    }
}
Enter fullscreen mode Exit fullscreen mode

The Mutex is there because UniFFI hands objects to Swift behind an Arc and exported methods only get &self, so the hasher's state needs interior mutability. It has to be the thread-safe kind, since UniFFI requires exported objects to be Send + Sync (Swift can call them from any thread), which rules out a RefCell.

And the Swift side reads the open descriptor from offset 0:

func blake3(ofOpenFile file: FileHandle) throws -> String {
    let hasher = ChecksumHasher()
    var buffer = Data(count: 1_024 * 1_024)
    var offset: off_t = 0
    while true {
        let count = buffer.withUnsafeMutableBytes { bytes in
            pread(file.fileDescriptor, bytes.baseAddress, bytes.count, offset)
        }
        if count == 0 { break }
        guard count > 0 else {
            if errno == EINTR { continue }
            throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
        }
        hasher.update(data: buffer.prefix(count))
        offset += off_t(count)
    }
    return hasher.finalizeHex()
}
Enter fullscreen mode Exit fullscreen mode

pread reads at an explicit offset and doesn't move the descriptor's own offset, so whoever holds the handle finds it where they left it, which also avoids the shared-offset problem from the previous post. A failed read has to throw, because with a break a file whose first read fails hashes to the BLAKE3 of empty input (the same af1349b9… as in the previous post), so any two unreadable files would look like duplicates, and the next step deletes one of them.

Getting the bytes into Rust

The first version of update took data: Vec<u8>, and I had assumed that passing a chunk across was a memory copy and negligible next to hashing the bytes, without measuring it. A review of the branch did measure it, with a standalone benchmark that runs UniFFI's own conversion code on 1 MiB chunks of a 1 GiB file, and the new path was 2.3 times slower than the old path-based hash:

Hashing 1 GiB Time
Rust reads the file by path 0.54 s
pread, the Vec<u8> conversion and hashing (Rust side) 1.27 s
of which lifting the Vec<u8> in Rust 0.68-0.71 s

In uniffi_core 0.32 a Vec<T> argument crosses the boundary serialized into a buffer (a length followed by each item), and on the Rust side Lift for Vec<T> reads it back one element at a time, so a 1 MiB chunk is 1,048,576 rounds of the per-item read. Stable Rust has no specialization, so Vec<u8> gets the same generic loop as any other vector, and a comment above UniFFI's vector conversions says that passing Vec<u8> directly is "future work". The plain memory copies on both sides were cheap in comparison (the Swift half took about 0.1 s per GiB).

UniFFI already has a better option for this, because a borrowed &[u8] argument isn't serialized at all. That only applies to &[u8] itself as a direct argument, not inside a record or an Option, and not as a return value. The generated Swift wraps the Data in withUnsafeBytes and hands Rust a pointer and a length:

fileprivate enum FfiConverterByRefBytes: FfiConverter {
    typealias SwiftType = Data
    typealias FfiType = ForeignBytes

    static func lower<R>(_ value: Data, _ body: (ForeignBytes) throws -> R) rethrows -> R {
        return try value.withUnsafeBytes { rawBuf in
            try body(ForeignBytes(rawBufferPointer: rawBuf))
        }
    }
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Changing update from Vec<u8> to &[u8] fixed it without touching the Swift call site. In a temporary test in the app's own test target (a different setup from the table, so these numbers only compare with each other), 512 MiB hashed through the descriptor took 0.47-0.49 s against 0.49-0.60 s by path, with equal digests, so it's back on par with Rust reading the file itself. The borrow only lives for the duration of the call, which is exactly what a hasher's update needs (the scope-bound lower above is how the generated code makes sure of it).

After that the Mac test run passed all 81 cases (the fix added two), and the log showed no sandbox approval requests from the test host.

Descriptors in a sandbox, and bytes across UniFFI

If you already hold a file open, read the descriptor (pread from offset 0 keeps its offset untouched) and don't reopen it through /dev/fd/<n>, because on iOS that path doesn't exist, on macOS it shares the descriptor's offset, and in a sandboxed Mac app the open can wait on a Full Disk Access dialog that nobody is there to answer, which on a test machine looks like a hang with no error at all. Holding the descriptor keeps the file from being swapped out from under you, not from being written to, so if you act on the hash, check the file again afterwards. When a Mac test hangs on something like this, the spindump XCTest attaches to the result bundle shows where it's stuck, and a probe that is meant to rule something out has to run inside the same sandbox, because an unsandboxed one proves nothing about a sandbox decision. For bulk bytes over UniFFI 0.32's Swift bindings, take a borrowed &[u8] argument rather than a Vec<u8>, since the vector is read back one byte at a time, and in general measure what passing a chunk across the boundary costs before treating it as a cheap copy.

Top comments (0)