diff --git a/NOTICE.txt b/NOTICE.txt index e2167974..a7756f29 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -34,7 +34,7 @@ This product contains test vectors from Google's wycheproof project. --- -This product contains a derivation of various scripts from SwiftNIO. +This product contains a derivation of various files from SwiftNIO. * LICENSE (Apache License 2.0): * https://www.apache.org/licenses/LICENSE-2.0 diff --git a/Sources/_CryptoExtras/CMakeLists.txt b/Sources/_CryptoExtras/CMakeLists.txt index f32a903e..d4c8ea26 100644 --- a/Sources/_CryptoExtras/CMakeLists.txt +++ b/Sources/_CryptoExtras/CMakeLists.txt @@ -65,6 +65,10 @@ add_library(_CryptoExtras "Util/PEMDocument.swift" "Util/PrettyBytes.swift" "Util/SubjectPublicKeyInfo.swift" + "Util/ThreadSpecific/ThreadOps.swift" + "Util/ThreadSpecific/ThreadPosix.swift" + "Util/ThreadSpecific/ThreadSpecific.swift" + "Util/ThreadSpecific/ThreadWindows.swift" "ZKPs/DLEQ.swift" "ZKPs/Prover.swift" "ZKPs/Verifier.swift" diff --git a/Sources/_CryptoExtras/ECToolbox/BoringSSL/ECToolbox_boring.swift b/Sources/_CryptoExtras/ECToolbox/BoringSSL/ECToolbox_boring.swift index fd369d77..0a08ff52 100644 --- a/Sources/_CryptoExtras/ECToolbox/BoringSSL/ECToolbox_boring.swift +++ b/Sources/_CryptoExtras/ECToolbox/BoringSSL/ECToolbox_boring.swift @@ -65,14 +65,15 @@ extension P256: OpenSSLSupportedNISTCurve { @inlinable static var hashToFieldByteCount: Int { 48 } + private static let __ffacTSV = ThreadSpecificVariable() + @usableFromInline static var __ffac: FiniteFieldArithmeticContext { - let key = "com.apple.swift-crypto.P256.__ffac" - if let value = Thread.current.threadDictionary[key] as? FiniteFieldArithmeticContext { + if let value = Self.__ffacTSV.currentValue { return value } let value = try! FiniteFieldArithmeticContext(fieldSize: P256.group.order) - Thread.current.threadDictionary[key] = value + Self.__ffacTSV.currentValue = value return value } } @@ -98,14 +99,15 @@ extension P384: OpenSSLSupportedNISTCurve { @inlinable static var hashToFieldByteCount: Int { 72 } + private static let __ffacTSV = ThreadSpecificVariable() + @usableFromInline static var __ffac: FiniteFieldArithmeticContext { - let key = "com.apple.swift-crypto.P384.__ffac" - if let value = Thread.current.threadDictionary[key] as? FiniteFieldArithmeticContext { + if let value = Self.__ffacTSV.currentValue { return value } let value = try! FiniteFieldArithmeticContext(fieldSize: P384.group.order) - Thread.current.threadDictionary[key] = value + Self.__ffacTSV.currentValue = value return value } } @@ -131,14 +133,15 @@ extension P521: OpenSSLSupportedNISTCurve { @inlinable static var hashToFieldByteCount: Int { 98 } + private static let __ffacTSV = ThreadSpecificVariable() + @usableFromInline static var __ffac: FiniteFieldArithmeticContext { - let key = "com.apple.swift-crypto.P521.__ffac" - if let value = Thread.current.threadDictionary[key] as? FiniteFieldArithmeticContext { + if let value = Self.__ffacTSV.currentValue { return value } let value = try! FiniteFieldArithmeticContext(fieldSize: P521.group.order) - Thread.current.threadDictionary[key] = value + Self.__ffacTSV.currentValue = value return value } } diff --git a/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadOps.swift b/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadOps.swift new file mode 100644 index 00000000..0dc4111f --- /dev/null +++ b/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadOps.swift @@ -0,0 +1,35 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2014 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +protocol ThreadOps { + associatedtype ThreadSpecificKey + associatedtype ThreadSpecificKeyDestructor + + static func allocateThreadSpecificValue(destructor: ThreadSpecificKeyDestructor) -> ThreadSpecificKey + static func deallocateThreadSpecificValue(_ key: ThreadSpecificKey) + static func getThreadSpecificValue(_ key: ThreadSpecificKey) -> UnsafeMutableRawPointer? + static func setThreadSpecificValue(key: ThreadSpecificKey, value: UnsafeMutableRawPointer?) +} diff --git a/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadPosix.swift b/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadPosix.swift new file mode 100644 index 00000000..6b2ccdf0 --- /dev/null +++ b/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadPosix.swift @@ -0,0 +1,73 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +#if os(Linux) || os(Android) || os(FreeBSD) || canImport(Darwin) +#if canImport(Glibc) +@preconcurrency import Glibc +#elseif canImport(Bionic) +@preconcurrency import Bionic +#elseif canImport(Musl) +@preconcurrency import Musl +#elseif canImport(Android) +@preconcurrency import Android +#elseif canImport(Darwin) +import Darwin +#endif + +typealias ThreadOpsSystem = ThreadOpsPosix + +enum ThreadOpsPosix: ThreadOps { + typealias ThreadSpecificKey = pthread_key_t + #if canImport(Darwin) + typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer) -> Void + #else + typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer?) -> Void + #endif + + static func allocateThreadSpecificValue(destructor: @escaping ThreadSpecificKeyDestructor) -> ThreadSpecificKey { + var value = pthread_key_t() + let result = pthread_key_create(&value, Optional(destructor)) + precondition(result == 0, "pthread_key_create failed: \(result)") + return value + } + + static func deallocateThreadSpecificValue(_ key: ThreadSpecificKey) { + let result = pthread_key_delete(key) + precondition(result == 0, "pthread_key_delete failed: \(result)") + } + + static func getThreadSpecificValue(_ key: ThreadSpecificKey) -> UnsafeMutableRawPointer? { + pthread_getspecific(key) + } + + static func setThreadSpecificValue(key: ThreadSpecificKey, value: UnsafeMutableRawPointer?) { + let result = pthread_setspecific(key, value) + precondition(result == 0, "pthread_setspecific failed: \(result)") + } +} + +#endif diff --git a/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadSpecific.swift b/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadSpecific.swift new file mode 100644 index 00000000..96eb7100 --- /dev/null +++ b/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadSpecific.swift @@ -0,0 +1,111 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2025 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +// Derived from swift-nio's ThreadSpecificVariable type. + +/// A ``ThreadSpecificVariable`` is a variable that can be read and set like a normal variable except that it holds +/// different variables per thread. +/// +/// ``ThreadSpecificVariable`` is thread-safe so it can be used with multiple threads at the same time but the value +/// returned by ``currentValue`` is defined per thread. +/// +/// - Note: Though ``ThreadSpecificVariable`` is thread-safe, it is not `Sendable` unless `Value` is `Sendable`. +/// If ``ThreadSpecificVariable`` were unconditionally `Sendable`, it could be used to "smuggle" +/// non-`Sendable` state out of an actor or other isolation domain without triggering warnings. If you +/// are attempting to use ``ThreadSpecificVariable`` with non-`Sendable` data, consider using a dynamic +/// enforcement tool like `NIOLoopBoundBox` to police the access. +final class ThreadSpecificVariable { + // the actual type in there is `Box<(ThreadSpecificVariable, T)>` but we can't use that as C functions can't capture (even types) + private typealias BoxedType = Box<(AnyObject, AnyObject)> + + private class Key { + private var underlyingKey: ThreadOpsSystem.ThreadSpecificKey + + internal init(destructor: @escaping ThreadOpsSystem.ThreadSpecificKeyDestructor) { + self.underlyingKey = ThreadOpsSystem.allocateThreadSpecificValue(destructor: destructor) + } + + deinit { + ThreadOpsSystem.deallocateThreadSpecificValue(self.underlyingKey) + } + + func get() -> UnsafeMutableRawPointer? { + ThreadOpsSystem.getThreadSpecificValue(self.underlyingKey) + } + + func set(value: UnsafeMutableRawPointer?) { + ThreadOpsSystem.setThreadSpecificValue(key: self.underlyingKey, value: value) + } + } + + private let key: Key + + /// Initialize a new `ThreadSpecificVariable` without a current value (`currentValue == nil`). + init() { + self.key = Key(destructor: { + Unmanaged.fromOpaque(($0 as UnsafeMutableRawPointer?)!).release() + }) + } + + /// Initialize a new `ThreadSpecificVariable` with `value` for the calling thread. After calling this, the calling + /// thread will see `currentValue == value` but on all other threads `currentValue` will be `nil` until changed. + /// + /// - Parameters: + /// - value: The value to set for the calling thread. + convenience init(value: Value) { + self.init() + self.currentValue = value + } + + /// The value for the current thread. + @available( + *, + noasync, + message: "threads can change between suspension points and therefore the thread specific value too" + ) + var currentValue: Value? { + get { + self.get() + } + set { + self.set(newValue) + } + } + + /// Get the current value for the calling thread. + private func get() -> Value? { + guard let raw = self.key.get() else { return nil } + // parenthesize the return value to silence the cast warning + return + (Unmanaged + .fromOpaque(raw) + .takeUnretainedValue() + .value.1 as! Value) + } + + /// Set the current value for the calling threads. The `currentValue` for all other threads remains unchanged. + private func set(_ newValue: Value?) { + if let raw = self.key.get() { + Unmanaged.fromOpaque(raw).release() + } + self.key.set(value: newValue.map { Unmanaged.passRetained(Box((self, $0))).toOpaque() }) + } +} + +extension ThreadSpecificVariable: @unchecked Sendable where Value: Sendable {} + +final class Box { + let value: T + init(_ value: T) { self.value = value } +} diff --git a/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadWindows.swift b/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadWindows.swift new file mode 100644 index 00000000..6cbacedd --- /dev/null +++ b/Sources/_CryptoExtras/Util/ThreadSpecific/ThreadWindows.swift @@ -0,0 +1,56 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2025 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +#if os(Windows) + +import WinSDK + +typealias ThreadOpsSystem = ThreadOpsWindows + +enum ThreadOpsWindows: ThreadOps { + typealias ThreadSpecificKey = DWORD + typealias ThreadSpecificKeyDestructor = @convention(c) (UnsafeMutableRawPointer?) -> Void + + static func allocateThreadSpecificValue(destructor: @escaping ThreadSpecificKeyDestructor) -> ThreadSpecificKey { + FlsAlloc(destructor) + } + + static func deallocateThreadSpecificValue(_ key: ThreadSpecificKey) { + let dwResult: Bool = FlsFree(key) + precondition(dwResult, "FlsFree: \(GetLastError())") + } + + static func getThreadSpecificValue(_ key: ThreadSpecificKey) -> UnsafeMutableRawPointer? { + FlsGetValue(key) + } + + static func setThreadSpecificValue(key: ThreadSpecificKey, value: UnsafeMutableRawPointer?) { + FlsSetValue(key, value) + } +} + +#endif