Bypassing Kotlin’s Null-Safety

In this short article, we will have a look at how we can bypass Kotlin’s native null-safety with sun.misc.Unsafe, and see why it can be dangerous even if we are not messing up with it directly.

Mythical sun.misc.Unsafe

The sun.misc.Unsafe class is an internal JVM tool for executing low-level operations like off-heap memory allocation, thread parking, CAS, and much more.

This class is like one of those scary computer game creatures that are there only to intimidate us, in theory, we can’t get close because they are part of the environment, but it’s often possible by exploiting glitches or holes.

If we try to access the Unsafe instance, we encounter a private constructor and a static getUnsafe() method that raises a SecurityException practically every time we call it:

public final class Unsafe {
    private static final Unsafe theUnsafe;
    // ...

    private Unsafe() {}

    @CallerSensitive
    public static Unsafe getUnsafe() {
        Class var0 = Reflection.getCallerClass();
        if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
            throw new SecurityException("Unsafe");
        } else {
            return theUnsafe;
        }
    }
}

 

So, in theory, it’s guarded by a strong encapsulation, and an exception being thrown on every getUnsafe() call… but we do have the Reflection mechanism, and we can easily bypass those:

private fun getUnsafe(): Unsafe {
    return Unsafe::class.java.getDeclaredField("theUnsafe")
            .apply { isAccessible = true }
            .let { it.get(null) as Unsafe }
}

Mighty Unsafe.allocateInstance()

This method allocates an empty instance of a given class directly on the heap ignoring field initialization and constructors.

And this allows us, indeed, to effectively bypass Kotlin’s safety checks:

A cool thing to do on Friday’s evening, but what about just not using Unsafe and staying (null)safe?

Problem: Unsafe in External Libraries

The problem is that most Java libraries were written with Java in mind, where using Unsafe for certain scenarios is slightly less unsafe than it is e.g., for Kotlin.

This is especially the case with serialization/deserialization libraries – one of such is Google’s Gson which internally uses Unsafe for instantiating objects in certain situations – which is totally acceptable for Java.

If we start using it in Kotlin, we indeed might end up with an undesired behaviour observed above:

@Test
fun unsafe_2() {
    val foo = Gson().fromJson("{}", Foo::class.java)

    assertThat(foo.nonNullable).isNull()
}

In this case, we simply need to perform checks manually after instantiation, which is not super problematic – what’s problematic is the lack of consciousness that this happens, which can cost much.

Are you sure the library you are using is not doing that internally?

Code snippets can be found on GitHub.

Key Takeaways

  • Kotlin’s null-safety does not go beyond objects’ initialization phase and is bypassable
  • External libraries that use Unsafe internally can do that too – it’s important to be aware of this
You May Also Like

Custom SonarQube rules for Unit Tests

It's a tutorial about creating new rules for SonarQube analysis to be applied to Unit Tests. It is not trivial and involves a few tricky database steps, so I want to share my tutorial about it.It's a tutorial about creating new rules for SonarQube analysis to be applied to Unit Tests. It is not trivial and involves a few tricky database steps, so I want to share my tutorial about it.

GWT Hosted mode on 64bit linux

GWT for linux is build against 32bit architecture. It contains some SWT/GTK 32bit modules. So if you try to run it with 64bit java it failsException in thread "main" java.lang.UnsatisfiedLinkError: /opt/tools/sdk/gwt/gwt-linux-1.5.3/libswt-pi-gtk-3235....

Grails render as JSON catch

One of a reasons your controller doesn't render a proper response in JSON format might be wrong package name that you use. It is easy to overlook. Import are on top of a file, you look at your code and everything seems to be fine. Except response is still not in JSON format.

Consider this simple controller:

class RestJsonCatchController {
def grailsJson() {
render([first: 'foo', second: 5] as grails.converters.JSON)
}

def netSfJson() {
render([first: 'foo', second: 5] as net.sf.json.JSON)
}
}

And now, with finger crossed... We have a winner!

$ curl localhost:8080/example/restJsonCatch/grailsJson
{"first":"foo","second":5}
$ curl localhost:8080/example/restJsonCatch/netSfJson
{first=foo, second=5}

As you can see only grails.converters.JSON converts your response to JSON format. There is no such converter for net.sf.json.JSON, so Grails has no converter to apply and it renders Map normally.

Conclusion: always carefully look at your imports if you're working with JSON in Grails!

Edit: Burt suggested that this is a bug. I've submitted JIRA issue here: GRAILS-9622 render as class that is not a codec should throw exception