Thursday, September 19, 2013

How to kill Java with a Regular Expression

We recently stumbled upon a phenomen we absolutely weren't aware of: You can kill any Java IDE and also any Java process with a simple regular expression...

Back in university, I was taught that regular expressions, which are called regular grammers or type 3 grammers always end up in an finite state automaton and can therefore be processed in linear time (input length doubles, processing time doubles). However, that's only true for "sane" expressions. A regular expression can also result in an non-deterministic finite state automaton and things can get messed up quite bad.

Consider the expression: (0*)*A This will any number of zeros, followed by an upper case A. Now if you use Matcher.find() for this expression, everything is fine as long as there is a match in the input. However, if you call this, with "00000000000000000000" as input, your program will hang (and so will the regex console in Eclipse or IntelliJ and every (Java-based) online regex service).

What at first glance looks like an infinite loop, truns out to be catastrophic backtracking. What this basically means is, that the matcher detects, that no A was found at the end of the input. Now the outer quantifier goes on step back - the inner one forward and again - no result. Therefore the matcher goes back step by step retrying all combinations to find a match. It will eventually return (without a match) but the complexity (and therefore the runtime) of this is expotential (adding one character to the input doubles the runtime). A detailed description can be found here: catastrophic backtracking

Here are some runtimes I measured (which almost exactly double for each character added):0000000000: 0.1ms00000000000: 0.2ms000000000000: 0.7ms0000000000000: 1.3ms00000000000000: 1.7ms000000000000000: 3.5ms0000000000000000: 7.2ms00000000000000000: 13.9ms000000000000000000: 27.5ms0000000000000000000: 55.5ms00000000000000000000: 113.0ms000000000000000000000: 226.4ms0000000000000000000000: 439.1ms00000000000000000000000: 886.0ms
As a little side-note: For micro benchmarks like this, you always need to "warm" up the JVM as the HotSpot JIT will jump in at some point and optimize the code. Therefore the first run looks like this:

So what's the take-away here? If you're running a server application or anything critical used by many users, don't let them enter regular expressions unless you really trust them. There are regex implementations out there, which detect this problem and abort, but Java (up to JDK 8) doesn't.

Note:You can test this with your local IDE or a small Java program to your hearts content - but please don't start to knock out all the regex tester websites out there. Those guys provide a nice tool free of charge, so it would be quite unfair..