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.1ms
00000000000: 0.2ms
000000000000: 0.7ms
0000000000000: 1.3ms
00000000000000: 1.7ms
000000000000000: 3.5ms
0000000000000000: 7.2ms
00000000000000000: 13.9ms
000000000000000000: 27.5ms
0000000000000000000: 55.5ms
00000000000000000000: 113.0ms
000000000000000000000: 226.4ms
0000000000000000000000: 439.1ms
00000000000000000000000: 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:

0000000000: 6.8ms
00000000000: 11.8ms
000000000000: 25.5ms
0000000000000: 39.5ms
00000000000000: 6.3ms   <- JIT jumped in and started to translate
000000000000000: 5.4ms     to native code.
0000000000000000: 7.1ms
00000000000000000: 14.2ms
000000000000000000: 26.8ms
0000000000000000000: 54.4ms
00000000000000000000: 109.6ms
000000000000000000000: 222.1ms
0000000000000000000000: 439.2ms
00000000000000000000000: 885.6ms

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..

Here is the tiny benchmark I used:

public class Test {
    public static void main(String[] args) {
        for (int runs = 0; runs < 2; runs++) {
            Pattern pattern = Pattern.compile("(0*)*A");
            // Run from 5 to 25 characters
            for (int length = 5; length < 25; length++) {
                // Build input of specified length
                String input = "";
                for (int i = 0; i < length; i++) { input += "0"; }
               
                // Measure the average duration of two calls... 
                long start = System.nanoTime();
                for (int i = 0; i < 2; i++) {
                    pattern.matcher(input).find();
                }
                System.out.println(input + ": " 
                       + ((System.nanoTime() - start) / 2000000d) 
                       + "ms");
            }
        }
    }
} 

 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

4 Responses to "How to kill Java with a Regular Expression"

  1. - says:

    fyi: http://madbean.com/2004/mb2004-20/

    another Java Regex “feature” ;)

  2. Yes, this is known problem with anything that can be treated like “program code”. And the RegEx pattern literal certanly is. But

    A) IntelliJ IDEA won’t hang on this – and most likely on any – regular expression used in its “find”. And not because of multithreading or something. We just won’t let the evaluating thread to hang.

    B) There is a totally generic solution that allows this – if you think of the problem root.

    The problem root is that you loosing execution control whenever you invoke any lib function. And the more complex its code is the more likely you can get unexpected behaviour on arbitrary input.
    Most likely (and its true for java regex lib) the only point where you can still easily control this 3rd party code is the access to the input data.

    In this case wrapping input in custom delegating CharSequence will allow you to abort the execution based on execution timing or any other condition.

  3. Iulian says:

    I agree with the take-away and I think it fits in the more general approach of not “trusting” any user input.

    Looking at the benchmark code, the issue there is mainly the use of greedy quantifiers. Using possessive quantifiers could prevent this behavior: http://docs.oracle.com/javase/tutorial/essential/regex/quant.html

  4. Seth says:

    Hey Andreas, This is very interesting. Thanks a lot for sharing it and it’s a good thing you mentioned about not testing this code online.

Leave a Reply


2 × = six



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close