Skip to content

Commit

Permalink
% swiftlint autocorrect
Browse files Browse the repository at this point in the history
  • Loading branch information
sigito committed Dec 22, 2016
1 parent cc3db66 commit b08e22a
Show file tree
Hide file tree
Showing 49 changed files with 195 additions and 229 deletions.
Expand Up @@ -27,43 +27,43 @@ private func raiseBadInstructionException() {
/// A simple NSException subclass. It's not required to subclass NSException (since the exception type is represented in the name) but this helps for identifying the exception through runtime type.
@objc public class BadInstructionException: NSException {
static var name: String = "com.cocoawithlove.BadInstruction"

init() {
super.init(name: NSExceptionName(rawValue: BadInstructionException.name), reason: nil, userInfo: nil)
}

required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

/// An Objective-C callable function, invoked from the `mach_exc_server` callback function `catch_mach_exception_raise_state` to push the `raiseBadInstructionException` function onto the stack.
public class func catch_mach_exception_raise_state(_ exception_port: mach_port_t, exception: exception_type_t, code: UnsafePointer<mach_exception_data_type_t>, codeCnt: mach_msg_type_number_t, flavor: UnsafeMutablePointer<Int32>, old_state: UnsafePointer<natural_t>, old_stateCnt: mach_msg_type_number_t, new_state: thread_state_t, new_stateCnt: UnsafeMutablePointer<mach_msg_type_number_t>) -> kern_return_t {

#if arch(x86_64)
// Make sure we've been given enough memory
if old_stateCnt != x86_THREAD_STATE64_COUNT || new_stateCnt.pointee < x86_THREAD_STATE64_COUNT {
return KERN_INVALID_ARGUMENT
}

// Read the old thread state
var state = old_state.withMemoryRebound(to: x86_thread_state64_t.self, capacity: 1) { return $0.pointee }

// 1. Decrement the stack pointer
state.__rsp -= __uint64_t(MemoryLayout<Int>.size)

// 2. Save the old Instruction Pointer to the stack.
if let pointer = UnsafeMutablePointer<__uint64_t>(bitPattern: UInt(state.__rsp)) {
pointer.pointee = state.__rip
} else {
return KERN_INVALID_ARGUMENT
}

// 3. Set the Instruction Pointer to the new function's address
var f: @convention(c) () -> Void = raiseBadInstructionException
withUnsafePointer(to: &f) {
state.__rip = $0.withMemoryRebound(to: __uint64_t.self, capacity: 1) { return $0.pointee }
}

// Write the new thread state
new_state.withMemoryRebound(to: x86_thread_state64_t.self, capacity: 1) { $0.pointee = state }
new_stateCnt.pointee = x86_THREAD_STATE64_COUNT
Expand Down
Expand Up @@ -21,18 +21,18 @@
import Foundation

#if arch(x86_64)

private enum PthreadError: Error { case code(Int32) }
private enum MachExcServer: Error { case code(kern_return_t) }

/// A quick function for converting Mach error results into Swift errors
private func kernCheck(_ f: () -> Int32) throws {
let r = f()
guard r == KERN_SUCCESS else {
throw NSError(domain: NSMachErrorDomain, code: Int(r), userInfo: nil)
}
}

extension execTypesCountTuple {
mutating func pointer<R>(in block: (UnsafeMutablePointer<T>) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
Expand All @@ -42,7 +42,7 @@ import Foundation
}
}
}

extension request_mach_exception_raise_t {
mutating func withMsgHeaderPointer<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
Expand All @@ -52,7 +52,7 @@ import Foundation
}
}
}

extension reply_mach_exception_raise_state_t {
mutating func withMsgHeaderPointer<R>(in block: (UnsafeMutablePointer<mach_msg_header_t>) -> R) -> R {
return withUnsafeMutablePointer(to: &self) { p -> R in
Expand All @@ -62,7 +62,7 @@ import Foundation
}
}
}

/// A structure used to store context associated with the Mach message port
private struct MachContext {
var masks = execTypesCountTuple<exception_mask_t>()
Expand All @@ -72,7 +72,7 @@ import Foundation
var flavors = execTypesCountTuple<thread_state_flavor_t>()
var currentExceptionPort: mach_port_t = 0
var handlerThread: pthread_t? = nil

mutating func withUnsafeMutablePointers<R>(in block: (UnsafeMutablePointer<exception_mask_t>, UnsafeMutablePointer<mach_port_t>, UnsafeMutablePointer<exception_behavior_t>, UnsafeMutablePointer<thread_state_flavor_t>) -> R) -> R {
return masks.pointer { masksPtr in
return ports.pointer { portsPtr in
Expand All @@ -85,13 +85,13 @@ import Foundation
}
}
}

/// A function for receiving mach messages and parsing the first with mach_exc_server (and if any others are received, throwing them away).
private func machMessageHandler(_ arg: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? {
let context = arg.assumingMemoryBound(to: MachContext.self).pointee
var request = request_mach_exception_raise_t()
var reply = reply_mach_exception_raise_state_t()

var handledfirstException = false
repeat { do {
// Request the next mach message from the port
Expand All @@ -100,26 +100,26 @@ import Foundation
try kernCheck { request.withMsgHeaderPointer { requestPtr in
mach_msg(requestPtr, MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0, request.Head.msgh_size, context.currentExceptionPort, 0, UInt32(MACH_PORT_NULL))
} }

// Prepare the reply structure
reply.Head.msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(request.Head.msgh_bits), 0)
reply.Head.msgh_local_port = UInt32(MACH_PORT_NULL)
reply.Head.msgh_remote_port = request.Head.msgh_remote_port
reply.Head.msgh_size = UInt32(MemoryLayout<reply_mach_exception_raise_state_t>.size)
reply.NDR = NDR_record

if !handledfirstException {
// Use the MiG generated server to invoke our handler for the request and fill in the rest of the reply structure
guard request.withMsgHeaderPointer(in: { requestPtr in reply.withMsgHeaderPointer { replyPtr in
mach_exc_server(requestPtr, replyPtr)
} }) != 0 else { throw MachExcServer.code(reply.RetCode) }

handledfirstException = true
} else {
// If multiple fatal errors occur, don't handle subsquent errors (let the program crash)
reply.RetCode = KERN_FAILURE
}

// Send the reply
try kernCheck { reply.withMsgHeaderPointer { replyPtr in
mach_msg(replyPtr, MACH_SEND_MSG, reply.Head.msgh_size, 0, UInt32(MACH_PORT_NULL), 0, UInt32(MACH_PORT_NULL))
Expand All @@ -133,7 +133,7 @@ import Foundation
fatalError("Mach message error: \(error)")
} } while true
}

/// Run the provided block. If a mach "BAD_INSTRUCTION" exception is raised, catch it and return a BadInstructionException (which captures stack information about the throw site, if desired). Otherwise return nil.
/// NOTE: This function is only intended for use in test harnesses – use in a distributed build is almost certainly a bad choice. If a "BAD_INSTRUCTION" exception is raised, the block will be exited before completion via Objective-C exception. The risks associated with an Objective-C exception apply here: most Swift/Objective-C functions are *not* exception-safe. Memory may be leaked and the program will not necessarily be left in a safe state.
/// - parameter block: a function without parameters that will be run
Expand All @@ -150,7 +150,7 @@ import Foundation
pthread_join(handlerThread!, nil)
}
}

try kernCheck {
// 1. Create the mach port
mach_port_allocate(mach_task_self_, MACH_PORT_RIGHT_RECEIVE, &context.currentExceptionPort)
Expand All @@ -159,27 +159,27 @@ import Foundation
// 7. Cleanup the mach port
mach_port_destroy(mach_task_self_, context.currentExceptionPort)
}

try kernCheck {
// 2. Configure the mach port
mach_port_insert_right(mach_task_self_, context.currentExceptionPort, context.currentExceptionPort, MACH_MSG_TYPE_MAKE_SEND)
}

try kernCheck { context.withUnsafeMutablePointers { masksPtr, portsPtr, behaviorsPtr, flavorsPtr in
// 3. Apply the mach port as the handler for this thread
thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, context.currentExceptionPort, Int32(bitPattern: UInt32(EXCEPTION_STATE) | MACH_EXCEPTION_CODES), x86_THREAD_STATE64, masksPtr, &context.count, portsPtr, behaviorsPtr, flavorsPtr)
} }

defer { context.withUnsafeMutablePointers { masksPtr, portsPtr, behaviorsPtr, flavorsPtr in
// 6. Unapply the mach port
_ = thread_swap_exception_ports(mach_thread_self(), EXC_MASK_BAD_INSTRUCTION, 0, EXCEPTION_DEFAULT, THREAD_STATE_NONE, masksPtr, &context.count, portsPtr, behaviorsPtr, flavorsPtr)
} }

try withUnsafeMutablePointer(to: &context) { c throws in
// 4. Create the thread
let e = pthread_create(&handlerThread, nil, machMessageHandler, c)
guard e == 0 else { throw PthreadError.code(e) }

// 5. Run the block
result = BadInstructionException.catchException(in: block)
}
Expand All @@ -191,4 +191,3 @@ import Foundation
}

#endif

Expand Up @@ -34,7 +34,7 @@ import Foundation
// * Plus all of the same caveats as the Mach exceptions version (doesn't play well with other handlers, probably leaks ARC memory, etc)
// Treat it like a loaded shotgun. Don't point it at your face.

private var env = jmp_buf(0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0)
private var env = jmp_buf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

private func triggerLongJmp() {
longjmp(&env.0, 1)
Expand Down Expand Up @@ -72,7 +72,7 @@ public func catchBadInstruction( block: () -> Void) -> BadInstructionException?
var sigActionPrev = sigaction()
let action = __sigaction_u(__sa_sigaction: sigIllHandler)
var sigActionNew = sigaction(__sigaction_u: action, sa_mask: sigset_t(), sa_flags: SA_SIGINFO)

// Install the signal action
if sigaction(SIGILL, &sigActionNew, &sigActionPrev) != 0 {
fatalError("Sigaction error: \(errno)")
Expand All @@ -93,7 +93,7 @@ public func catchBadInstruction( block: () -> Void) -> BadInstructionException?

// Run the block
block()

return nil
}

Expand Down
Expand Up @@ -55,7 +55,7 @@ let EXC_TYPES_COUNT = 14
struct execTypesCountTuple<T: ExpressibleByIntegerLiteral> {
// From /usr/include/mach/i386/exception.h
// #define EXC_TYPES_COUNT 14 /* incl. illegal exception 0 */
var value: (T,T,T,T,T,T,T,T,T,T,T,T,T,T) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
var value: (T, T, T, T, T, T, T, T, T, T, T, T, T, T) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
init() {
}
}
Expand Down
1 change: 0 additions & 1 deletion Sources/Nimble/Adapters/AssertionDispatcher.swift
@@ -1,4 +1,3 @@

/// AssertionDispatcher allows multiple AssertionHandlers to receive
/// assertion messages.
///
Expand Down
2 changes: 1 addition & 1 deletion Sources/Nimble/Adapters/AssertionRecorder.swift
Expand Up @@ -22,7 +22,7 @@ public struct AssertionRecord: CustomStringConvertible {
/// This is useful for testing failure messages for matchers.
///
/// @see AssertionHandler
public class AssertionRecorder : AssertionHandler {
public class AssertionRecorder: AssertionHandler {
/// All the assertions that were captured by this recorder
public var assertions = [AssertionRecord]()

Expand Down
6 changes: 3 additions & 3 deletions Sources/Nimble/Adapters/NMBExpectation.swift
Expand Up @@ -2,7 +2,7 @@ import Foundation

#if _runtime(_ObjC)

internal struct ObjCMatcherWrapper : Matcher {
internal struct ObjCMatcherWrapper: Matcher {
let matcher: NMBMatcher

func matches(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
Expand All @@ -21,7 +21,7 @@ internal struct ObjCMatcherWrapper : Matcher {
}

// Equivalent to Expectation, but for Nimble's Objective-C interface
public class NMBExpectation : NSObject {
public class NMBExpectation: NSObject {
internal let _actualBlock: () -> NSObject!
internal var _negative: Bool
internal let _file: FileString
Expand All @@ -36,7 +36,7 @@ public class NMBExpectation : NSObject {
}

private var expectValue: Expectation<NSObject> {
return expect(_file, line: _line){
return expect(_file, line: _line) {
self._actualBlock() as NSObject?
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Nimble/Adapters/NMBObjCMatcher.swift
Expand Up @@ -5,7 +5,7 @@ import Foundation
public typealias MatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage) -> Bool
public typealias FullMatcherBlock = (_ actualExpression: Expression<NSObject>, _ failureMessage: FailureMessage, _ shouldNotMatch: Bool) -> Bool

public class NMBObjCMatcher : NSObject, NMBMatcher {
public class NMBObjCMatcher: NSObject, NMBMatcher {
let _match: MatcherBlock
let _doesNotMatch: MatcherBlock
let canMatchNil: Bool
Expand Down
5 changes: 2 additions & 3 deletions Sources/Nimble/Adapters/NimbleXCTestHandler.swift
Expand Up @@ -3,7 +3,7 @@ import XCTest

/// Default handler for Nimble. This assertion handler passes failures along to
/// XCTest.
public class NimbleXCTestHandler : AssertionHandler {
public class NimbleXCTestHandler: AssertionHandler {
public func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) {
if !assertion {
recordFailure("\(message.stringValue)\n", location: location)
Expand All @@ -29,7 +29,7 @@ public class NimbleShortXCTestHandler: AssertionHandler {

/// Fallback handler in case XCTest is unavailable. This assertion handler will abort
/// the program if it is invoked.
class NimbleXCTestUnavailableHandler : AssertionHandler {
class NimbleXCTestUnavailableHandler: AssertionHandler {
func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) {
fatalError("XCTest is not available and no custom assertion handler was configured. Aborting.")
}
Expand Down Expand Up @@ -61,7 +61,6 @@ class NimbleXCTestUnavailableHandler : AssertionHandler {
}
#endif


func isXCTestAvailable() -> Bool {
#if _runtime(_ObjC)
// XCTest is weakly linked and so may not be present
Expand Down
15 changes: 5 additions & 10 deletions Sources/Nimble/Expectation.swift
@@ -1,8 +1,7 @@
import Foundation

internal func expressionMatches<T, U>(_ expression: Expression<T>, matcher: U, to: String, description: String?) -> (Bool, FailureMessage)
where U: Matcher, U.ValueType == T
{
where U: Matcher, U.ValueType == T {
let msg = FailureMessage()
msg.userDescription = description
msg.to = to
Expand All @@ -19,8 +18,7 @@ internal func expressionMatches<T, U>(_ expression: Expression<T>, matcher: U, t
}

internal func expressionDoesNotMatch<T, U>(_ expression: Expression<T>, matcher: U, toNot: String, description: String?) -> (Bool, FailureMessage)
where U: Matcher, U.ValueType == T
{
where U: Matcher, U.ValueType == T {
let msg = FailureMessage()
msg.userDescription = description
msg.to = toNot
Expand All @@ -47,16 +45,14 @@ public struct Expectation<T> {

/// Tests the actual value using a matcher to match.
public func to<U>(_ matcher: U, description: String? = nil)
where U: Matcher, U.ValueType == T
{
where U: Matcher, U.ValueType == T {
let (pass, msg) = expressionMatches(expression, matcher: matcher, to: "to", description: description)
verify(pass, msg)
}

/// Tests the actual value using a matcher to not match.
public func toNot<U>(_ matcher: U, description: String? = nil)
where U: Matcher, U.ValueType == T
{
where U: Matcher, U.ValueType == T {
let (pass, msg) = expressionDoesNotMatch(expression, matcher: matcher, toNot: "to not", description: description)
verify(pass, msg)
}
Expand All @@ -65,8 +61,7 @@ public struct Expectation<T> {
///
/// Alias to toNot().
public func notTo<U>(_ matcher: U, description: String? = nil)
where U: Matcher, U.ValueType == T
{
where U: Matcher, U.ValueType == T {
toNot(matcher, description: description)
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/Nimble/FailureMessage.swift
Expand Up @@ -59,7 +59,7 @@ public class FailureMessage: NSObject {
if let userDescription = userDescription {
return "\(userDescription)\n\(value)"
}

return value
}
}

0 comments on commit b08e22a

Please sign in to comment.