Skip to content

Crash: Variable is not retained in await statement in Release mode. #61658

@WarWithinMe

Description

@WarWithinMe

Describe the bug
In Release mode, a variable might not get retained if it's being used in an await statement.
In Debug mode, the crash does not exist.

Steps To Reproduce
Minimal reproduce code:

import UIKit

class Data {
  var obj = NSObject()
}

actor Consumer {
  func consume(_ data: Data) { print(data) }
}

class View: UIView {
  var consumer = Consumer()

  var data: Data? {
    didSet {

      // 1. Crash. data is released before consumer.consume(), then consumer prints an already released object.
      //    This only happens in Release mode
      Task {
        if let data {
          await consumer.consume(data)
        }
      }

      // 2. Works fine, if data is used before await.
//      Task {
//        if let data {
//          print(data)
//          await consumer.consume(data)
//        }
//      }

      // 3. Works fine, if there's another statement before await.
//      Task {
//        if let data {
//          print("ok")
//          await consumer.consume(data)
//        }
//      }

      // 4. Works fine, if there's another task.
//      Task {
//        if let data {
//          Task {
//            await consumer.consume(data)
//          }
//        }
//      }
    }
  }
}

class ViewController: UIViewController {
  override func loadView() {
    self.view = View(frame: .init(x: 0, y: 0, width: 100, height: 100))
  }
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    Task {
      while (true) {
        try await Task.sleep(nanoseconds: 1000)
        (view as! View).data = .init()
      }
    }
  }
}

Expected behavior
The data object shƒould stay valid until after the await statement.

Environment (please fill out the following information)

  • OS: [e.g. macOS 11.0] ios 16
  • Xcode Version/Tag/Branch: Xcode-14.1.0-Release.Candidate

Additional context
Tested with swiftlang-5.7.1.135.2 clang-1400.0.29.51

Minimal Project to Reproduce
Test.zip

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.crashBug: A crash, i.e., an abnormal termination of softwareoptimized onlyFlag: An issue whose reproduction requires optimized compilationrun-time crashBug → crash: Swift code crashed during execution

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions