swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
66.77k stars 10.29k forks source link

Swift 5.7 crash in iOS 15 or lower with -Osize optimisation level. #60743

Open mikhailmulyar opened 1 year ago

mikhailmulyar commented 1 year ago

Describe the bug This code crashes in iOS 15 or lower simulator or device when optimisation level is set to -Osize. It is crashing with EXC_BAD_ACCESS.

import SwiftUI

protocol SomeProto: AnyObject {
    var proto: any SomeGenericProto<Int> { get set }
    func getElements() -> [Int]
}

class SomeImpl: SomeProto {
    var proto: any SomeGenericProto<Int> = SomeGenericImpl(elements: [1,2,3])

    func getElements() -> [Int] {
        proto.getElements()
    }
}

protocol SomeGenericProto<Element> {
    associatedtype Element

    func getElements() -> [Element]
}

final class SomeGenericImpl<Element>: SomeGenericProto {

    private let elements: [Element]

    init(elements: [Element]) {
        self.elements = elements
    }

    func getElements() -> [Element] {
        elements
    }
}

struct ContentView: View {

    var someValue: any SomeProto = SomeImpl()

    var body: some View {
        VStack {
            Text("Hello, world!" + "\(someValue.getElements().last ?? 0)")
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Steps To Reproduce Steps to reproduce the behavior:

  1. Create simple app project in Xcode 14 beta and paste this code into ContentView.swift.
  2. Set SWIFT_OPTIMIZATION_LEVEL to -Osize.
  3. Run app in iOS simulator 15.5 or lower.

Expected behavior App should not crash

Environment (please fill out the following information)

Additional context Possible workaround for crash is to conform SomeGenericProto to AnyObject

protocol SomeGenericProto<Element>: AnyObject
vrutberg commented 1 year ago

FWIW we just hit this bug at my job, where our iOS app would crash on iOS 15.x.

tbkka commented 1 year ago

To diagnose crashes like this, we need a backtrace of the crashing app and ideally a small project that reproduces the crash.

AnthonyLatsis commented 1 year ago

Reduced example:

protocol P<A> {
  associatedtype A
}
func foo(_: any P<Never>) {}

This should be rejected with Runtime support for parameterized protocol types is only available in ... or newer when targeting OSs with 5.6 or older runtimes.