Thursday, March 6, 2014

Goto fail;

Apple recently faced a security issue and provided a patch to fix it: About the security content of iOS 7.0.6
A web site is also available to check if your current OS must be updated: https://gotofail.com/

An interesting analysis of this - what appears to be - bug can be found in this article but please note that I am not sharing the point of view expressed in the conclusion.
I mean, whatever the way, bugs happen.
To make a long story short, it looks like a bad copy & paste duplicated a "goto fail;" instruction which, in the end, has no condition and is always evaluated.

As I recently talked about the advantages of using a lint-tool, I wanted to check if JShint would be capable of detecting this issue.
However - and fortunately - goto does not exist in JavaScript.

There are several ways to reproduce the same effect than a 'goto' instruction:

I usually embrace my if statements with brackets, I wanted to make my samples look similar to the initial problem and check how JSHint would react.
  • First example, the one-time do / while with break
  • function main(parameter) { var success = false; do { if (parameter === "condition1") break; if (parameter === "condition2") break; break; success = true; } while(0); if (success) { alert("Do"); } else { alert("Don't"); } } main("condition3"); JSHint produces a warning: 10 Unreachable 'success' after 'break'.
  • Second example, return in a separate function
  • function testCondition(parameter) { if (parameter === "condition1") return false; if (parameter === "condition2") return false; return false; return true; } function main(parameter) { if (testCondition(parameter)) { alert("Do"); } else { alert("Don't"); } } main("condition3"); JSHint produces a warning: 7 Unreachable 'return' after 'return'.
  • Last example, exceptions
  • function main(parameter) { try { if (parameter === "condition1") throw "fail"; if (parameter === "condition2") throw "fail"; throw "fail"; alert("Do"); } catch (e) { alert("Don't"); } } main("condition3"); JSHint produces a warning: 8 Unreachable 'alert' after 'throw'.

To conclude, JShint is capable of detecting an unreachable code and generates the appropriate warning.
It also means that all the warnings are meaningful and should be carefully considered.

If you want to check by yourself, go to http://www.jshint.com/ and copy & paste the samples directly where the JavaScript sample is written (upper left part of the homepage).