File: Mocking.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (369 lines) | stat: -rw-r--r-- 10,131 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 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
//
//===----------------------------------------------------------------------===//

/*
 This source file is part of the Swift System open source project

 Copyright (c) 2020 Apple Inc. and the Swift System project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See https://swift.org/LICENSE.txt for license information
 */

#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android)
import SystemPackage

#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
import CNIOLinux
#elseif canImport(Musl)
import Musl
import CNIOLinux
#endif

// Syscall mocking support.
//
// NOTE: This is currently the bare minimum needed for System's testing purposes, though we do
// eventually want to expose some solution to users.
//
// Mocking is contextual, accessible through MockingDriver.withMockingEnabled. Mocking
// state, including whether it is enabled, is stored in thread-local storage. Mocking is only
// enabled in testing builds of System currently, to minimize runtime overhead of release builds.
//

#if ENABLE_MOCKING
@_spi(Testing)
public struct Trace {
    @_spi(Testing)
    public struct Entry {
        @_spi(Testing)
        public var name: String
        @_spi(Testing)
        public var arguments: [AnyHashable]

        @_spi(Testing)
        public init(name: String, _ arguments: [AnyHashable]) {
            self.name = name
            self.arguments = arguments
        }
    }

    private var entries: [Entry] = []
    private var firstEntry: Int = 0

    @_spi(Testing)
    public var isEmpty: Bool { firstEntry >= entries.count }

    @_spi(Testing)
    public mutating func dequeue() -> Entry? {
        guard !self.isEmpty else { return nil }
        defer { firstEntry += 1 }
        return entries[firstEntry]
    }

    fileprivate mutating func add(_ e: Entry) {
        entries.append(e)
    }
}

@_spi(Testing)
public enum ForceErrno: Equatable {
    case none
    case always(errno: CInt)

    case counted(errno: CInt, count: Int)
}

// Provide access to the driver, context, and trace stack of mocking
@_spi(Testing)
public final class MockingDriver {
    // Record syscalls and their arguments
    @_spi(Testing)
    public var trace = Trace()

    // Mock errors inside syscalls
    @_spi(Testing)
    public var forceErrno = ForceErrno.none

    // Whether we should pretend to be Windows for syntactic operations
    // inside FilePath
    fileprivate var forceWindowsSyntaxForPaths = false
}

private let driverKey: _PlatformTLSKey = { makeTLSKey() }()

internal var currentMockingDriver: MockingDriver? {
    #if !ENABLE_MOCKING
    fatalError("Contextual mocking in non-mocking build")
    #endif
    guard let rawPtr = getTLS(driverKey) else { return nil }

    return Unmanaged<MockingDriver>.fromOpaque(rawPtr).takeUnretainedValue()
}

extension MockingDriver {
    /// Enables mocking for the duration of `f` with a clean trace queue
    /// Restores prior mocking status and trace queue after execution
    @_spi(Testing)
    public static func withMockingEnabled(
        _ f: (MockingDriver) throws -> Void
    ) rethrows {
        let priorMocking = currentMockingDriver
        let driver = MockingDriver()

        defer {
            if let object = priorMocking {
                setTLS(driverKey, Unmanaged.passUnretained(object).toOpaque())
            } else {
                setTLS(driverKey, nil)
            }
            _fixLifetime(driver)
        }

        setTLS(driverKey, Unmanaged.passUnretained(driver).toOpaque())
        return try f(driver)
    }
}

// Check TLS for mocking
@inline(never)
private var contextualMockingEnabled: Bool {
    return currentMockingDriver != nil
}

extension MockingDriver {
    @_spi(Testing)
    public static var enabled: Bool { mockingEnabled }

    @_spi(Testing)
    public static var forceWindowsPaths: Bool {
        currentMockingDriver?.forceWindowsSyntaxForPaths ?? false
    }
}

#endif  // ENABLE_MOCKING

@inline(__always)
internal var mockingEnabled: Bool {
    // Fast constant-foldable check for release builds
    #if ENABLE_MOCKING
    return contextualMockingEnabled
    #else
    return false
    #endif
}

@inline(__always)
internal var forceWindowsPaths: Bool {
    #if !ENABLE_MOCKING
    return false
    #else
    return MockingDriver.forceWindowsPaths
    #endif
}

#if ENABLE_MOCKING
// Strip the mock_system prefix and the arg list suffix
private func originalSyscallName(_ function: String) -> String {
    // `function` must be of format `system_<name>(<parameters>)`
    for `prefix` in ["system_", "libc_"] {
        if function.starts(with: `prefix`) {
            return String(function.dropFirst(`prefix`.count).prefix { $0 != "(" })
        }
    }
    preconditionFailure("\(function) must start with 'system_' or 'libc_'")
}

private func mockImpl(syscall name: String, args: [AnyHashable]) -> CInt {
    precondition(mockingEnabled)
    let origName = originalSyscallName(name)
    guard let driver = currentMockingDriver else {
        fatalError("Mocking requested from non-mocking context")
    }

    driver.trace.add(Trace.Entry(name: origName, args))

    switch driver.forceErrno {
    case .none: break
    case .always(let e):
        system_errno = e
        return -1
    case .counted(let e, let count):
        assert(count >= 1)
        system_errno = e
        driver.forceErrno = count > 1 ? .counted(errno: e, count: count - 1) : .none
        return -1
    }

    return 0
}

private func reinterpret(_ args: [AnyHashable?]) -> [AnyHashable] {
    return args.map { arg in
        switch arg {
        case let charPointer as UnsafePointer<CInterop.PlatformChar>:
            return String(_errorCorrectingPlatformString: charPointer)
        case is UnsafeMutablePointer<CInterop.PlatformChar>:
            return "<buffer>"
        case is UnsafeMutableRawPointer:
            return "<buffer>"
        case is UnsafeRawPointer:
            return "<buffer>"
        case .none:
            return "nil"
        case let .some(arg):
            return arg
        }
    }
}

func mock(
    syscall name: String = #function,
    _ args: AnyHashable?...
) -> CInt {
    return mockImpl(syscall: name, args: reinterpret(args))
}

func mockInt(
    syscall name: String = #function,
    _ args: AnyHashable?...
) -> Int {
    return Int(mockImpl(syscall: name, args: reinterpret(args)))
}

#endif  // ENABLE_MOCKING

// Force paths to be treated as Windows syntactically if `enabled` is
// true.
@_spi(Testing)
public func _withWindowsPaths(enabled: Bool, _ body: () -> Void) {
    #if ENABLE_MOCKING
    guard enabled else {
        body()
        return
    }
    MockingDriver.withMockingEnabled { driver in
        driver.forceWindowsSyntaxForPaths = true
        body()
    }
    #else
    body()
    #endif
}

// Internal wrappers and typedefs which help reduce #if littering in System's
// code base.

// TODO: Should CSystem just include all the header files we need?

internal typealias _COffT = off_t

// MARK: syscalls and variables

#if canImport(Darwin)
internal var system_errno: CInt {
    get { Darwin.errno }
    set { Darwin.errno = newValue }
}
#elseif canImport(Glibc)
internal var system_errno: CInt {
    get { Glibc.errno }
    set { Glibc.errno = newValue }
}
#elseif canImport(Musl)
internal var system_errno: CInt {
    get { Musl.errno }
    set { Musl.errno = newValue }
}
#endif

// MARK: C stdlib decls

// Convention: `system_foo` is system's wrapper for `foo`.

internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer<Int8>! {
    strerror(__errnum)
}

internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
    strlen(s)
}
internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
    strlen(s)
}

// Convention: `system_platform_foo` is a
// platform-representation-abstracted wrapper around `foo`-like functionality.
// Type and layout differences such as the `char` vs `wchar` are abstracted.
//

// strlen for the platform string
internal func system_platform_strlen(_ s: UnsafePointer<CInterop.PlatformChar>) -> Int {
    return strlen(s)
}

// memset for raw buffers
// FIXME: Do we really not have something like this in the stdlib already?
internal func system_memset(
    _ buffer: UnsafeMutableRawBufferPointer,
    to byte: UInt8
) {
    guard buffer.count > 0 else { return }
    memset(buffer.baseAddress!, CInt(byte), buffer.count)
}

// Interop between String and platfrom string
extension String {
    internal func _withPlatformString<Result>(
        _ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
    ) rethrows -> Result {
        // Need to #if because CChar may be signed
        return try withCString(body)
    }

    internal init?(_platformString platformString: UnsafePointer<CInterop.PlatformChar>) {
        // Need to #if because CChar may be signed
        self.init(validatingUTF8: platformString)
    }

    internal init(
        _errorCorrectingPlatformString platformString: UnsafePointer<CInterop.PlatformChar>
    ) {
        // Need to #if because CChar may be signed
        self.init(cString: platformString)
    }
}

internal typealias _PlatformTLSKey = pthread_key_t

internal func makeTLSKey() -> _PlatformTLSKey {
    var raw = pthread_key_t()
    guard 0 == pthread_key_create(&raw, nil) else {
        fatalError("Unable to create key")
    }
    return raw
}

internal func setTLS(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) {
    guard 0 == pthread_setspecific(key, p) else {
        fatalError("Unable to set TLS")
    }
}

internal func getTLS(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
    return pthread_getspecific(key)
}
#endif