How to Increase Rust's Stack Size on macOS

TLDR; here’s the command I use to increase the default Rust stack size on macOS.

rustc -C 'link-args=-Wl,-stack_size,0x80000000'  // 2 GB stack size

This command will compile the source file using a stack size of 2 GB (0x80000000 = 2147483648 bytes = 2 GB). If you’re interested in what these flags mean, or how I arrived at this, feel free to read on.

I recently ran into the following runtime error while coding in Rust:

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
Abort trap: 6

Usually when you hit a stack overflow error it is due to some sort of infinite recursion. I hit this error while trying to implement a backtracking solution for an Advent of Code problem I had been working on. I was able to verify that my code wouldn’t recurse forever, and implementing the solution using an iterative approach would’ve been time consuming and difficult. So I figured I would just increase the stack size and call it a day.

Figuring out how to do this on my system wasn’t as straight forward as I expected it to be. Most of the online examples I saw were for Linux machines, like in this post. On Linux, to handle C dependencies, Rust will invoke a C compiler, usually gcc. On macOS, however, it will use clang, which needs different flags for correctly setting the linker args.

In the aforementioned post, they suggest to use the following to set the stack size.

rustc -C link-args=-Wl,-zstack-size=4194304

This doesn’t work on macOS. After doing some digging it looked like I just needed to get the linker args passed correctly. Here is the clang man page docs for -Wl.

              Pass the comma separated arguments in args to the linker.

This led me to check the ld man page, which clang uses as its linker. Here we can find out more about the -stack_size flag.

     -stack_size size
                 Specifies the maximum stack size for the main thread in a program.  With-
                 out this option a program has a 8MB stack.  The argument size is a hexa-
                 decimal number with an optional leading 0x. The size should be a multiple
                 of the architecture's page size (4KB or 16KB).

This is what gives us the following command to set the Rust stack size at compile time.

rustc -C 'link-args=-Wl,-stack_size,0x80000000'  // 2 GB stack size

To verify this works you can use otool to see what the stack size is set to.

rustc -C 'link-args=-Wl,-stack_size,0x80000000'
otool -lV ./code | grep stack
stacksize 2147483648

On a strange note, when compiling without these options otool says the stack size is 0. I’m not sure why this is…

otool -lV ./code | grep stack
stacksize 0

I’m hoping this post will be a good reference, and/or helpful to anyone who also hits this issue. Happy coding!