Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SystemInternals: support mocking on Windows #9

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Sources/SystemInternals/Mocking.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,24 +87,41 @@ public class MockingDriver {
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
import Glibc
#elseif os(Windows)
import ucrt
import WinSDK
#else
#error("Unsupported Platform")
#endif

#if os(Windows)
internal let key: DWORD = {
var raw: DWORD = FlsAlloc(nil)
if raw == FLS_OUT_OF_INDEXES {
fatalError("Unable to create key")
}
return raw
}()
#else
internal let key: pthread_key_t = {
var raw = pthread_key_t()
guard 0 == pthread_key_create(&raw, nil) else {
fatalError("Unable to create key")
}
return raw
}()
#endif

internal var currentMockingDriver: MockingDriver? {
#if !ENABLE_MOCKING
fatalError("Contextual mocking in non-mocking build")
#endif

#if os(Windows)
guard let rawPtr = FlsGetValue(key) else { return nil }
#else
guard let rawPtr = pthread_getspecific(key) else { return nil }
#endif

return Unmanaged<MockingDriver>.fromOpaque(rawPtr).takeUnretainedValue()
}
Expand All @@ -120,16 +137,30 @@ extension MockingDriver {

defer {
if let object = priorMocking {
#if os(Windows)
_ = FlsSetValue(key, Unmanaged.passUnretained(object).toOpaque())
#else
pthread_setspecific(key, Unmanaged.passUnretained(object).toOpaque())
#endif
} else {
#if os(Windows)
_ = FlsSetValue(key, nil)
#else
pthread_setspecific(key, nil)
#endif
}
_fixLifetime(driver)
}

#if os(Windows)
guard FlsSetValue(key, Unmanaged.passUnretained(driver).toOpaque()) else {
fatalError("Unable to set TLSData")
}
#else
guard 0 == pthread_setspecific(key, Unmanaged.passUnretained(driver).toOpaque()) else {
fatalError("Unable to set TLSData")
}
#endif

return try f(driver)
}
Expand Down