Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

A process holding one of Peel's file locks can't be stopped with Ctrl-Z

Țugui Dragoș8a7f78a667f0
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Uninterrupted.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Uninterrupted.swift
index 53789d72..96694cf5 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Uninterrupted.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Uninterrupted.swift
@@ -1,5 +1,5 @@
import Darwin
-import Synchronization
+import PeelCore
/// Keeps `peel` running from a move, or a put back, until History records it: stopped in between, History would miss
/// what moved, or keep listing what went back.
@@ -8,28 +8,10 @@ enum Uninterrupted {
/// output piped into a command that has quit.
static let signals = [SIGINT, SIGTERM, SIGHUP, SIGQUIT, SIGPIPE]
- /// How many runs are under way, and the handlers the signals had before the first of them.
- private static let held = Mutex<(runs: Int, handlers: [sig_t?])>((0, []))
+ private static let ignored = IgnoredSignals(signals)
- /// Runs `work` with `signals` ignored. Ignored rather than blocked, since a signal blocked on one thread still
- /// stops the process through another. Only the last run to end gives each signal its handler back.
+ /// Runs `work` with `signals` ignored.
static func run<T>(_ work: () async throws -> T) async rethrows -> T {
- held.withLock { held in
- if held.runs == 0 {
- held.handlers = signals.map { signal($0, SIG_IGN) }
- }
- held.runs += 1
- }
- defer {
- held.withLock { held in
- held.runs -= 1
- if held.runs == 0 {
- for (number, handler) in zip(signals, held.handlers) {
- signal(number, handler)
- }
- }
- }
- }
- return try await work()
+ try await ignored.run(work)
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FileLock.swift b/Packages/PeelCore/Sources/PeelCore/Support/FileLock.swift
index 11b28f07..f9a76f69 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/FileLock.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/FileLock.swift
@@ -3,15 +3,26 @@ import Foundation
/// An advisory lock (`flock`) on a `.lock` file beside the file being changed, so a read and the write that
/// follows it are one step for every process and task that goes through here. When the lock file cannot be
-/// opened, the change still runs, without the lock.
+/// opened or locked, the change still runs, without the lock.
enum FileLock {
+ /// While a process waits for a lock or holds it, the terminal cannot stop it (Ctrl-Z): stopped there, it would
+ /// keep every other process that needs the file waiting until it went on.
+ private static let unstoppable = IgnoredSignals([SIGTSTP])
+
static func whileHeld<T>(beside url: URL, _ change: () -> T) -> T {
try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
let descriptor = open(url.path(percentEncoded: false) + ".lock", O_CREAT | O_RDWR | O_CLOEXEC, 0o600)
guard descriptor >= 0 else { return change() }
defer { close(descriptor) }
- flock(descriptor, LOCK_EX)
- defer { flock(descriptor, LOCK_UN) }
- return change()
+ return unstoppable.run {
+ // A signal caught while waiting ends the wait early (EINTR), without the lock.
+ var locked = flock(descriptor, LOCK_EX)
+ while locked != 0, errno == EINTR {
+ locked = flock(descriptor, LOCK_EX)
+ }
+ guard locked == 0 else { return change() }
+ defer { flock(descriptor, LOCK_UN) }
+ return change()
+ }
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/IgnoredSignals.swift b/Packages/PeelCore/Sources/PeelCore/Support/IgnoredSignals.swift
new file mode 100644
index 00000000..bea63aa7
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Support/IgnoredSignals.swift
@@ -0,0 +1,46 @@
+import Darwin
+import Synchronization
+
+/// Signals a process ignores while some work runs. Ignored rather than blocked, since a signal blocked on one
+/// thread still reaches the process through another. Runs may overlap: the first to begin sets the handlers
+/// aside, and only the last to end gives each signal its handler back. A signal belongs to one such set.
+public final class IgnoredSignals: Sendable {
+ public let signals: [Int32]
+ private let held = Mutex<(runs: Int, handlers: [sig_t?])>((0, []))
+
+ public init(_ signals: [Int32]) {
+ self.signals = signals
+ }
+
+ public func run<T>(_ work: () throws -> T) rethrows -> T {
+ begin()
+ defer { end() }
+ return try work()
+ }
+
+ public func run<T>(_ work: () async throws -> T) async rethrows -> T {
+ begin()
+ defer { end() }
+ return try await work()
+ }
+
+ private func begin() {
+ held.withLock { held in
+ if held.runs == 0 {
+ held.handlers = signals.map { signal($0, SIG_IGN) }
+ }
+ held.runs += 1
+ }
+ }
+
+ private func end() {
+ held.withLock { held in
+ held.runs -= 1
+ if held.runs == 0 {
+ for (number, handler) in zip(signals, held.handlers) {
+ signal(number, handler)
+ }
+ }
+ }
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileLockTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileLockTests.swift
index 0efe31dd..71c961ec 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/FileLockTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileLockTests.swift
@@ -1,6 +1,7 @@
import Darwin
import Foundation
@testable import PeelCore
+import Synchronization
import Testing
struct FileLockTests {
@@ -24,6 +25,50 @@ struct FileLockTests {
#expect(FileManager.default.fileExists(atPath: url.deletingLastPathComponent().path(percentEncoded: false)))
}
+ @Test func theTerminalCannotStopAProcessThatHoldsTheLock() throws {
+ let directory = try TemporaryDirectory()
+
+ let ignored = FileLock.whileHeld(beside: directory.url.appending(path: "Peel/removals.json")) { SignalDisposition.isIgnored(SIGTSTP) }
+
+ #expect(ignored)
+ }
+
+ /// A signal caught while waiting ends `flock` early, with EINTR and without the lock.
+ @Test func aSignalWhileWaitingDoesNotLetTheChangeRunUnlocked() throws {
+ let directory = try TemporaryDirectory()
+ let url = directory.url.appending(path: "Peel/removals.json")
+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ let other = open(url.path(percentEncoded: false) + ".lock", O_CREAT | O_RDWR | O_CLOEXEC, 0o600)
+ defer { close(other) }
+ #expect(flock(other, LOCK_EX) == 0)
+ var action = sigaction()
+ action.__sigaction_u.__sa_handler = { _ in }
+ var previous = sigaction()
+ sigaction(SIGUSR1, &action, &previous)
+ defer { sigaction(SIGUSR1, &previous, nil) }
+
+ let state = Mutex<(thread: UInt, released: Bool, ranUnlocked: Bool?)>((0, false, nil))
+ let finished = DispatchSemaphore(value: 0)
+ Thread {
+ // A thread starts with the signals its creator blocks, and the test runner's threads block this one.
+ var signals = sigset_t()
+ sigemptyset(&signals)
+ sigaddset(&signals, SIGUSR1)
+ pthread_sigmask(SIG_UNBLOCK, &signals, nil)
+ state.withLock { $0.thread = UInt(bitPattern: pthread_self()) }
+ FileLock.whileHeld(beside: url) { state.withLock { $0.ranUnlocked = !$0.released } }
+ finished.signal()
+ }.start()
+ Thread.sleep(forTimeInterval: 0.2)
+ if let thread = pthread_t(bitPattern: state.withLock { $0.thread }) { pthread_kill(thread, SIGUSR1) }
+ Thread.sleep(forTimeInterval: 0.3)
+ state.withLock { $0.released = true }
+ flock(other, LOCK_UN)
+
+ #expect(finished.wait(timeout: .now() + 5) == .success)
+ #expect(state.withLock { $0.ranUnlocked } == false, "the change ran while another held the lock")
+ }
+
@Test(.permissionsHold) func runsTheChangeWhenNoLockCanBeMade() throws {
let directory = try TemporaryDirectory()
try directory.directory("Locked")
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/IgnoredSignalsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/IgnoredSignalsTests.swift
new file mode 100644
index 00000000..af00c7ee
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/IgnoredSignalsTests.swift
@@ -0,0 +1,12 @@
+import Darwin
+@testable import PeelCore
+import Testing
+
+struct IgnoredSignalsTests {
+ @Test func givesEachSignalItsHandlerBackOnceTheWorkEnds() {
+ let ignored = IgnoredSignals([SIGUSR2])
+
+ #expect(ignored.run { SignalDisposition.isIgnored(SIGUSR2) })
+ #expect(!SignalDisposition.isIgnored(SIGUSR2))
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SignalDisposition.swift b/Packages/PeelCore/Tests/PeelCoreTests/SignalDisposition.swift
new file mode 100644
index 00000000..44f2a790
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/SignalDisposition.swift
@@ -0,0 +1,10 @@
+import Darwin
+
+enum SignalDisposition {
+ /// Whether `number` is ignored now, read without changing it.
+ static func isIgnored(_ number: Int32) -> Bool {
+ var action = sigaction()
+ guard sigaction(number, nil, &action) == 0 else { return false }
+ return unsafeBitCast(action.__sigaction_u.__sa_handler, to: Int.self) == unsafeBitCast(SIG_IGN, to: Int.self)
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninterruptedTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninterruptedTests.swift
index 127579c9..4204ac5e 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/UninterruptedTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninterruptedTests.swift
@@ -4,18 +4,11 @@ import Testing
/// `peel` keeps running from a move, or a put back, until History records it.
struct UninterruptedTests {
- /// Whether `number` is ignored now, read without changing it.
- private static func isIgnored(_ number: Int32) -> Bool {
- var action = sigaction()
- guard sigaction(number, nil, &action) == 0 else { return false }
- return unsafeBitCast(action.__sigaction_u.__sa_handler, to: Int.self) == unsafeBitCast(SIG_IGN, to: Int.self)
- }
-
/// Everything that would stop `peel` between a move and History is ignored meanwhile: Ctrl-C and a kill, and also
/// a terminal closing or an SSH connection dropping, Ctrl-\, and output piped into a command that has quit.
@Test func whatWouldStopPeelIsIgnoredUntilHistoryIsWritten() async {
#expect(Set(Uninterrupted.signals) == [SIGINT, SIGTERM, SIGHUP, SIGQUIT, SIGPIPE])
- let ignored = await Uninterrupted.run { Uninterrupted.signals.filter(Self.isIgnored) }
+ let ignored = await Uninterrupted.run { Uninterrupted.signals.filter(SignalDisposition.isIgnored) }
#expect(ignored == Uninterrupted.signals)
}
@@ -35,7 +28,7 @@ struct UninterruptedTests {
await Uninterrupted.run {
release.yield()
await first.value
- #expect(Uninterrupted.signals.allSatisfy(Self.isIgnored), "the run still under way lost its hold")
+ #expect(Uninterrupted.signals.allSatisfy(SignalDisposition.isIgnored), "the run still under way lost its hold")
}
}
}