[swift-users] What is "binding" memory?

Andrew Trick atrick at apple.com
Thu Nov 3 22:48:01 CDT 2016


> On Nov 2, 2016, at 10:07 AM, Manfred Schubert via swift-users <swift-users at swift.org> wrote:
> 
> Am 01.11.2016 um 21:40 schrieb Andrew Trick <atrick at apple.com>:
>> 
>> I’m not sure I like the “prepares the memory” language myself. Binding memory communicates to the compiler that the memory locations are safe for typed access. Nothing happens at runtime--until someone writes a type safety sanitizer.
> 
> So nothing happens at runtime, and also nothing appears to happen at compile time.

Nothing observable happens at the call to ptrT = bindMemory(to: T.self, …). It's effect on the program is making the subsequent ptrT.pointee a well-defined operation.

> If I try this code:
> 
>> var rawPtr = UnsafeMutableRawPointer.allocate(bytes: 2, alignedTo: 0)
>> 
>> var widePtr = rawPtr.bindMemory(to: Int16.self, capacity: 1)
>> 
>> widePtr.pointee = 32
>> 
>> var narrowPtr = rawPtr.bindMemory(to: UInt8.self, capacity: 2)
>> 
>> narrowPtr[0] = 16
>> narrowPtr[1] = 255
>> 
>> print(widePtr.pointee)
> 
> This compiles and runs as expected, but it should not be allowed if I understand things correctly. So shouldn’t it be a compile time error or crash at runtime? If not, what do I get over how it was before where I was casting to a typed pointer?

print(widePtr.pointee) is undefined. It may execute just the way you expect. In practice, it may also be reordered with the assignments to narrowPtr. Our optimizer is designed to do that but by chance isn’t in this version of the compiler. In theory anything can happen.

The real danger of undefined behavior of course is that the program will behave as you expect without warning when you develop the code, and future versions of the compiler may change the behavior in unpredictable ways.

This API will make it easier to develop static diagnostics that catch undefined behavior and much easier to write a runtime sanitizer. Neither of those things exist yet. It might be easy to catch obvious cases like this, but the value of catching just the obvious cases is limited.

>> It affects the abstract state of the memory location, independent of the pointer variable used to access that memory. Binding memory returns a typed pointer for convenience and clarity, but there’s nothing special about that particular pointer value.
> 
> If it were not returning a typed pointer, what would it actually do?

It would bind memory. Returning a typed pointer actually has nothing to do with its semantics.

That fact that it’s one of the only ways to get a typed pointer from a raw pointer forces the programmer to bind the memory’s type before performing typed access on the memory.

-Andy

> 
> 
> Manfred
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list