Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Keep up with a chatty guest console without per-line regexes

Jackyda1179396997
diff --git a/VPhoneLaunchpad/Tests/ConsoleOutputTests.sh b/VPhoneLaunchpad/Tests/ConsoleOutputTests.sh
new file mode 100755
index 00000000..1e6733a3
--- /dev/null
+++ b/VPhoneLaunchpad/Tests/ConsoleOutputTests.sh
@@ -0,0 +1,15 @@
+#!/bin/zsh
+set -euo pipefail
+
+launchpad="${0:a:h:h}"
+temporary="$(/usr/bin/mktemp -d)"
+trap '/bin/rm -rf "$temporary"' EXIT
+
+/usr/bin/xcrun swiftc -swift-version 6 -strict-concurrency=complete \
+ -parse-as-library \
+ "$launchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLineReader.swift" \
+ "$launchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadNewlineTranslator.swift" \
+ "$launchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadLogWriter.swift" \
+ "$launchpad/Tests/ConsoleOutputTests.swift" \
+ -o "$temporary/console-output-tests"
+"$temporary/console-output-tests" "$@"
diff --git a/VPhoneLaunchpad/Tests/ConsoleOutputTests.swift b/VPhoneLaunchpad/Tests/ConsoleOutputTests.swift
new file mode 100644
index 00000000..b0049889
--- /dev/null
+++ b/VPhoneLaunchpad/Tests/ConsoleOutputTests.swift
@@ -0,0 +1,260 @@
+import Foundation
+
+/// The path a running guest's console takes through Launchpad: the line
+/// splitter and panic check on the `vm launch` tail, the newline translation
+/// the log terminal is fed through, and the log writer. Each is checked
+/// against the implementation it replaced, over logs cut at random points.
+@main
+struct ConsoleOutputTests {
+ static func expect(_ condition: Bool, _ message: @autoclosure () -> String, line: Int = #line) {
+ precondition(condition, "line \(line): \(message())")
+ }
+
+ static func main() {
+ splitter()
+ panicLines()
+ newlines()
+ writer()
+ print("Console output tests passed: line splitting, panic lines, newline translation, log writer")
+ }
+
+ // MARK: - Samples
+
+ /// A console log as a guest prints it: plain lines, coloured lines,
+ /// bare and doubled line ends, progress redraws, blank lines and a little
+ /// invalid UTF-8.
+ static func consoleSample(lines: Int, seed: UInt64) -> Data {
+ var random = SplitMix(seed: seed)
+ let pieces: [String] = [
+ "set_dir_stats:3204: disk1s7 setting dir-stats for ino 1234 parent 2",
+ "\u{1B}[32m[vphoned]\u{1B}[0m ping ok",
+ "\u{1B}[1;31mpanic(cpu 0 caller 0xfffffff0): \u{1B}[0m",
+ "progress 12 100\r",
+ " \t ",
+ "",
+ "$ vphone-cli restore ios27-rc",
+ "warning: low space",
+ "\u{1B}[?25l\u{1B}[2K redraw\u{1B}[",
+ "\u{1B}x not a sequence \u{1B}[12;",
+ "Stackshot succeeded",
+ "spanic? ppanic unpanic",
+ "研究 \u{3000} ok",
+ ]
+ var data = Data()
+ for _ in 0 ..< lines {
+ data.append(contentsOf: pieces[Int(random.next() % UInt64(pieces.count))].utf8)
+ switch random.next() % 10 {
+ case 0: data.append(contentsOf: [0x0D, 0x0A])
+ case 1: data.append(0x0D)
+ case 2: data.append(contentsOf: [0xE2, 0x9C])
+ default: data.append(0x0A)
+ }
+ }
+ return data
+ }
+
+ /// `data` cut at random points, some cuts inside a line, a CR LF pair or
+ /// a UTF-8 sequence.
+ static func chunks(of data: Data, seed: UInt64) -> [Data] {
+ var random = SplitMix(seed: seed)
+ var result: [Data] = []
+ var start = data.startIndex
+ while start < data.endIndex {
+ let length = 1 + Int(random.next() % 300)
+ let end = min(start + length, data.endIndex)
+ result.append(Data(data[start ..< end]))
+ start = end
+ }
+ return result
+ }
+
+ struct SplitMix {
+ var state: UInt64
+ init(seed: UInt64) { state = seed }
+ mutating func next() -> UInt64 {
+ state &+= 0x9E37_79B9_7F4A_7C15
+ var z = state
+ z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
+ z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
+ return z ^ (z >> 31)
+ }
+ }
+
+ // MARK: - Line splitter
+
+ /// The splitter before it worked a chunk at a time.
+ struct ReferenceSplitter {
+ var buffer = Data()
+
+ mutating func feed(_ data: Data, _ onLine: (String) -> Void) {
+ buffer.append(data)
+ while let end = buffer.firstIndex(where: { $0 == 0x0A || $0 == 0x0D }) {
+ Self.emit(buffer[buffer.startIndex ..< end], onLine)
+ buffer.removeSubrange(buffer.startIndex ... end)
+ }
+ }
+
+ mutating func flush(_ onLine: (String) -> Void) {
+ Self.emit(buffer, onLine)
+ buffer.removeAll()
+ }
+
+ static func emit(_ bytes: Data, _ onLine: (String) -> Void) {
+ let text = String(decoding: bytes, as: UTF8.self)
+ .replacingOccurrences(of: "\u{1B}\\[[0-9;?]*[ -/]*[@-~]", with: "", options: .regularExpression)
+ if !text.trimmingCharacters(in: .whitespaces).isEmpty {
+ onLine(text)
+ }
+ }
+ }
+
+ /// The splitter gives the lines the regular-expression splitter it
+ /// replaced gave, wherever the reads cut the output.
+ static func splitter() {
+ for seed in UInt64(1) ... 6 {
+ let log = consoleSample(lines: 3000, seed: seed)
+ var expected: [String] = []
+ var reference = ReferenceSplitter()
+ reference.feed(log) { expected.append($0) }
+ reference.flush { expected.append($0) }
+
+ var splitter = VPhoneLaunchpadLineSplitter()
+ var lines: [String] = []
+ for part in chunks(of: log, seed: seed &* 17) {
+ splitter.feed(part) { lines.append($0) }
+ }
+ splitter.flush { lines.append($0) }
+ expect(lines == expected, "seed \(seed): \(lines.count) lines, expected \(expected.count)")
+
+ var whole = VPhoneLaunchpadLineSplitter()
+ var wholeLines: [String] = []
+ whole.feed(log) { wholeLines.append($0) }
+ whole.flush { wholeLines.append($0) }
+ expect(wholeLines == expected, "seed \(seed) in one read")
+ }
+
+ var splitter = VPhoneLaunchpadLineSplitter()
+ var lines: [String] = []
+ splitter.feed(Data("\u{1B}[1;32mok\u{1B}[0m\r\n \u{2003}\t\nrest".utf8)) { lines.append($0) }
+ expect(lines == ["ok"], "colour dropped, blank lines skipped: \(lines)")
+ splitter.feed(Data(" of it".utf8)) { lines.append($0) }
+ splitter.flush { lines.append($0) }
+ expect(lines == ["ok", "rest of it"], "partial line across chunks: \(lines)")
+ expect(VPhoneLaunchpadLineSplitter.strippingEscapes("a\u{1B}[b\u{1B}") == "a\u{1B}",
+ "ESC [ with no parameters ends at its final byte; a trailing ESC stays")
+ expect(VPhoneLaunchpadLineSplitter.strippingEscapes("a\u{1B}[12;\u{1B}[0m研") == "a\u{1B}[12;研",
+ "an unfinished sequence stays")
+ }
+
+ // MARK: - Panic lines
+
+ /// The panic check agrees with the pattern on its own, which is what
+ /// `VPhoneLaunchpadCreationPipeline.isPanic` evaluated for every line.
+ static func panicLines() {
+ func reference(_ line: String) -> Bool {
+ line.range(of: VPhoneLaunchpadPanicLine.pattern, options: [.regularExpression, .caseInsensitive]) != nil
+ }
+ expect(VPhoneLaunchpadPanicLine.pattern == #"(^|[^p])(panic|kernel panic|panic\.apple\.com|stackshot succeeded)"#,
+ "the pattern is unchanged")
+ let lines = [
+ "panic(cpu 0 caller 0xfffffff0)", "Kernel Panic", "PANIC", "xnu: kernel panic", "https://panic.apple.com/",
+ "spanic", "ppanic", "PPANIC", "Ppanic", "unpanic", "stackshot succeeded", "Stackshot SUCCEEDED",
+ "ſtackshot ſucceeded", "pstackshot succeeded", "stackshot succeeded", "pani c", "set_dir_stats:3204: disk1s7",
+ "", "p", "panic", "\u{1B}[31mpanic\u{1B}[0m", "研究panic",
+ ]
+ for line in lines {
+ let expected = reference(line)
+ expect(VPhoneLaunchpadPanicLine.matches(line) == expected, "\(line.debugDescription) should be \(expected)")
+ }
+ for seed in UInt64(1) ... 3 {
+ var splitter = VPhoneLaunchpadLineSplitter()
+ var count = 0
+ splitter.feed(consoleSample(lines: 3000, seed: seed)) { line in
+ expect(VPhoneLaunchpadPanicLine.matches(line) == reference(line), "\(line.debugDescription), seed \(seed)")
+ count += 1
+ }
+ expect(count > 0, "seed \(seed) gave lines")
+ }
+ expect(VPhoneLaunchpadPanicLine.contains("xPaNiC", "panic"), "any ASCII case")
+ expect(!VPhoneLaunchpadPanicLine.contains("pan", "panic"), "shorter than the word")
+ expect(!VPhoneLaunchpadPanicLine.contains("p@nic", "panic"), "only letters fold")
+ }
+
+ // MARK: - Newline translation
+
+ /// The translation before it copied runs between line feeds.
+ struct ReferenceNewlineTranslator {
+ var previous: UInt8 = 0
+
+ mutating func translate(_ data: Data) -> Data {
+ var output = Data()
+ for byte in data {
+ if byte == 0x0A, previous != 0x0D {
+ output.append(0x0D)
+ }
+ output.append(byte)
+ previous = byte
+ }
+ return output
+ }
+ }
+
+ /// The translator's output does not depend on where the reads cut the
+ /// log, and matches the byte-at-a-time translation it replaced.
+ static func newlines() {
+ for seed in UInt64(1) ... 6 {
+ let log = consoleSample(lines: 3000, seed: seed)
+ let parts = chunks(of: log, seed: seed &* 31)
+ var reference = ReferenceNewlineTranslator()
+ let expected = parts.reduce(into: Data()) { $0.append(reference.translate($1)) }
+ var whole = VPhoneLaunchpadNewlineTranslator()
+ var cut = VPhoneLaunchpadNewlineTranslator()
+ let joined = parts.reduce(into: Data()) { $0.append(cut.translate($1)) }
+ expect(whole.translate(log) == expected, "whole, seed \(seed)")
+ expect(joined == expected, "chunked, seed \(seed)")
+ }
+ var newline = VPhoneLaunchpadNewlineTranslator()
+ expect(newline.translate(Data()).isEmpty, "empty chunk")
+ expect(newline.translate(Data("a\r".utf8)) == Data("a\r".utf8), "CR at a chunk's end")
+ expect(newline.translate(Data("\nb\n".utf8)) == Data("\nb\r\n".utf8), "its LF gains nothing")
+ expect(newline.translate(Data("\n\n".utf8)) == Data("\r\n\r\n".utf8), "empty lines")
+ // The log tail hands over a slice once it has skipped a partial line.
+ let chunk = Data("partial\nx\ny".utf8)
+ let slice = chunk[chunk.index(after: chunk.firstIndex(of: 0x0A)!)...]
+ var sliced = VPhoneLaunchpadNewlineTranslator()
+ expect(sliced.translate(slice) == Data("x\r\ny".utf8), "a slice that does not start at zero")
+ }
+
+ // MARK: - Log writer
+
+ /// The writer keeps every line, in order, however many arrive at once,
+ /// and the last twelve for error details.
+ static func writer() {
+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("console-output-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let url = directory.appendingPathComponent("create.log")
+ let writer = VPhoneLaunchpadLogWriter(url: url)
+ let count = 20000
+ DispatchQueue.concurrentPerform(iterations: 4) { worker in
+ for index in 0 ..< count / 4 {
+ writer.write("\(worker) \(index)")
+ }
+ }
+ var text = ""
+ for _ in 0 ..< 500 {
+ text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
+ if text.split(separator: "\n").count == count {
+ break
+ }
+ Thread.sleep(forTimeInterval: 0.01)
+ }
+ let lines = text.split(separator: "\n")
+ expect(lines.count == count, "\(lines.count) of \(count) lines written")
+ expect(text.hasSuffix("\n"), "every line ends with a line feed")
+ for worker in 0 ..< 4 {
+ let own = lines.filter { $0.hasPrefix("\(worker) ") }.map { Int($0.split(separator: " ")[1])! }
+ expect(own == Array(0 ..< count / 4), "worker \(worker)'s lines in order")
+ }
+ expect(writer.tail.split(separator: "\n").count == 12, "tail keeps twelve lines")
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadLogWriter.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadLogWriter.swift
new file mode 100644
index 00000000..675cdf93
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadLogWriter.swift
@@ -0,0 +1,64 @@
+import Foundation
+
+// MARK: - Writer
+
+/// Appends lines to a log file on a serial queue, so command output is
+/// written from the thread that read it and never waits on the main actor.
+/// Lines that arrive while a write is under way go out together in the next
+/// one, so a chatty command costs a write per batch, not per line. Keeps the
+/// last few lines for error details.
+final nonisolated class VPhoneLaunchpadLogWriter: @unchecked Sendable {
+ let url: URL
+ private let queue = DispatchQueue(label: "com.vphone.launchpad.log")
+ private let lock = NSLock()
+ private var handle: FileHandle?
+ private var recent: [String] = []
+ /// Bytes not yet handed to the queue, and whether a write is scheduled
+ /// to take them. Both under `lock`.
+ private var pending = Data()
+ private var isFlushScheduled = false
+
+ /// Starts an empty log at `url`, replacing any earlier one.
+ init(url: URL) {
+ self.url = url
+ queue.async { [self] in
+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ FileManager.default.createFile(atPath: url.path, contents: nil)
+ handle = try? FileHandle(forWritingTo: url)
+ }
+ }
+
+ deinit {
+ try? handle?.close()
+ }
+
+ func write(_ line: String) {
+ let schedules = lock.withLock {
+ recent.append(line)
+ if recent.count > 12 {
+ recent.removeFirst(recent.count - 12)
+ }
+ pending.append(contentsOf: line.utf8)
+ pending.append(0x0A)
+ let schedules = !isFlushScheduled
+ isFlushScheduled = true
+ return schedules
+ }
+ if schedules {
+ queue.async { [self] in
+ let data = lock.withLock {
+ let data = pending
+ pending = Data()
+ isFlushScheduled = false
+ return data
+ }
+ try? handle?.write(contentsOf: data)
+ }
+ }
+ }
+
+ /// The last lines written, for an error's detail text.
+ var tail: String {
+ lock.withLock { recent.joined(separator: "\n") }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadNewlineTranslator.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadNewlineTranslator.swift
new file mode 100644
index 00000000..3b93432d
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadNewlineTranslator.swift
@@ -0,0 +1,44 @@
+import Foundation
+
+/// Log files end lines with a bare line feed, which a terminal treats as
+/// "down one row" without returning to the first column; each one gains a
+/// carriage return.
+///
+/// A console can print thousands of lines a second, so a chunk is copied in
+/// the runs between line feeds, not byte by byte.
+nonisolated struct VPhoneLaunchpadNewlineTranslator {
+ private var previous: UInt8 = 0
+
+ mutating func translate(_ data: Data) -> Data {
+ guard let last = data.last else {
+ return Data()
+ }
+ var output = Data(capacity: data.count + data.count / 32)
+ let previous = previous
+ data.withUnsafeBytes { bytes in
+ var start = 0
+ while let end = Self.lineFeed(in: bytes, from: start) {
+ let before = end > 0 ? bytes[end - 1] : previous
+ output.append(contentsOf: UnsafeRawBufferPointer(rebasing: bytes[start ..< end]))
+ if before != 0x0D {
+ output.append(0x0D)
+ }
+ output.append(0x0A)
+ start = end + 1
+ }
+ output.append(contentsOf: UnsafeRawBufferPointer(rebasing: bytes[start...]))
+ }
+ self.previous = last
+ return output
+ }
+
+ /// The offset of the next line feed at or after `start`.
+ private static func lineFeed(in bytes: UnsafeRawBufferPointer, from start: Int) -> Int? {
+ guard start < bytes.count, let base = bytes.baseAddress,
+ let found = memchr(base + start, 0x0A, bytes.count - start)
+ else {
+ return nil
+ }
+ return base.distance(to: UnsafeRawPointer(found))
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swift
index 02b3a66a..747ddd17 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swift
@@ -103,6 +103,9 @@ nonisolated enum VPhoneLaunchpadLogTail {
if let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),
let number = (attributes[.systemFileNumber] as? NSNumber)?.uint64Value,
let size = (attributes[.size] as? NSNumber)?.uint64Value,
+ // A quiet log costs one stat a poll: it is opened only once
+ // it has grown or been replaced.
+ file != number || size != offset,
let handle = try? FileHandle(forReadingFrom: url)
{
// A new run replaces the file. Start the terminal over.
@@ -137,65 +140,3 @@ nonisolated enum VPhoneLaunchpadLogTail {
}
}
}
-
-/// Log files end lines with a bare line feed, which a terminal treats as
-/// "down one row" without returning to the first column.
-nonisolated struct VPhoneLaunchpadNewlineTranslator {
- private var previous: UInt8 = 0
-
- mutating func translate(_ data: Data) -> Data {
- var output = Data(capacity: data.count + data.count / 32)
- for byte in data {
- if byte == 0x0A, previous != 0x0D {
- output.append(0x0D)
- }
- output.append(byte)
- previous = byte
- }
- return output
- }
-}
-
-// MARK: - Writer
-
-/// Appends lines to a log file on a serial queue, so command output is
-/// written from the thread that read it and never waits on the main actor.
-/// Keeps the last few lines for error details.
-final nonisolated class VPhoneLaunchpadLogWriter: @unchecked Sendable {
- let url: URL
- private let queue = DispatchQueue(label: "com.vphone.launchpad.log")
- private let lock = NSLock()
- private var handle: FileHandle?
- private var recent: [String] = []
-
- /// Starts an empty log at `url`, replacing any earlier one.
- init(url: URL) {
- self.url = url
- queue.async { [self] in
- try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
- FileManager.default.createFile(atPath: url.path, contents: nil)
- handle = try? FileHandle(forWritingTo: url)
- }
- }
-
- deinit {
- try? handle?.close()
- }
-
- func write(_ line: String) {
- lock.withLock {
- recent.append(line)
- if recent.count > 12 {
- recent.removeFirst(recent.count - 12)
- }
- }
- queue.async { [self] in
- try? handle?.write(contentsOf: Data("\(line)\n".utf8))
- }
- }
-
- /// The last lines written, for an error's detail text.
- var tail: String {
- lock.withLock { recent.joined(separator: "\n") }
- }
-}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
index deb7bac5..04e5279b 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift
@@ -98,8 +98,6 @@ final class VPhoneLaunchpadCreationPipeline {
private var dfu: VPhoneLaunchpadChildProcess?
private var dfuPanicked = false
- nonisolated static let panicPattern = #"(^|[^p])(panic|kernel panic|panic\.apple\.com|stackshot succeeded)"#
-
init(
options: Options,
bundles: VPhoneLaunchpadCoreBundle,
@@ -455,7 +453,7 @@ final class VPhoneLaunchpadCreationPipeline {
// MARK: - Helpers
nonisolated static func isPanic(_ line: String) -> Bool {
- line.range(of: panicPattern, options: [.regularExpression, .caseInsensitive]) != nil
+ VPhoneLaunchpadPanicLine.matches(line)
}
/// The ECID the DFU boot wrote into udid-prediction.txt.
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLineReader.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLineReader.swift
index 6710a0de..130af17d 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLineReader.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadLineReader.swift
@@ -3,29 +3,85 @@ import Foundation
/// Splits a child's output into display lines. `vphone-cli` redraws progress
/// with carriage returns and colours some output, so both `\r` and `\n` end a
/// line, ANSI escape sequences are dropped, and blank lines are skipped.
+///
+/// A running guest's console goes through this line by line, so a chunk is
+/// split in one pass: the unterminated rest is kept once at the end instead
+/// of being shifted down after every line, and escape sequences are dropped
+/// by a scan, not a regular expression compiled for each line.
nonisolated struct VPhoneLaunchpadLineSplitter {
private var buffer = Data()
mutating func feed(_ data: Data, _ onLine: (String) -> Void) {
buffer.append(data)
- while let end = buffer.firstIndex(where: { $0 == 0x0A || $0 == 0x0D }) {
- Self.emit(buffer[buffer.startIndex ..< end], onLine)
- buffer.removeSubrange(buffer.startIndex ... end)
+ let consumed = buffer.withUnsafeBytes { raw -> Int in
+ let bytes = raw.bindMemory(to: UInt8.self)
+ var start = 0
+ for index in bytes.indices where bytes[index] == 0x0A || bytes[index] == 0x0D {
+ Self.emit(UnsafeBufferPointer(rebasing: bytes[start ..< index]), onLine)
+ start = index + 1
+ }
+ return start
+ }
+ if consumed == buffer.count {
+ buffer.removeAll(keepingCapacity: true)
+ } else if consumed > 0 {
+ buffer = Data(buffer.dropFirst(consumed))
}
}
mutating func flush(_ onLine: (String) -> Void) {
- Self.emit(buffer, onLine)
+ buffer.withUnsafeBytes { raw in
+ Self.emit(raw.bindMemory(to: UInt8.self), onLine)
+ }
buffer.removeAll()
}
- private static func emit(_ bytes: Data, _ onLine: (String) -> Void) {
- let text = String(decoding: bytes, as: UTF8.self)
- .replacingOccurrences(of: "\u{1B}\\[[0-9;?]*[ -/]*[@-~]", with: "", options: .regularExpression)
- if !text.trimmingCharacters(in: .whitespaces).isEmpty {
+ private static func emit(_ bytes: UnsafeBufferPointer<UInt8>, _ onLine: (String) -> Void) {
+ var text = String(decoding: bytes, as: UTF8.self)
+ if bytes.contains(0x1B) {
+ text = strippingEscapes(text)
+ }
+ if !isBlank(text) {
onLine(text)
}
}
+
+ /// `text` without its CSI sequences: ESC `[`, parameter bytes `0-9 ; ?`,
+ /// intermediate bytes ` -/`, then one final byte `@-~`. This removes what
+ /// the pattern `\u{1B}\[[0-9;?]*[ -/]*[@-~]` matches; the three byte sets
+ /// are disjoint, so a greedy scan finds the same matches. An ESC that
+ /// starts no sequence stays. Only ASCII bytes go, so the rest stays valid
+ /// UTF-8.
+ static func strippingEscapes(_ text: String) -> String {
+ let bytes = Array(text.utf8)
+ var output: [UInt8] = []
+ output.reserveCapacity(bytes.count)
+ var index = 0
+ while index < bytes.count {
+ if bytes[index] == 0x1B, index + 1 < bytes.count, bytes[index + 1] == 0x5B {
+ var end = index + 2
+ while end < bytes.count, (0x30 ... 0x39).contains(bytes[end]) || bytes[end] == 0x3B || bytes[end] == 0x3F {
+ end += 1
+ }
+ while end < bytes.count, (0x20 ... 0x2F).contains(bytes[end]) {
+ end += 1
+ }
+ if end < bytes.count, (0x40 ... 0x7E).contains(bytes[end]) {
+ index = end + 1
+ continue
+ }
+ }
+ output.append(bytes[index])
+ index += 1
+ }
+ return String(decoding: output, as: UTF8.self)
+ }
+
+ /// Empty, or only tabs and space separators (Unicode category Zs): what
+ /// trimming `CharacterSet.whitespaces` leaves empty.
+ private static func isBlank(_ text: String) -> Bool {
+ text.unicodeScalars.allSatisfy { $0 == "\t" || $0.properties.generalCategory == .spaceSeparator }
+ }
}
nonisolated enum VPhoneLaunchpadLineReader {
@@ -42,3 +98,45 @@ nonisolated enum VPhoneLaunchpadLineReader {
splitter.flush(onLine)
}
}
+
+// MARK: - Panic lines
+
+/// Whether a console line reports a kernel panic. Every line a running guest
+/// prints is checked, so the many lines that hold neither `panic` nor
+/// `ucceeded` skip the regular expression.
+nonisolated enum VPhoneLaunchpadPanicLine {
+ static let pattern = #"(^|[^p])(panic|kernel panic|panic\.apple\.com|stackshot succeeded)"#
+
+ static func matches(_ line: String) -> Bool {
+ // Every match holds `panic` or `succeeded` in some case. Case-
+ // insensitive matching may take a long s for the s, so the check
+ // looks for `ucceeded`, which only ASCII letters spell.
+ guard contains(line, "panic") || contains(line, "ucceeded") else {
+ return false
+ }
+ return line.range(of: pattern, options: [.regularExpression, .caseInsensitive]) != nil
+ }
+
+ /// Whether `text` holds `needle`, a lowercase ASCII word, in any ASCII
+ /// case.
+ static func contains(_ text: String, _ needle: StaticString) -> Bool {
+ let word = UnsafeBufferPointer(start: needle.utf8Start, count: needle.utf8CodeUnitCount)
+ var text = text
+ return text.withUTF8 { bytes in
+ var start = 0
+ while start + word.count <= bytes.count {
+ var offset = 0
+ // Setting bit 5 lowers an ASCII capital and moves no other
+ // byte onto a lowercase letter.
+ while offset < word.count, bytes[start + offset] | 0x20 == word[offset] {
+ offset += 1
+ }
+ if offset == word.count {
+ return true
+ }
+ start += 1
+ }
+ return false
+ }
+ }
+}