Optimizing the size of your Rust binaries

By default, Rust produces fairly large binaries, which may be annoying when building a RAT. A larger executable means more resources used on the system, longer and less reliable downloads, and easier to be detected.

We will see a few tips to reduce the size of a Rust executable.

Note that each of the following points may come with drawbacks, so you are free to mix them according to your own needs.

This post is an excerpt from my course Black Hat Rust

Optimization Level

In Cargo.toml

opt-level = 'z' # Optimize for size

In Cargo.toml

lto = true

Parallel Code Generation Units

In Cargo.toml

codegen-units = 1

Note that those techniques may slow down the compilation, especially Parallel Code Generation Units. In return, the compiler will be able to better optimize your binary.

Choosing the right crates

Finally, choosing small crates can have the biggest impact on the size of the final executable. You can use cargo-bloat to find which crates are bloating your project and thus find alternatives, as we did for the agent's HTTP client library.

1 email / week to learn how to (ab)use technology for fun & profit: Programming, Hacking & Entrepreneurship.
I hate spam even more than you do. I'll never share your email, and you can unsubscribe at any time.

Tags: hacking, programming, rust, tutorial

Want to learn Rust, Cryptography and Security? Get my book Black Hat Rust!