Skip to content

Constrain implicit raw pointer conversion to bitwise-copyable values #64927

@atrick

Description

@atrick

Swift 5.9 introduces warnings that catch conversions from an inout argument in the caller to an UnsafeRawPointer in the callee whenever the original type contains an object reference.

For general types:
warning: forming an 'UnsafeRawPointer' to a variable of type 'T'; this is likely incorrect because 'T' may contain an object reference.

For arrays:
warning: forming an 'UnsafeRawPointer' to a variable of type '[T]'; this is likely incorrect because 'T' may contain an object reference.

For strings:
warning: forming an 'UnsafeRawPointer' to an inout variable of type String exposes the internal representation rather than the string contents.

This issue is explained in the Swift evolution pitch Constrain implicit raw pointer conversion to bitwise-copyable values.

To workaround these warnings, please refer to Workarounds for common cases.

To understand why the warning is necessary, consider these examples. Here, the user likely wants to inspect the contents of a string, but instead they've leaked the internal representation:

func inspectString(string: inout String) {
  readBytes(&string) // reads the string's internal representation
}

This is a pernicious security issue because the code will happen to work during testing for small strings. Removing the '&' sigil changes the string conversion into an array-like conversion:

func inspectString(string: inout String) {
  readBytes(string) // reads the string's characters
}

In the next example, the author clearly expected Foundation.Data to have the same sort of implicit conversion support as Array:

func foo(data: inout Data) {
  readBytes(&data)
}

This compiles without warning, but it unintentionally exposes data object's internal storage representation rather than its elements.

Metadata

Metadata

Assignees

Labels

featureA feature request or implementationswift 5.9

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions