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.

Intel Software finds tools beside an app and behind command links

Țugui Dragoșa116d0c085e2
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift b/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift
index ceced476..68487fa2 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift
@@ -1,5 +1,6 @@
import Darwin
public import Foundation
+internal import PeelPrivileged
/// Intel-only software, which needs Rosetta on Apple silicon. macOS 27 is the last release to offer Rosetta.
public struct IntelFinding: Sendable, Hashable, Identifiable {
@@ -58,9 +59,13 @@ public enum IntelInspector {
/// `Contents/Frameworks` is not one of them: a library there is loaded into the app's own process, so an
/// Intel-only one matters only when the app itself runs as Intel code. The bundles beside the libraries are
/// processes, and `frameworkProcesses` finds those.
+ /// `Contents/MacOS` holds helper tools beside the main executable, whose own architectures decide whether the
+ /// app is listed as a whole. A Quick Look generator, a Spotlight importer and a system extension run in a
+ /// process of their own as well.
static let embeddedDirectories = [
- "Contents/Library/LoginItems", "Contents/PlugIns", "Contents/Extensions", "Contents/XPCServices",
- "Contents/Helpers", "Contents/Library/LaunchServices",
+ "Contents/MacOS", "Contents/Library/LoginItems", "Contents/PlugIns", "Contents/Extensions",
+ "Contents/XPCServices", "Contents/Helpers", "Contents/Library/LaunchServices",
+ "Contents/Library/SystemExtensions", "Contents/Library/QuickLook", "Contents/Library/Spotlight",
]
/// The extensions of bundles that run as a process of their own.
@@ -154,13 +159,18 @@ public enum IntelInspector {
))
}
- for url in tools(in: toolDirectories) where !Task.isCancelled && !exclusions.excludes(url) && isIntelOnly(executable: url) && isNew(url) {
+ // A command that leads into an app listed already is that app's.
+ let apps = findings.filter { $0.kind == .app }.map { PathPattern.comparablePath(of: $0.url) }
+ for tool in tools(in: toolDirectories) where !Task.isCancelled && !exclusions.excludes(tool.url) {
+ let path = PathPattern.comparablePath(of: tool.url)
+ guard !apps.contains(where: { PathComponents.isPath(path, inside: $0) }) else { continue }
+ guard isIntelOnly(executable: tool.url), isNew(tool.url) else { continue }
findings.append(IntelFinding(
- url: url,
+ url: tool.url,
kind: .commandLineTool,
- name: url.lastPathComponent,
+ name: tool.name,
owner: nil,
- size: await measure(url),
+ size: await measure(tool.url),
))
}
@@ -178,7 +188,9 @@ public enum IntelInspector {
if info.st_mode & S_IFMT == S_IFDIR {
return !url.pathExtension.isEmpty && isIntelOnly(bundle: url)
}
+ // A library or a bundle kept beside the programs runs in the process that loads it.
return info.st_mode & S_IFMT == S_IFREG && isIntelOnly(executable: url)
+ && MachOHeader.isProgram(at: url)
}
}
}
@@ -241,17 +253,20 @@ public enum IntelInspector {
}
}
- static func tools(in directories: [String]) -> [URL] {
- directories.flatMap { directory -> [URL] in
- let url = URL(filePath: directory, directoryHint: .isDirectory)
+ /// The programs the commands in `directories` run, each under the command's name. A command is often a link,
+ /// as every one a Homebrew in `/usr/local` makes into its `Cellar`, and the program it leads to is what runs.
+ static func tools(in directories: [String]) -> [(name: String, url: URL)] {
+ directories.flatMap { directory -> [(name: String, url: URL)] in
+ let folder = URL(filePath: directory, directoryHint: .isDirectory)
let names = (try? FileManager.default.contentsOfDirectory(atPath: directory)) ?? []
- return names.map { url.appending(path: $0) }.filter { candidate in
- // Only plain files, not links: a link takes a few bytes, and the binary it points to
- // belongs to something else.
+ return names.compactMap { name in
+ let program = folder.appending(path: name).resolvingSymlinksInPath()
var info = stat()
- let path = candidate.path(percentEncoded: false)
- guard lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { return false }
- return FileManager.default.isExecutableFile(atPath: path)
+ let path = program.path(percentEncoded: false)
+ guard stat(path, &info) == 0, info.st_mode & S_IFMT == S_IFREG,
+ FileManager.default.isExecutableFile(atPath: path)
+ else { return nil }
+ return (name, program)
}
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/MachOHeader.swift b/Packages/PeelCore/Sources/PeelCore/Apps/MachOHeader.swift
index 63c3af81..cf4ab894 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/MachOHeader.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/MachOHeader.swift
@@ -8,6 +8,8 @@ enum MachOHeader {
private static let cpuTypeARM64: UInt32 = 0x0100_000C
private static let cpuTypeX86_64: UInt32 = 0x0100_0007
private static let maximumFatArchitectures = 32
+ /// `MH_EXECUTE` in `<mach-o/loader.h>`: a program, as opposed to a library or a bundle another program loads.
+ private static let programFileType: UInt32 = 0x2
/// Returns the architectures of the executable at `url`. Whatever is at that path gets opened, and a named
/// pipe opened for reading would wait forever for a writer. `O_NONBLOCK` returns at once, and only a regular
@@ -23,6 +25,40 @@ enum MachOHeader {
return count > 0 ? architectures(inHeader: Array(bytes[0..<count])) : []
}
+ /// Whether the file at `url` is a program of its own rather than code another program loads. A universal
+ /// file is judged by its first slice, since every slice of one file is built as the same kind.
+ static func isProgram(at url: URL) -> Bool {
+ let descriptor = open(url.path(percentEncoded: false), O_RDONLY | O_NONBLOCK | O_CLOEXEC)
+ guard descriptor >= 0 else { return false }
+ defer { close(descriptor) }
+ var info = stat()
+ guard fstat(descriptor, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { return false }
+ func bytes(at offset: off_t, count: Int) -> [UInt8] {
+ var buffer = [UInt8](repeating: 0, count: count)
+ let read = pread(descriptor, &buffer, count, offset)
+ return read > 0 ? Array(buffer[0..<read]) : []
+ }
+ func isAProgram(_ header: [UInt8]) -> Bool {
+ bigEndianUInt32(header, at: 0) == machMagic64Swapped
+ && littleEndianUInt32(header, at: 12) == programFileType
+ }
+ let header = bytes(at: 0, count: 32)
+ switch bigEndianUInt32(header, at: 0) {
+ case machMagic64Swapped:
+ return isAProgram(header)
+ case fatMagic:
+ guard let offset = bigEndianUInt32(header, at: 16) else { return false }
+ return isAProgram(bytes(at: off_t(offset), count: 16))
+ case fatMagic64:
+ guard let high = bigEndianUInt32(header, at: 16), let low = bigEndianUInt32(header, at: 20) else {
+ return false
+ }
+ return isAProgram(bytes(at: off_t(UInt64(high) << 32 | UInt64(low)), count: 16))
+ default:
+ return false
+ }
+ }
+
static func architectures(inHeader bytes: [UInt8]) -> Set<Architecture> {
guard let magic = bigEndianUInt32(bytes, at: 0) else { return [] }
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift
index 29e3081e..860d592e 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/IntelInspectorTests.swift
@@ -21,6 +21,11 @@ struct IntelInspectorTests {
return Data(bytes)
}
+ /// A 64 bit Intel Mach-O header of the given file type: 2 is a program, 8 a bundle loaded into another one.
+ private func intelHeader(fileType: UInt8) -> Data {
+ Data([0xCF, 0xFA, 0xED, 0xFE, 0x07, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, fileType, 0x00, 0x00, 0x00])
+ }
+
private let intel: UInt32 = 0x0100_0007
private let appleSilicon: UInt32 = 0x0100_000C
@@ -104,13 +109,56 @@ struct IntelInspectorTests {
_ = try bundle(directory, "Universal.app/Contents/XPCServices/Service.xpc", cpuTypes: [intel, appleSilicon])
_ = try bundle(directory, "Universal.app/Contents/PlugIns/Old.appex", cpuTypes: [intel])
- let plainHelper = try directory.file("Universal.app/Contents/Helpers/updater", contents: fatHeader([intel]))
+ let plainHelper = try directory.file(
+ "Universal.app/Contents/Helpers/updater", contents: intelHeader(fileType: 2)
+ )
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: plainHelper.path(percentEncoded: false))
let found = IntelInspector.intelOnlyBundles(inside: directory.url.appending(path: "Universal.app", directoryHint: .isDirectory))
#expect(Set(found.map(\.lastPathComponent)) == ["Launcher.app", "Old.appex", "updater"])
}
+ /// Apple's place for a helper tool is `Contents/MacOS` beside the main executable, and a Quick Look generator,
+ /// a Spotlight importer or a system extension the app carries runs in a process of its own too.
+ @Test func findsIntelToolsBesideTheMainExecutableAndInTheAppsLibrary() throws {
+ let directory = try TemporaryDirectory()
+ _ = try bundle(directory, "Universal.app", cpuTypes: [intel, appleSilicon])
+ let tool = try directory.file("Universal.app/Contents/MacOS/ffmpeg", contents: intelHeader(fileType: 2))
+ try directory.setPermissions(0o755, of: tool)
+ // A library the tool loads runs in the tool's process, not one of its own.
+ let library = try directory.file("Universal.app/Contents/MacOS/7z.so", contents: intelHeader(fileType: 8))
+ try directory.setPermissions(0o755, of: library)
+ let appLibrary = "Universal.app/Contents/Library"
+ _ = try bundle(directory, "\(appLibrary)/QuickLook/Preview.qlgenerator", cpuTypes: [intel])
+ _ = try bundle(directory, "\(appLibrary)/Spotlight/Importer.mdimporter", cpuTypes: [intel])
+ _ = try bundle(directory, "\(appLibrary)/SystemExtensions/Filter.systemextension", cpuTypes: [intel])
+
+ let app = directory.url.appending(path: "Universal.app", directoryHint: .isDirectory)
+ let found = IntelInspector.intelOnlyBundles(inside: app)
+
+ #expect(Set(found.map(\.lastPathComponent)) == [
+ "ffmpeg", "Preview.qlgenerator", "Importer.mdimporter", "Filter.systemextension",
+ ])
+ }
+
+ /// A Homebrew installed for Intel keeps every command in `/usr/local/bin` as a link into its `Cellar`. The
+ /// program the link leads to is what needs Rosetta, listed under the command's name.
+ @Test func findsTheIntelProgramACommandLinkLeadsTo() throws {
+ let directory = try TemporaryDirectory()
+ let program = try directory.file("Cellar/tool/1.0/bin/tool", contents: fatHeader([intel]))
+ try directory.setPermissions(0o755, of: program)
+ let bin = try directory.directory("bin")
+ try FileManager.default.createSymbolicLink(
+ atPath: bin.appending(path: "tool").path(percentEncoded: false),
+ withDestinationPath: "../Cellar/tool/1.0/bin/tool"
+ )
+
+ let tools = IntelInspector.tools(in: [bin.path(percentEncoded: false)])
+
+ #expect(tools.map(\.name) == ["tool"])
+ #expect(tools.map { PathPattern.comparablePath(of: $0.url) } == [PathPattern.comparablePath(of: program)])
+ }
+
/// Every Electron app keeps its helper processes under `Contents/Frameworks`, and Sparkle keeps its
/// XPC services two levels down inside its framework. Those are processes, not libraries.
@Test func findsTheHelperProcessesKeptUnderFrameworks() throws {
diff --git a/README.md b/README.md
index 4c701268..d9ec41f4 100644
--- a/README.md
+++ b/README.md
@@ -149,7 +149,8 @@ lists them.
- **Background Items:** launch agents and daemons, and the app that added each one.
- **Extensions and Plug-ins:** app extensions, system extensions, and plug-ins, from audio units to Quick Look.
- **Package Receipts:** what installer packages put on your Mac, item by item.
-- **Intel Software:** everything that still needs Rosetta, including helpers hidden inside universal apps.
+- **Intel Software:** what still needs Rosetta: apps, the helpers and tools inside universal apps, plug-ins,
+ drivers, background items, and the commands in `/usr/local`.
- **Homebrew:** your formulae and casks, with Update, Clean Up, Check Health, Scan for Vulnerabilities, Upgrade,
and Uninstall, or the command to run in Terminal for a cask that asks for an administrator's password.