diff --git a/.github/workflows/swift.yml b/.github/workflows/swift.yml index 849b14e..6353470 100644 --- a/.github/workflows/swift.yml +++ b/.github/workflows/swift.yml @@ -84,3 +84,70 @@ jobs: run: swift test - name: Build and test without FreeType run: swift test --disable-default-traits --scratch-path .build-notrait + + armv7: + name: Linux (armv7, build) + runs-on: ubuntu-latest + # Swift's modules only load in the compiler that built them, so the + # image's version and the SDK's must be the same. + container: swift:6.4.3-trixie + env: + SWIFT_VERSION: "6.4.3" + SDK_SHA256: 243184bf809a3a17d36b9b411e353e8ad07585cdbff1129dd1bb969882352a0f + steps: + - uses: actions/checkout@v4 + - name: Install dependencies + run: | + apt-get update + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates curl git + - name: Cache the armv7 SDK + id: cache-sdk + uses: actions/cache@v4 + with: + path: /opt/armv7-sdk + key: armv7-sdk-${{ env.SWIFT_VERSION }}-trixie-${{ env.SDK_SHA256 }} + # Swift has no official 32-bit ARM SDK: this is the community's. + - name: Download the armv7 SDK + if: steps.cache-sdk.outputs.cache-hit != 'true' + run: | + name="swift-$SWIFT_VERSION-RELEASE-debian-trixie-armv7-sdk.tar.gz" + curl -fsSLo /tmp/sdk.tar.gz \ + "https://github.com/swift-embedded-linux/armhf-debian/releases/download/$SWIFT_VERSION/$name" + echo "$SDK_SHA256 /tmp/sdk.tar.gz" | sha256sum -c - + mkdir -p /opt/armv7-sdk + tar -xzf /tmp/sdk.tar.gz -C /opt/armv7-sdk + - name: Describe the destination + run: | + sdk="/opt/armv7-sdk/swift-$SWIFT_VERSION-RELEASE-debian-trixie-armv7/debian-trixie" + plugins="$(dirname "$(command -v swiftc)")/../lib/swift/host/plugins" + cat > armv7.json < 0, height > 0, width <= 64, height <= 64, [1, 2, 4, 8].contains(depth) else { throw MacError.parameter } + // Each row holds all its pixels, so indexing them stays inside. + guard rowBytes >= (width * depth + 7) / 8 else { throw MacError.parameter } var tableReader = try BigEndianReader(source).subreader(at: tableOffset, count: 8) try tableReader.skip(6) let entries = Int(try tableReader.read(UInt16.self)) + 1 diff --git a/Sources/Graphite2D/IconFamily.swift b/Sources/Graphite2D/IconFamily.swift index cebf41d..82705fd 100644 --- a/Sources/Graphite2D/IconFamily.swift +++ b/Sources/Graphite2D/IconFamily.swift @@ -23,11 +23,11 @@ public struct IconFamily: Sendable { var reader = BigEndianReader(bytes) do { guard try reader.read(UInt32.self) == FourCharCode("icns").rawValue else { throw MacError.parameter } - let length = min(Int(try reader.read(UInt32.self)), reader.count) + let length = min(Int(clamping: try reader.read(UInt32.self)), reader.count) members = [:] while reader.offset + 8 <= length { let type = FourCharCode(try reader.read(UInt32.self)) - let size = Int(try reader.read(UInt32.self)) + let size = Int(clamping: try reader.read(UInt32.self)) guard size >= 8 else { throw MacError.parameter } members[type] = Array(try reader.readBytes(size - 8)) } @@ -161,6 +161,9 @@ public struct ColorIcon: Sendable { try reader.skip(8 + 4) // its bounds, iconData let height = bounds.height, width = bounds.width guard width > 0, height > 0, width <= 1024, height <= 1024, [1, 2, 4, 8].contains(depth) else { throw MacError.parameter } + // Each row holds all its pixels and mask bits, so indexing them + // stays inside. + guard rowBytes >= (width * depth + 7) / 8, maskRowBytes >= (width + 7) / 8 else { throw MacError.parameter } let mask = Array(try reader.readBytes(maskRowBytes * height)) try reader.skip(bitmapRowBytes * height) let tableStart = reader.offset diff --git a/Sources/Graphite2D/Picture.swift b/Sources/Graphite2D/Picture.swift index 314f05c..e6c55fe 100644 --- a/Sources/Graphite2D/Picture.swift +++ b/Sources/Graphite2D/Picture.swift @@ -274,7 +274,7 @@ private struct Parser { private mutating func skipWordLength() throws { try reader.skip(Int(try reader.read(UInt16.self))) } - private mutating func skipLongLength() throws { try reader.skip(Int(try reader.read(UInt32.self))) } + private mutating func skipLongLength() throws { try reader.skip(Int(clamping: try reader.read(UInt32.self))) } private mutating func operation(_ opcode: Int) throws -> Picture.Operation? { switch opcode { @@ -434,27 +434,30 @@ private struct Parser { /// CompressedQuickTime: its matrix's translation and scale place the /// image's source rectangle; its image description says the codec. private mutating func compressedImage() throws -> Picture.Operation? { - let length = Int(try reader.read(UInt32.self)) + let length = Int(clamping: try reader.read(UInt32.self)) var data = try reader.subreader(length) try data.skip(2) // version var matrix: [Int32] = [] for _ in 0 ..< 9 { matrix.append(Int32(bitPattern: try data.read(UInt32.self))) } - let matteSize = Int(try data.read(UInt32.self)) + let matteSize = Int(clamping: try data.read(UInt32.self)) try data.skip(8) // matteRect let mode = TransferMode(rawValue: Int16(bitPattern: try data.read(UInt16.self))) let source = try PicturePixels.readRect(&data) try data.skip(4) // accuracy - let maskSize = Int(try data.read(UInt32.self)) - try data.skip(matteSize + maskSize) + let maskSize = Int(clamping: try data.read(UInt32.self)) + // One at a time: their sum can overflow on a 32-bit CPU. + try data.skip(matteSize) + try data.skip(maskSize) let descriptionStart = data.offset - let descriptionSize = Int(try data.read(UInt32.self)) + let descriptionSize = Int(clamping: try data.read(UInt32.self)) let codec = FourCharCode(try data.read(UInt32.self)) try data.seek(to: descriptionStart + 32) let width = Int(try data.read(UInt16.self)), height = Int(try data.read(UInt16.self)) try data.seek(to: descriptionStart + 44) - let dataSize = Int(try data.read(UInt32.self)) + let dataSize = Int(clamping: try data.read(UInt32.self)) try data.seek(to: descriptionStart + 82) let depth = Int(try data.read(UInt16.self)) + guard descriptionSize <= data.count - descriptionStart else { throw MacError.parameter } try data.seek(to: descriptionStart + descriptionSize) let image = Array(try data.readBytes(min(dataSize, data.remaining))) // The matrix's scale (Fixed) and translation (Fixed) place the diff --git a/Sources/GraphiteAutomation/DescriptorClassicData.swift b/Sources/GraphiteAutomation/DescriptorClassicData.swift index db8a3d5..5a271dd 100644 --- a/Sources/GraphiteAutomation/DescriptorClassicData.swift +++ b/Sources/GraphiteAutomation/DescriptorClassicData.swift @@ -52,7 +52,7 @@ public extension Descriptor { let start = try data.long() data.position = 16 let count = try data.long() - data.position = Int(start) + data.position = Int(clamping: start) self.init(type: type, items: try data.items(count, keyed: !isList, depth: 0), isKeyed: !isList) } @@ -159,7 +159,7 @@ private struct ClassicData { mutating func code() throws(MacError) -> FourCharCode { FourCharCode(rawValue: try long()) } mutating func value() throws(MacError) -> [UInt8] { - let size = Int(try long()) + let size = Int(clamping: try long()) guard size <= bytes.count - position else { throw .corruptData } defer { position += size + (size & 1) } return Array(bytes[position ..< position + size]) @@ -224,7 +224,7 @@ private struct ClassicData { descriptor: Descriptor(type: DescriptorType.sInt32, bytes: big(0)))) } attributes += listed - position = Int(parameters) + position = Int(clamping: parameters) return Descriptor(type: DescriptorType.appleEvent, items: try items(parameterCount, keyed: true, depth: 0), attributes: attributes, isKeyed: true) } diff --git a/Sources/GraphiteCore/Extended80.swift b/Sources/GraphiteCore/Extended80.swift index 0a0a181..02b2596 100644 --- a/Sources/GraphiteCore/Extended80.swift +++ b/Sources/GraphiteCore/Extended80.swift @@ -78,7 +78,10 @@ public struct Extended80: Hashable, Sendable { if leading > Double.greatestFiniteMagnitude.exponent { return Double(sign: sign, exponent: 0, significand: .infinity) } - if leading < Double.leastNonzeroMagnitude.exponent - 1 { + // Below half the smallest denormal, 2^-1074. Not asked of + // `leastNonzeroMagnitude`, which on 32-bit ARM is the smallest + // normal number. + if leading < -1075 { return Double(sign: sign, exponent: 0, significand: 0) } return Double(sign: sign, exponent: exponent - 63, significand: Double(mantissa)) diff --git a/Sources/GraphiteFiles/AppleDouble.swift b/Sources/GraphiteFiles/AppleDouble.swift index b3cba47..e8bdea2 100644 --- a/Sources/GraphiteFiles/AppleDouble.swift +++ b/Sources/GraphiteFiles/AppleDouble.swift @@ -70,8 +70,8 @@ public struct AppleDouble: Hashable, Sendable { entries = [] for _ in 0 ..< count { let id = try reader.read(UInt32.self) - let offset = Int(try reader.read(UInt32.self)) - let length = Int(try reader.read(UInt32.self)) + let offset = Int(clamping: try reader.read(UInt32.self)) + let length = Int(clamping: try reader.read(UInt32.self)) let entry = try reader.subreader(at: offset, count: length) entries.append(Entry(id: EntryID(rawValue: id), bytes: Array(entry.bytes))) } diff --git a/Sources/GraphiteResources/ResourceMap.swift b/Sources/GraphiteResources/ResourceMap.swift index 8785524..1fba00c 100644 --- a/Sources/GraphiteResources/ResourceMap.swift +++ b/Sources/GraphiteResources/ResourceMap.swift @@ -119,10 +119,10 @@ public struct ResourceMap: Hashable, Sendable { guard bytes.count >= 16 else { throw .endOfFile } do { var header = BigEndianReader(bytes) - let dataOffset = Int(try header.read(UInt32.self)) - let mapOffset = Int(try header.read(UInt32.self)) - let dataLength = Int(try header.read(UInt32.self)) - let mapLength = Int(try header.read(UInt32.self)) + let dataOffset = Int(clamping: try header.read(UInt32.self)) + let mapOffset = Int(clamping: try header.read(UInt32.self)) + let dataLength = Int(clamping: try header.read(UInt32.self)) + let mapLength = Int(clamping: try header.read(UInt32.self)) guard dataOffset <= bytes.count, dataLength <= bytes.count - dataOffset, mapOffset <= bytes.count, mapLength <= bytes.count - mapOffset, mapLength >= 28 else { throw MacError.mapRead } let map = try BigEndianReader(bytes).subreader(at: mapOffset, count: mapLength) @@ -154,7 +154,7 @@ public struct ResourceMap: Hashable, Sendable { name = PascalString(bytes: try map.subreader(at: at + 1, count: length).bytes) } guard offset + 4 <= dataLength else { throw MacError.mapRead } - let length = Int(try header.peek(UInt32.self, at: dataOffset + offset)) + let length = Int(clamping: try header.peek(UInt32.self, at: dataOffset + offset)) guard length <= dataLength - offset - 4 else { throw MacError.mapRead } let start = dataOffset + offset + 4 entries.append(Entry(resource: Resource(type: type, id: id, name: name, attributes: attributes), data: start ..< start + length)) diff --git a/Sources/GraphiteSound/AIFF.swift b/Sources/GraphiteSound/AIFF.swift index 17815bb..006cee2 100644 --- a/Sources/GraphiteSound/AIFF.swift +++ b/Sources/GraphiteSound/AIFF.swift @@ -39,8 +39,8 @@ public extension SampledSound { var reader = BigEndianReader(data) do { guard try reader.read(UInt32.self) == FourCharCode("FORM").rawValue else { throw MacError.badFileFormat } - let formSize = Int(try reader.read(UInt32.self)) - let end = min(data.count, 8 + formSize) + let formSize = Int(clamping: try reader.read(UInt32.self)) + let end = 8 + min(formSize, data.count - 8) let formType = FourCharCode(try reader.read(UInt32.self)) guard formType == "AIFF" || formType == "AIFC" else { throw MacError.badFileFormat } @@ -52,13 +52,13 @@ public extension SampledSound { while reader.offset + 8 <= end { let id = FourCharCode(try reader.read(UInt32.self)) - let size = Int(try reader.read(UInt32.self)) + let size = Int(clamping: try reader.read(UInt32.self)) let body = reader.offset guard size <= data.count - body else { throw MacError.badFileFormat } switch id { case "COMM": let channels = Int(try reader.read(UInt16.self)) - let frames = Int(try reader.read(UInt32.self)) + let frames = Int(clamping: try reader.read(UInt32.self)) let bits = Int(try reader.read(UInt16.self)) let rate = try reader.readExtended80().doubleValue var encoding = SoundEncoding.signedBigEndian @@ -73,7 +73,7 @@ public extension SampledSound { let count = Int(try reader.read(UInt16.self)) for _ in 0 ..< count { let marker = try reader.read(UInt16.self) - markers[marker] = Int(try reader.read(UInt32.self)) + markers[marker] = Int(clamping: try reader.read(UInt32.self)) // The name, a Pascal string padded to an even length. let length = Int(try reader.read(UInt8.self)) try reader.skip(length + (length + 1) % 2) @@ -86,10 +86,9 @@ public extension SampledSound { let loopEnd = try reader.read(UInt16.self) if playMode == 1 { loopMarkers = (begin, loopEnd) } case "SSND": - let offset = Int(try reader.read(UInt32.self)) + let offset = Int(clamping: try reader.read(UInt32.self)) try reader.skip(4) // blockSize - let start = body + 8 + offset - if start <= body + size { samples = start ..< body + size } + if offset <= size - 8 { samples = body + 8 + offset ..< body + size } default: break } diff --git a/Sources/GraphiteSound/SoundResource.swift b/Sources/GraphiteSound/SoundResource.swift index 272aaa9..dd9ab2f 100644 --- a/Sources/GraphiteSound/SoundResource.swift +++ b/Sources/GraphiteSound/SoundResource.swift @@ -76,7 +76,7 @@ public enum SoundResource { for _ in 0 ..< commands { let command = try reader.read(UInt16.self) try reader.skip(2) // param1 - let parameter = Int(try reader.read(UInt32.self)) + let parameter = Int(clamping: try reader.read(UInt32.self)) // With its high bit set, a command's param2 is an offset // from the resource's start to its sound data. if command & 0x8000 != 0, headerCommands.contains(command & 0x7FFF) { @@ -114,8 +114,8 @@ public extension SampledSound { guard try reader.read(UInt32.self) == 0 else { throw MacError.badFormat } // samplePtr let length = Int(try reader.read(Int32.self)) // the byte count, or the channels let rate = Double(try reader.read(UInt32.self)) / 65536 - let loopStart = Int(try reader.read(UInt32.self)) - let loopEnd = Int(try reader.read(UInt32.self)) + let loopStart = Int(clamping: try reader.read(UInt32.self)) + let loopEnd = Int(clamping: try reader.read(UInt32.self)) let encode = try reader.read(UInt8.self) let baseNote = Int(try reader.read(UInt8.self)) let encoding: SoundEncoding diff --git a/Sources/GraphiteText/SfntTables.swift b/Sources/GraphiteText/SfntTables.swift index 1b1d091..9a92c20 100644 --- a/Sources/GraphiteText/SfntTables.swift +++ b/Sources/GraphiteText/SfntTables.swift @@ -24,9 +24,11 @@ public struct SfntTables: Sendable { var tag = try reader.read(UInt32.self) if tag == FourCharCode("ttcf").rawValue { try reader.skip(4) // version - let count = Int(try reader.read(UInt32.self)) - guard index >= 0, index < count else { throw MacError.parameter } - try reader.seek(to: Int(try reader.peek(UInt32.self, at: 12 + 4 * index))) + let count = Int(clamping: try reader.read(UInt32.self)) + // The count may be more than the file can hold, and `4 * index` + // must not overflow on a 32-bit CPU. + guard index >= 0, index < count, index <= (font.count - 16) / 4 else { throw MacError.parameter } + try reader.seek(to: Int(clamping: try reader.peek(UInt32.self, at: 12 + 4 * index))) tag = try reader.read(UInt32.self) } guard tag == 0x0001_0000 || [FourCharCode("true"), "OTTO", "typ1"].contains(FourCharCode(tag)) else { @@ -37,8 +39,8 @@ public struct SfntTables: Sendable { for _ in 0 ..< count { let name = FourCharCode(try reader.read(UInt32.self)) try reader.skip(4) // checksum - let offset = Int(try reader.read(UInt32.self)) - let length = Int(try reader.read(UInt32.self)) + let offset = Int(clamping: try reader.read(UInt32.self)) + let length = Int(clamping: try reader.read(UInt32.self)) // A table past the end of the file is not there; the first of a tag wins. guard offset <= font.count, length <= font.count - offset, directory[name] == nil else { continue } directory[name] = offset ..< offset + length diff --git a/Tests/Graphite2DTests/IconBytesTests.swift b/Tests/Graphite2DTests/IconBytesTests.swift index c624f38..5cb242b 100644 --- a/Tests/Graphite2DTests/IconBytesTests.swift +++ b/Tests/Graphite2DTests/IconBytesTests.swift @@ -32,4 +32,22 @@ import Graphite2D #expect(throws: MacError.parameter) { try IconFamily(icns: Data([0, 1, 2, 3])) } #expect(throws: MacError.parameter) { try IconFamily(icns: Data()) } } + + /// Values past a 32-bit Int's, and ones whose sums would pass it. + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedSizes(value: UInt32) throws { + func file(length: UInt32, size: UInt32) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(FourCharCode("icns").rawValue) + writer.write(length) + writer.write(FourCharCode("ICN#").rawValue) + writer.write(size) + writer.writeZeros(8) + return writer.bytes + } + // A member past the end. + #expect(throws: MacError.parameter) { try IconFamily(icns: file(length: 24, size: value)) } + // The family's length stops at the bytes there are. + #expect(try IconFamily(icns: file(length: value, size: 16)).members.count == 1) + } } diff --git a/Tests/Graphite2DTests/IconTests.swift b/Tests/Graphite2DTests/IconTests.swift index 1639d29..894e401 100644 --- a/Tests/Graphite2DTests/IconTests.swift +++ b/Tests/Graphite2DTests/IconTests.swift @@ -114,6 +114,13 @@ import Graphite2D #expect(icon.image == [0xFFFF_0000, 0x0000_00FF, 0xFF00_00FF, 0x00FF_0000]) #expect(icon.pixels.value(column: 0, row: 1) == 0xFF00_00FF) #expect(throws: MacError.self) { try ColorIcon(cicn: Array(writer.bytes.prefix(60))) } + // Rows too short for the icon's width: the pixel map's at 4, the + // mask's at 54. + for (offset, rowBytes) in [(4, 0), (4, 1), (54, 0)] as [(Int, UInt8)] { + var short = writer.bytes + short[offset + 1] = rowBytes + #expect(throws: MacError.parameter) { try ColorIcon(cicn: short) } + } } } @@ -170,5 +177,39 @@ import Graphite2D #expect(cursor.colorWidth == 2) #expect(cursor.argb == [0xFF00_FF00, 0xFFFF_FFFF, 0xFFFF_FFFF, 0xFF00_FF00]) #expect(throws: MacError.self) { try Cursor(crsr: Array(writer.bytes.prefix(100))) } + // Rows too short for the cursor's width: the pixel map's rowBytes. + for rowBytes: UInt8 in [0, 1] { + var short = writer.bytes + short[101] = rowBytes + #expect(throws: MacError.parameter) { try Cursor(crsr: short) } + } + } + + /// Values past a 32-bit Int's, and ones whose sums would pass it. + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedColorCursorOffsetsAreAParameterError(value: UInt32) { + // A record whose pixel map is at 96 and pixels at 146. + func record(map: UInt32 = 96, pixels: UInt32 = 146, table: UInt32 = 150) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(UInt16(0x8001)) + writer.write(map) + writer.write(pixels) + writer.writeZeros(86) + writer.writeZeros(4) + writer.write(UInt16(0x8000 | 2)) + for value: Int16 in [0, 0, 2, 2] { writer.write(UInt16(bitPattern: value)) } + writer.writeZeros(2 + 2 + 4 + 4 + 4 + 2) + writer.write(UInt16(8)) + writer.writeZeros(2 + 2 + 4) + writer.write(table) + writer.writeZeros(4) + writer.write(bytes: [1, 0, 0, 1]) + writer.write(bytes: ColorTable(colors: [.white, .black]).clut) + return writer.bytes + } + #expect(throws: Never.self) { try Cursor(crsr: record()) } + for bytes in [record(map: value), record(pixels: value), record(table: value)] { + #expect(throws: MacError.parameter) { try Cursor(crsr: bytes) } + } } } diff --git a/Tests/Graphite2DTests/PictureTests.swift b/Tests/Graphite2DTests/PictureTests.swift index 8558a02..7616305 100644 --- a/Tests/Graphite2DTests/PictureTests.swift +++ b/Tests/Graphite2DTests/PictureTests.swift @@ -292,4 +292,37 @@ private struct PictureWriter { // A PICT file's 512-byte header. #expect(try Picture(file: [UInt8](repeating: 0, count: 512) + bytes).operations.count == 2) } + + /// Values past a 32-bit Int's, and ones whose sums would pass it. + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedLengthsAreAParameterError(value: UInt32) { + // A reserved opcode skipped by its long length. + for opcode: UInt16 in [0x00D0, 0x8100, 0x8200] { + var picture = PictureWriter(frame: frame) + picture.opcode(opcode) + picture.writer.write(value) + let bytes = picture.end() + #expect(throws: MacError.parameter) { try Picture(bytes: bytes) } + } + // A compressed image's matte, mask and image description sizes. + func compressed(matteSize: UInt32 = 0, maskSize: UInt32 = 0, descriptionSize: UInt32 = 86) -> [UInt8] { + var body = BigEndianWriter() + body.writeZeros(2 + 36) // version, matrix + body.write(matteSize) + body.writeZeros(8 + 2 + 8 + 4) // matteRect, mode, source, accuracy + body.write(maskSize) + body.write(descriptionSize) + body.writeZeros(82) + var picture = PictureWriter(frame: frame) + picture.opcode(0x8200) + picture.writer.write(UInt32(body.count)) + picture.writer.write(bytes: body.bytes) + return picture.end() + } + #expect(throws: Never.self) { try Picture(bytes: compressed()) } + for bytes in [compressed(matteSize: value), compressed(maskSize: value), + compressed(matteSize: value, maskSize: value), compressed(descriptionSize: value)] { + #expect(throws: MacError.parameter) { try Picture(bytes: bytes) } + } + } } diff --git a/Tests/GraphiteAutomationTests/DescriptorClassicDataTests.swift b/Tests/GraphiteAutomationTests/DescriptorClassicDataTests.swift index 72f0517..2d12976 100644 --- a/Tests/GraphiteAutomationTests/DescriptorClassicDataTests.swift +++ b/Tests/GraphiteAutomationTests/DescriptorClassicDataTests.swift @@ -125,4 +125,22 @@ import GraphiteAutomation #expect(throws: MacError(-1702)) { try Descriptor(type: "aevt", classicData: list) } #expect(throws: MacError(-1704)) { try long(1).classicData() } } + + /// Values past a 32-bit Int's, and ones whose sums would pass it. + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedSizesAndOffsetsAreCorrupt(value: UInt32) throws { + let field = withUnsafeBytes(of: value.bigEndian) { Array($0) } + let list = try Descriptor.list([long(1)]).classicData() + // Where a list's items start, and its one item's size: its last four + // bytes before the number. + for offset in [8, list.count - 8] { + var bytes = list + bytes.replaceSubrange(offset ..< offset + 4, with: field) + #expect(throws: MacError(-1702)) { try Descriptor(type: "list", classicData: bytes) } + } + // Where an event's parameters start. + var event = captured("event without key1") + event.replaceSubrange(8 ..< 12, with: field) + #expect(throws: MacError(-1702)) { try Descriptor(type: "aevt", classicData: event) } + } } diff --git a/Tests/GraphiteCoreTests/NumberTests.swift b/Tests/GraphiteCoreTests/NumberTests.swift index 8aeec14..1d1f74f 100644 --- a/Tests/GraphiteCoreTests/NumberTests.swift +++ b/Tests/GraphiteCoreTests/NumberTests.swift @@ -64,7 +64,7 @@ import GraphiteCore @Test func roundTrips() { let values: [Double] = [0, -0.0, 1, -1, 0.5, 3.141592653589793, 1e-300, -1e300, .leastNonzeroMagnitude, - .leastNormalMagnitude, .greatestFiniteMagnitude, 5e-324 * 3, .infinity, -.infinity] + .leastNormalMagnitude, .greatestFiniteMagnitude, Double(bitPattern: 1), 5e-324 * 3, .infinity, -.infinity] for value in values { let extended = Extended80(value) #expect(extended.doubleValue == value, "\(value)") @@ -75,7 +75,9 @@ import GraphiteCore } @Test func normalizesDenormals() { - let extended = Extended80(Double.leastNonzeroMagnitude) + // The smallest denormal, which `leastNonzeroMagnitude` isn't on + // 32-bit ARM. + let extended = Extended80(Double(bitPattern: 1)) #expect(extended.mantissa == 1 << 63) #expect(extended.exponent == -1074) } diff --git a/Tests/GraphiteFilesTests/AppleDoubleBytesTests.swift b/Tests/GraphiteFilesTests/AppleDoubleBytesTests.swift index 464d66a..bd6e45c 100644 --- a/Tests/GraphiteFilesTests/AppleDoubleBytesTests.swift +++ b/Tests/GraphiteFilesTests/AppleDoubleBytesTests.swift @@ -34,4 +34,16 @@ import GraphiteFiles #expect(throws: MacError.parameter) { try AppleDouble(bytes: Data([1, 2, 3, 4, 5, 6, 7, 8])) } #expect(throws: MacError.parameter) { try AppleDouble(bytes: Data(file().prefix(30))) } } + + /// Values past a 32-bit Int's, and ones whose sums would pass it. + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedEntriesAreAParameterError(value: UInt32) { + let field = withUnsafeBytes(of: value.bigEndian) { Array($0) } + // The first entry's offset and length. + for offset in [30, 34] { + var bytes = file() + bytes.replaceSubrange(offset ..< offset + 4, with: field) + #expect(throws: MacError.parameter) { try AppleDouble(bytes: bytes) } + } + } } diff --git a/Tests/GraphiteResourcesTests/ResourceMapTests.swift b/Tests/GraphiteResourcesTests/ResourceMapTests.swift index 2a71b28..53756ff 100644 --- a/Tests/GraphiteResourcesTests/ResourceMapTests.swift +++ b/Tests/GraphiteResourcesTests/ResourceMapTests.swift @@ -100,4 +100,17 @@ import GraphiteResources #expect(version.numVersion == 0x0102_6003) #expect(throws: MacError.mapRead) { try VersionResource(bytes: [1, 2, 3]) } } + + /// Values past a 32-bit Int's, and ones whose sums would pass it. + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedLengthsAndOffsetsThrow(value: UInt32) throws { + let fork = try ResourceMap.write(Self.resources) + let field = withUnsafeBytes(of: value.bigEndian) { Array($0) } + // The header's two offsets and two lengths, then the first resource's length. + for offset in [0, 4, 8, 12, 256] { + var bytes = fork + bytes.replaceSubrange(offset ..< offset + 4, with: field) + #expect(throws: MacError.mapRead) { try ResourceMap(parsing: bytes) } + } + } } diff --git a/Tests/GraphiteSoundTests/AIFFTests.swift b/Tests/GraphiteSoundTests/AIFFTests.swift index 70a8cbd..c0a2143 100644 --- a/Tests/GraphiteSoundTests/AIFFTests.swift +++ b/Tests/GraphiteSoundTests/AIFFTests.swift @@ -236,4 +236,32 @@ import GraphiteSound if let sound = try? SampledSound(aiff: bytes) { _ = try? sound.pcm16() } } } + + /// Values past a 32-bit Int's, and ones whose sums would pass it. + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedFields(value: UInt32) throws { + let field = withUnsafeBytes(of: value.bigEndian) { Array($0) } + let good = file([common(frames: 1), soundData([0, 9])]) + // The form's size is only a limit on where chunks are looked for. + var form = good + form.replaceSubrange(4 ..< 8, with: field) + #expect(try SampledSound(aiff: form).pcm16() == [9]) + // The common chunk's size. + var chunkSize = good + chunkSize.replaceSubrange(16 ..< 20, with: field) + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: chunkSize) } + // The sound data chunk's offset. + #expect(throws: MacError.badFileFormat) { + try SampledSound(aiff: file([common(frames: 1), soundData([0, 9], offset: value)])) + } + // More frames than there are is the sound there is, and a loop to + // a marker past it is kept for the player to cut short. + let long = try SampledSound(aiff: file([ + common(frames: value), markers([(1, 0, "a"), (2, value, "b")]), instrument(playMode: 1, begin: 1, end: 2), + soundData([0, 9]), + ])) + #expect(long.count == Int(clamping: value)) + #expect(long.loop == 0 ..< Int(clamping: value)) + #expect(try long.pcm16() == [9]) + } } diff --git a/Tests/GraphiteSoundTests/SoundResourceTests.swift b/Tests/GraphiteSoundTests/SoundResourceTests.swift index bfc7730..9d6c997 100644 --- a/Tests/GraphiteSoundTests/SoundResourceTests.swift +++ b/Tests/GraphiteSoundTests/SoundResourceTests.swift @@ -280,4 +280,21 @@ import GraphiteSound if let sound = try? SampledSound(snd: bytes) { _ = try? sound.pcm16() } } } + + /// Values past a 32-bit Int's, and ones whose sums would pass it. + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedFields(value: UInt32) throws { + let field = withUnsafeBytes(of: value.bigEndian) { Array($0) } + // The bufferCmd's offset to the header, the last four bytes before it. + let header = standard([128, 129]) + var resource = format1(header) + let at = resource.count - header.count - 4 + resource.replaceSubrange(at ..< at + 4, with: field) + #expect(throws: MacError.badFormat) { try SoundResource.headerOffset(in: resource) } + #expect(throws: MacError.badFormat) { try SampledSound(snd: resource) } + // Loop points past the samples don't trap. + let looped = try SampledSound(header: standard([128, 129], loopStart: 0, loopEnd: value)) + #expect(looped.loop == 0 ..< Int(clamping: value)) + _ = try SampledSound(header: standard([128, 129], loopStart: value, loopEnd: value)) + } } diff --git a/Tests/GraphiteTextTests/SfntTablesTests.swift b/Tests/GraphiteTextTests/SfntTablesTests.swift index f6d5d74..7030c66 100644 --- a/Tests/GraphiteTextTests/SfntTablesTests.swift +++ b/Tests/GraphiteTextTests/SfntTablesTests.swift @@ -158,4 +158,36 @@ import GraphiteText } } } + + /// Values past a 32-bit Int's, and ones whose sums would pass it. + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedTableFieldsLeaveTheTableOut(value: UInt32) throws { + let field = withUnsafeBytes(of: value.bigEndian) { Array($0) } + // The first table's offset and length. + for offset in [20, 24] { + var bytes = font + bytes.replaceSubrange(offset ..< offset + 4, with: field) + let tables = try SfntTables(font: bytes) + #expect(tables.table("head") == nil) + #expect(tables.table("post") == post()) + } + } + + @Test(arguments: [0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] as [UInt32]) + func oversizedCollectionFieldsAreAParameterError(value: UInt32) { + func collection(count: UInt32, offset: UInt32) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(FourCharCode("ttcf").rawValue) + writer.write(UInt32(0x0001_0000)) + writer.write(count) + writer.write(offset) + return writer.bytes + } + #expect(throws: MacError.parameter) { try SfntTables(font: collection(count: 1, offset: value)) } + // A count of faces the file can't hold, and a face far into it: + // four bytes each would pass a 32-bit Int. + for index in [1, 0x2000_0000, Int(Int32.max) - 1] { + #expect(throws: MacError.parameter) { try SfntTables(font: collection(count: value, offset: 16), index: index) } + } + } }