Skip to content

Commit 207ae32

Browse files
committed
[stdlib] add _withUnprotectedUnsafeMutableBytes()
1 parent 528dd09 commit 207ae32

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

stdlib/public/core/UnsafeRawBufferPointer.swift.gyb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1230,6 +1230,24 @@ func __abi_se0413_withUnsafeMutableBytes<T, Result>(
12301230
}
12311231
}
12321232

1233+
/// Invokes the given closure with a buffer pointer covering the raw bytes of
1234+
/// the given argument.
1235+
///
1236+
/// This function is similar to `withUnsafeMutableBytes`, except that it
1237+
/// doesn't trigger stack protection for the pointer.
1238+
@_alwaysEmitIntoClient
1239+
public func _withUnprotectedUnsafeMutableBytes<T, E: Error, Result>(
1240+
of value: inout T,
1241+
_ body: (UnsafeMutableRawBufferPointer) throws(E) -> Result
1242+
) throws(E) -> Result {
1243+
#if $BuiltinUnprotectedAddressOf
1244+
let pointer = UnsafeMutableRawPointer(Builtin.unprotectedAddressOf(&value))
1245+
#else
1246+
let pointer = UnsafeMutableRawPointer(Builtin.addressof(&value))
1247+
#endif
1248+
return try body(.init(start: pointer, count: MemoryLayout<T>.size))
1249+
}
1250+
12331251
/// Invokes the given closure with a buffer pointer covering the raw bytes of
12341252
/// the given argument.
12351253
///

test/SILOptimizer/stack_protection.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,16 @@ public func unprotectedUnsafeBytes() {
6464
}
6565
}
6666

67+
// CHECK-LABEL: sil @$s4test29unprotectedUnsafeMutableBytesyyF
68+
// CHECK-NOT: copy_addr
69+
// CHECK: } // end sil function '$s4test29unprotectedUnsafeMutableBytesyyF'
70+
public func unprotectedUnsafeMutableBytes() {
71+
var x = 0
72+
_withUnprotectedUnsafeMutableBytes(of: &x) {
73+
potentiallyBadCFunction($0.bindMemory(to: Int.self).baseAddress!)
74+
}
75+
}
76+
6777
// CHECK-LABEL: sil [stack_protection] @$s4test20overflowInCFunction2yyF
6878
// CHECK-NOT: copy_addr
6979
// CHECK: } // end sil function '$s4test20overflowInCFunction2yyF'

0 commit comments

Comments
 (0)