Monthly Archives: July 2024

Dlang PSA: Don’t use -release

Don’t use the -release command line switch for the D compiler.

Why? Because it removes bounds checks from arrays in @system code. Why is this a problem? It is a problem because the #1 problem with all exploits in the world is buffer overflows — writing or reading data that you are not supposed to have access to.

In other words, if you have a bug in your code where you don’t validate your array usage is within bounds, then bound checks will prevent a catastrophic error, or an exploit. If you are lucky, you get a segmentation fault that crashes your program.

Note that -release doesn’t even optimize the code! You still need to use -O -inline to get maximum performance. If you are feeling a bit adventurous, you might use -check=assert=off, but that’s only if you really have expensive asserts that are causing performance problems. Even then, I might look into selectively compiling some modules with asserts off to achieve the desired performance.

In general, turning off safety checks is only crucial for performance critical code. It should not be project-wide. And for bounds checks? You can easily omit bounds checks in @system code by using the .ptr[index] mechanism.

What about dub?

For those who use dub, you can actually override the release build option. Here is how I do it (dub.json format):

"buildTypes": {
    "release": {
        "buildOptions": [
            "inline",
            "optimize"
        ]
    }
}

This means, when you type dub -b release you won’t accidentally remove the most important checks present in your code.

But I want my code to be the fastest ever!!!

No, you don’t. You don’t care if it takes 200ms vs 250ms. Trust me. Just don’t do it.

Here is a case where D beat pretty much all the competition, and never turned off bounds checks: https://github.com/jinyus/related_post_gen