Why does pthread_cond_wait return if a breakpoint is set with Xcode 9? - swift

The following swift code should block forever - pthread_cond_wait should never return as no one signals it.
When I run it - it blocks as expected.
If I so much as set a breakpoint using Xcode 9 (9.0.1) the execution continues to the print("hi") line.
Is this a strange Xcode bug or am I doing something totally wrong?
import Foundation
func check(_ ret:Int32){
if ret != 0 {
fatalError("Error \(ret)")
}
}
var cond = pthread_cond_t()
pthread_cond_init(&cond,nil)
var mutex = pthread_mutex_t()
check(pthread_mutex_init(&mutex,nil))
check(pthread_mutex_lock(&mutex))
check(pthread_cond_wait(&cond,&mutex))
print("Hi")
check(pthread_mutex_unlock(&mutex))
Also checked with pthread_cond_timedwait, same behaviour.

pthread_cond_wait can have spurious wakeups. POSIX is very explicit about this:
When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.
It seems that in your environment, running under a debugger makes such wakeups happen, probably due to the extra signals the debugger triggers. It is certainly annoying if a debugger influences application behavior in such a way, but technically, it is not a bug.

Related

Unit test that verifies runtime error is thrown in Swift

Googling has led me to general Swift error handling links, but I have a more specific question. I think the answer here is "no, you're out of luck" but I want to double check to see if I'm missing something. This question from a few years ago seems similar and has some answers with gross looking workarounds... I'm looking to see if the latest version of Swift makes something more elegant possible.
Situation: I have a function which is NOT marked with throws, and uses try!.
Goal: I want to create a unit test which verifies that, yep, giving this function the wrong thing will in fact fail and throw a (runtime/fatal) error.
Problems:
When I wrap this function in a do-catch, the compiler warns me that the catch block is unreachable.
When I run the test and pass in the bad arguments, the do-catch does NOT catch the error.
XCTAssertThrows also does not catch the error.
This function is built to have an identical signature to another, silently failing function, which I swap it out for this one on simulators so that I can loudly fail during testing (either automated or manual). So I can't just change this to a throwing function, because then the other function will have to be marked as throwing and I want it to fail silently.
So, is there a way to throw an unhandled error that I can catch in a unit test?
Alternatively, can I make this function blow up in a testable way without changing the signature?
There is no way to catch non-throwing errors in swift and you mean that by using ! after try.
But you can refactor your code in a way you can have more control from outside of the function like this:
Factor out the throwing function, so you can test it in the right way:
func throwingFunc() throws {
let json = "catch me if you can".data(using: .utf8)!
try JSONDecoder().decode(Int.self, from: json)
}
Write a non-throwing wrapper with a custom error handler:
func nonThrowingFunc( catchHandler:((Error)->Void)? = nil ) {
guard let handler = catchHandler else { return try! throwingFunc() }
do {
try throwingFunc()
} catch {
handler(error)
}
}
So the handler will be called only if you are handling it:
// Test the function and faild the test if needed
nonThrowingFunc { error in
XCTFail(error.localizedDescription)
}
And you have the crashing one:
// Crash the program
nonThrowingFunc()
Note
! (as force) is designed for situations that you are pretty sure about the result. good examples:
Decoding hardcoded or static JSON
Force unwrapping hardcoded values
force try interfaces when you know what is the implementation of it at the point
etc.
If your function is not pure enough and may fail by passing different arguments, you should consider NOT forcing it and refactor your code to a safer version.
Swift (until & including current 5.5) postulates explicitly that all errors inside non-throwing function MUST be handled inside(!). So swift by-design has no public mechanism to intervene in this process and generates run-time error.
You might not even like my answer. But here it goes:
Though I agree that there are plenty of cases where try! is more useful (or event better) than try, I would also argue that they are not meant to be tested because they signify programmer mistakes. A programmer mistake is unplanned. You cannot test something unplanned. If you expect (or suspect) a mistake to happen in production, then you should not be using try! in the first place. To me this is a violation of what I think are standards for programming.
Throwable are added to handle expected mistakes and using try! tells the compiler that you expect a mistake will NEVER happen. For example, when you are parsing a hard-coded value that you know will never fail. So why would you ever need to test a mistake that will never happen?
You can also use an assertionFailure if you want to be rigorous in debug but safe in release.
Runtime errors, like
array index out of bounds
forcibly unwrapping nil values
division by zero
, are considered programming errors, and need precondition checks to reduce the chances they happen in production. The precondition failures are usually caught in the testing phase, as QA people toss the application on all sides, trying to find implementation flaws.
As they are programming errors, you should not need to test them, if indeed the execution of the code reached to a point where the assertion fails, then it means the other code failed to provide valid data. And that's what you should unit test, the other code.
It's best if you avoid the need to have the assertions. !, try!, IOU's, all trap for nil values, so better to avoid these constructs if you're not 100% sure that you'll receive only non-nil values.
A programming error most of the times means that your application reached into an unrecoverable state, and there's little it can be done afterwards, so better let it crash then continue with an invalid state.
Thus, Swift doesn't need to expose an API to handle this kind of scenarios. The existing workarounds, are complicated, fragile, and don't worth to be used in real-life applications.
To conclude:
replace the forced unwraps (try! included) with code that can handle nils, and unit test that, or,
unit test the caller code, since that's the actual problematic code.
The latter case assumes that the forced unwrap usage is legitimate, as the code expects for the callee to be non-nil, so the burden is moved on the other piece of code, the provider of the value that's being forcefully unwrapped.
use Generic Function XCTAssertThrowsError in swift for unit testing
Asserts that an expression throws an error.
func XCTAssertThrowsError<T>(_ expression: #autoclosure () throws -> T, _ message: #autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line, _ errorHandler: (_ error: Error) -> Void = { _ in })
https://developer.apple.com/documentation/xctest/1500795-xctassertthrowserror

Testing Swift code with preconditions

How do you write tests for Swift methods that have preconditions? Here is an example:
func doublePositive(n:Int) -> Int {
precondition(n >= 0)
return 2*n
}
Using XCTAssertThrowsError does not work:
func testDoublePositive() {
XCTAssertEqual(10, testObject.doublePositive(5)) // Works
XCTAssertThrowsError(testObject.doublePositive(-1)) // Breaks
}
This generates an error when running the test:
Thread 1:EXEC_BAD_INSTRUCTION (Code=EXCI386_INVOP, Subcode=0x0)
Is there a way to test preconditions of Swift?
You test Swift methods that have preconditions by only testing behavior with inputs that meet those preconditions. The behavior when the precondition is not met is clear without further testing, since preconditions are baked into the standard library.
If you doubt you've correctly specified a precondition, you can pull out the precondition expression into a Boolean function, then test that for correctly discerning valid from invalid inputs.
However, you can create for yourself what you wish for here:
An option to generate exceptions on precondition/assertion failures would do the trick: one would turn it on in debug builds, and turn it off in release builds.
Instead of calling Apple's precondition, you can write your own function, say, require. This could be conditionally compiled to act as you wish. You would then use this everywhere you'd otherwise be using precondition.

Optionals vs Throwing functions

Consider the following lookup function that I wrote, which is using optionals and optional binding, reports a message if key is not found in the dictionary
func lookUp<T:Equatable>(key:T , dictionary:[T:T]) -> T? {
for i in dictionary.keys {
if i == key{
return dictionary[i]
}
}
return nil
}
let dict = ["JO":"Jordan",
"UAE":"United Arab Emirates",
"USA":"United States Of America"
]
if let a = lookUp( "JO",dictionary:dict ) {
print(a) // prints Jordan
} else {
print("cant find value")
}
I have rewritten the following code, but this time, using error handling, guard statement, removing -> T? and writing an enum which conforms to ErrorType:
enum lookUpErrors : ErrorType {
case noSuchKeyInDictionary
}
func lookUpThrows<T:Equatable>(key:T , dic:[T:T])throws {
for i in dic.keys{
guard i == key else {
throw lookUpErrors.noSuchKeyInDictionary
}
print(dic[i]!)
}
}
do {
try lookUpThrows("UAE" , dic:dict) // prints united arab emirates
}
catch lookUpErrors.noSuchKeyInDictionary{
print("cant find value")
}
Both functions work well but:
which function grants better performance
which function is "safer"
which function is recommended (based on pros and cons)
Performance
The two approaches should have comparable performance. Under the hood they are both doing very similar things: returning a value with a flag that is checked, and only if the flag shows the result is valid, proceeding. With optionals, that flag is the enum (.None vs .Some), with throws that flag is an implicit one that triggers the jump to the catch block.
It's worth noting your two functions don't do the same thing (one returns nil if no key matches, the other throws if the first key doesn’t match).
If performance is critical, then you can write this to run much faster by eliminating the unnecessary key-subscript lookup like so:
func lookUp<T:Equatable>(key:T , dictionary:[T:T]) -> T? {
for (k,v) in dictionary where k == key {
return v
}
return nil
}
and
func lookUpThrows<T:Equatable>(key:T , dictionary:[T:T]) throws -> T {
for (k,v) in dic where k == key {
return v
}
throw lookUpErrors.noSuchKeyInDictionary
}
If you benchmark both of these with valid values in a tight loop, they perform identically. If you benchmark them with invalid values, the optional version performs about twice the speed, so presumably actually throwing has a small bit of overhead. But probably not anything noticeable unless you really are calling this function in a very tight loop and anticipating a lot of failures.
Which is safer?
They're both identically safe. In neither case can you call the function and then accidentally use an invalid result. The compiler forces you to either unwrap the optional, or catch the error.
In both cases, you can bypass the safety checks:
// force-unwrap the optional
let name = lookUp( "JO", dictionary: dict)!
// force-ignore the throw
let name = try! lookUpThrows("JO" , dic:dict)
It really comes down to which style of forcing the caller to handle possible failure is preferable.
Which function is recommended?
While this is more subjective, I think the answer’s pretty clear. You should use the optional one and not the throwing one.
For language style guidance, we need only look at the standard library. Dictionary already has a key-based lookup (which this function duplicates), and it returns an optional.
The big reason optional is a better choice is that in this function, there is only one thing that can go wrong. When nil is returned, it is for one reason only and that is that the key is not present in the dictionary. There is no circumstance where the function needs to indicate which reason of several that it threw, and the reason nil is returned should be completely obvious to the caller.
If on the other hand there were multiple reasons, and maybe the function needs to return an explanation (for example, a function that does a network call, that might fail because of network failure, or because of corrupt data), then an error classifying the failure and maybe including some error text would be a better choice.
The other reason optional is better in this case is that failure might even be expected/common. Errors are more for unusual/unexpected failures. The benefit of returning an optional is it’s very easy to use other optional features to handle it - for example optional chaining (lookUp("JO", dic:dict)?.uppercaseString) or defaulting using nil-coalescing (lookUp("JO", dic:dict) ?? "Team not found"). By contrast, try/catch is a bit of a pain to set up and use, unless the caller really wants "exceptional" error handling i.e. is going to do a bunch of stuff, some of which can fail, but wants to collect that failure handling down at the bottom.
#AirspeedVelocity already has a great answer, but I think it's worth going a bit further into why to use optionals vs errors.
There are basically four ways for something to go wrong:
Simple error: it fails in only one way, so you don't need to care about why something went wrong. The problem may come either from programmer logic or user data, so you need to be able to handle it at run time and design around it when coding.
This is the case for things like initializing an Int from a String (either the string is parseable as an integer or it's not) or dictionary-style lookups (either there's a value for the key or there's not). Optionals work really well for this in Swift.
Logic error: this is the kind of error that (in theory) comes up only during development, as a result of Doing It Wrong — for example, indexing beyond the bounds of an array.
In ObjC, NSException covers these kinds of cases. In Swift, we have functions like fatalError. I'd assume that part of why NSException isn't surfaced in Swift is that once your program encounters a logic error, it's not really safe to assume anything about its further operation. Logic errors should either be caught during development or cause a (nicely debuggable) crash rather than letting the program continue in an undefined (and thus unsafe) state.
Universal error: there are loads of ways to fail, but they aren't very connected to programmer logic or user action. You might run out of memory to allocate, get a low-level interrupt, or (wait for it...) overflow the stack, but those can happen with almost anything you do and not really because of any specific thing you do.
You see universal errors getting surfaced as exceptions in some other languages, but that means that you have to code around the possibility of any and every call you make being able to fail. And at that point you're writing more error handling than you are actual code.
Recoverable error: This is for when there are lots of ways to go wrong, but not in ways that preclude further operation, and what a program does upon encountering an error might change depending on what kind of error it is. Filesystems and networking are the common examples here: if you can't load a file, it might be because the user got the name wrong (so you should tell the user that) or because the wifi momentarily dropped and will be back shortly (so you might forego the alert and just try again).
In Cocoa, historically, this is what NSError parameters are for. Swift's error handling makes this pattern part of the language.
So, when you're writing new API (for yourself or someone else to call) in Swift, or using new ObjC annotations to make an existing API easier to use from Swift, think about what kind of errors you're dealing with.
Is there only one clear way to fail that isn't a result of API misuse? Use an Optional return type.
Can something fail only if a client doesn't follow your API contract — say, if you're writing a container class that has a subscript and a count, or requiring that some specific sequence of calls be made? Don't burden every bit of code that uses your API with error handling or optional unwrapping — just fatalError or assert (or throw NSException if your Swift API is a front to ObjC code) and document what the right way is for people to use your API.
Okay, so your ObjC init method returns nil iff [super init] returns nil. So should you mark your initializer as failable for Swift or add an error out-parpameter? Think about when that really happens — if -[NSObject init] is returning nil, it's because you chained it off of an alloc call that returned nil. If alloc fails, it's already The End Times for your process, so it's not worth handling that case.
Do you have multiple failure cases, some or all of which might be worth reporting to a user? Or that a client calling your API might want to ignore some but not all of? Write a Swift function that throws and a corresponding set of ErrorType values, or an ObjC method that returns an NSError out-parameter.
If you are using Swift 2.0 you could use both versions. The second version uses try/catch (introduced with 2.0) and is thus not backwards compatible which might be a disadvantage to consider.
If there is any performance difference then it will be neglectable.
My personal favorite is the first one as it is straight forward and well readable. If I had to do maintenance of the second version I would ask myself why the author took a try/catch approach for such a simple case. So I would rather be confused...
If you had many complex conditions with many exit points (throws) then I would go for the second one. But as I said, this is not the case here.

return inside a switch block yields "unreachable code" warning

I'm writing UnityScript code and at one point in my program, I want to terminate a function from within a switch block. This is a boiled down version of my code:
function Move(target: int) {
var targetTransform : Transform;
switch (target) {
case 0:
// do something including assigning targetTransform
break;
case 1:
// do something including actually moving my object
return; // since I moved already, I want the function to terminate here
default:
// do something including assigning targetTransform
}
object.Move(targetTransform); // object is locally available
}
Now for whatever reason, the Compiler gives me a
Assets/Scripts/GameMaster.js(490,9): BCW0015: WARNING: Unreachable code detected.
The line is the one containing the switch.
From my previous research, I found many similar problems, but all of them had actually unreachable code, like for example break statements after the returns or a return at the end even though each and every case returned at some point. This is not the case here, I just want one of my cases to return out of the function altogether, while the others shall break out of the switch and go on from there.
Is there a way to get rid of this warning? What is causing it in the first place, is this just a bug?
If at all possible, I'd prefer not to use a boolean and check for it after the switch block... This just seems like overkill only to terminate one case early.
This bug exists at least since 2010. Although it's perfectly legal to use a return statement instead of a break, the compiler will complain about unreachable code.
You have basically two options
ignore the warning and keep your code nice and clean
work around the warning by replacing the return with a boolean + break and check for the boolean after the switch block
As far as I know you can't even disable or suppress the warning. It's possible in C# but UnityScript seems to lack this feature. So this would result in a third possible solution: convert your code to C# :-)

Breaking when a method returns null in the Eclipse debugger

I'm working on an expression evaluator. There is an evaluate() function which is called many times depending on the complexity of the expression processed.
I need to break and investigate when this method returns null. There are many paths and return statements.
It is possible to break on exit method event but I can't find how to put a condition about the value returned.
I got stuck in that frustration too. One can inspect (and write conditions) on named variables, but not on something unnamed like a return value. Here are some ideas (for whoever might be interested):
One could include something like evaluate() == null in the breakpoint's condition. Tests performed (Eclipse 4.4) show that in such a case, the function will be performed again for the breakpoint purposes, but this time with the breakpoint disabled. So you will avoid a stack overflow situation, at least. Whether this would be useful, depends on the nature of the function under consideration - will it return the same value at breakpoint time as at run time? (Some s[a|i]mple code to test:)
class TestBreakpoint {
int counter = 0;
boolean eval() { /* <== breakpoint here, [x]on exit, [x]condition: eval()==false */
System.out.println("Iteration " + ++counter);
return true;
}
public static void main(String[] args) {
TestBreakpoint app = new TestBreakpoint();
System.out.println("STARTED");
app.eval();
System.out.println("STOPPED");
}
}
// RESULTS:
// Normal run: shows 1 iteration of eval()
// Debug run: shows 2 iterations of eval(), no stack overflow, no stop on breakpoint
Another way to make it easier (to potentially do debugging in future) would be to have coding conventions (or personal coding style) that require one to declare a local variable that is set inside the function, and returned only once at the end. E.g.:
public MyType evaluate() {
MyType result = null;
if (conditionA) result = new MyType('A');
else if (conditionB) result = new MyType ('B');
return result;
}
Then you can at least do an exit breakpoint with a condition like result == null. However, I agree that this is unnecessarily verbose for simple functions, is a bit contrary to flow that the language allows, and can only be enforced manually. (Personally, I do use this convention sometimes for more complex functions (the name result 'reserved' just for this use), where it may make things clearer, but not for simple functions. But it's difficult to draw the line; just this morning had to step through a simple function to see which of 3 possible cases was the one fired. For today's complex systems, one wants to avoid stepping.)
Barring the above, you would need to modify your code on a case by case basis as in the previous point for the single function to assign your return value to some variable, which you can test. If some work policy disallows you to make such non-functional changes, one is quite stuck... It is of course also possible that such a rewrite could result in a bug inadvertently being resolved, if the original code was a bit convoluted, so beware of reverting to the original after debugging, only to find that the bug is now back.
You didn't say what language you were working in. If it's Java or C++ you can set a condition on a Method (or Function) breakpoint using the breakpoint properties. Here are images showing both cases.
In the Java example you would unclik Entry and put a check in Exit.
Java Method Breakpoint Properties Dialog
!
C++ Function Breakpoint Properties Dialog
This is not yet supported by the Eclipse debugger and added as an enhancement request. I'd appreciate if you vote for it.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=425744