Skip to content

[SR-6338] Foundation Data.withUnsafeMutableBytes crash #4060

@swift-ci

Description

@swift-ci
Previous ID SR-6338
Radar rdar://problem/35442650
Original Reporter spc (JIRA User)
Type Bug
Status Closed
Resolution Done

Attachment: Download

Environment
  1. Tested from Xcode Version 9.1 (9B55), iOS Playground.

  2. Also tested on macOS High Sierra 10.13.1, with Apple Swift version 4.0.2 (swiftlang-900.0.69.2 clang-900.0.38),

Target: x86_64-apple-macosx10.9

Additional Detail from JIRA
Votes 0
Component/s Foundation
Labels Bug, RunTimeCrash
Assignee None
Priority Medium

md5: da28edbd18f5aa764fc8449dcf8f7cac

Issue Description:

Bellow swift code compiles, but failed to execute. The method 'withUnsafeMutableBytes' will raise an exception:

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

And in the call stack, I find the exception is raised from this method

// https://github.com/apple/swift/blob/swift-4.1-branch/stdlib/public/SDK/Foundation/Data.swift
public func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result
// The issue can be reproduced and always occurs. 

import Foundation

extension Data {
    mutating func overwrite<T>(_ value: T) {
        let typeSize = MemoryLayout<T>.size
        guard count == typeSize else {
            print("Failed to write value into data")
            return
        }
        self.withUnsafeMutableBytes({ (ptr: UnsafeMutablePointer<T>) -> Void in
            ptr.pointee = value
            return
        })
        return
    }
}


var data = Data(count: 6)

let one: UInt16 = 1

data[0...1].overwrite(one)
data[2...3].overwrite(one)
data[4...5].overwrite(one)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions