Return value write exceeds 4kb in single pass

Hello, I was playing with some code and came across this case case where Zig performs a return value write exceeding 4KB in a single pass. However, based on what I have read in Google, it is said that performing this return value writes larger than 4KB in a single pass is a violation, because the OS places a guard page at every 4KB boundary, that makes the write skip over it and inadvertently override other memory that it doesn’t has permission to be there yet. Is this true?

Or it is safe because no read/write happens there, just jump first, then the write happens sequentially via memset that would touch the guard page?

The code

const BigData = struct {
    bytes: [1024 * 1024]u8,
};

noinline fn returnArray(val: u8) BigData {
    var data: BigData = undefined;
    @memset(&data.bytes, val);
    return data;
}

export fn caller(val: u8) usize {
    const my_data = returnArray(val);
    return my_data.bytes[0];
}
example.caller:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 1048576
        mov     esi, edi
        lea     rdi, [rbp - 1048576]
        call    example.returnArray
        movzx   eax, byte ptr [rbp - 1048576]
        add     rsp, 1048576
        pop     rbp
        ret

example.returnArray:
        push    rbp
        mov     rbp, rsp
        mov     edx, 1048576
        pop     rbp
        jmp     memset@PLT

caller = example.caller

if it’s a violation, it should crash when you run it. does it?

It has no crash when I run it. However, is it guaranted a crash, or could it be silent?

Ouuuuu finally it crashhhhhh

The reason it didn’t crash earlier because I built it in ReleaseFast mode. Building it in debug mode then trigger the code to be run crash it like this

[dev@localhost zig]# ./zig-out/bin/zig
=== Test 1: Basic call ===
caller(42) = 42
=== Test 2: Recursive (depth=50) ===
Segmentation fault at address 0x7fd7c6a058
/root/zig/src/main.zig:18: 0x114d2c0 in recursive (zig)
fn recursive(depth: usize, val: u8) void {

/root/zig/src/main.zig:24:14: 0x114d36b in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:24:14: 0x114d36b in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:24:14: 0x114d36b in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:24:14: 0x114d36b in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:24:14: 0x114d36b in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:24:14: 0x114d36b in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:24:14: 0x114d36b in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:35:14: 0x114d193 in main (zig)
    recursive(200, 55);
             ^
/root/system/zig/zig-aarch64-linux-0.16.0/lib/std/start.zig:698:59: 0x114cdff in callMain (zig)
    if (fn_info.params.len == 0) return wrapMain(root.main());
                                                          ^
Aborted                    ./zig-out/bin/zig
[dev@localhost zig]#

So ReleaseFast makes it just silent

Will there a next step to prevent that from happening?

If you want to make this work, you have essentially two choices

  1. Rewrite it to use heap allocation (i.e. take Allocator arg and return *BigData).
  2. Perform a ‘stack-probe’ at the start of caller().

Option 1 is by far the better choice. Also, you can later retrofit it to use stack allocation by passing it a std.heap.FixedBufferAllocator.

If you really want to do stack probes though, there’s some good posts on oldnewthing that cover how it works:

And just for fun, an example of how stack probes can go wrong:

1 Like

I was just playing with random code, not fixing a project code :v. Yeah using heap would not touch big stack, it also faster because only copy pointer and metadata

The blogs are really nice, really good easy to understand explanations

Is there a roadmap in Zig to prevent that code ship? I mean we are human, sometimes it slip unnoticed, it would be great if Zig already handle this

@vincentd If I don’t call it resursively it doesn’t crash in debug build. Eg I just call it 2x sequentially. Does it means it is safe if called that way, or just it would crash later at much much down later like the blog post says?

In many ways, Optimize.safe (née OptimizeMode.ReleaseSafe), is the default mode for release/testing/fuzzing. It should catch what debug mode catches while providing reasonable performance on most platform. Measure and see if it’s worth it (i.e. the tradeoff between undefined behavior and speed and/or executable size).

This is probably because prior to main Zig expands the stack so the limit is just larger.

I would expect LLVM to optimise this to write to the callers stack instead of duping a large array, and that appears to be the case in the assembly you included, though I could wrong.

1 Like

I just tested with ReleaseSafe, it is same a silent Undefined Behaviour because no crash is triggered, where switching to debug build restore the crash. So it is only caught in debug build currently. It would be good if ReleaseSafe caught it, because sometimes we are just not sure with the state of quality of the current code and ship ReleaseSafe for confidence when deploying

Yeah, LLVM already changes it to write directly to the caller stack. The problem that I understand is the way how it is done, it doesn’t trigger the OS guard page to make the OS map next memory page

Another thing you might be running into is that the OS will impose a limit on the stack size beyond which it will not grow. 8 MB by default, on linux at least. That corresponds pretty well to the error you got (8x calls of 1 MB each). You can increase this limit with a syscall.

It’s probably optimising away the recursive calls, turning it into a flat loop or just removing it outright (if the result is never used). ReleaseSafe optimises, Debug does not.

Using @call with never_tail might help: Documentation - The Zig Programming Language

Yeah that could be, I remembered that 8 MB default size. Now I’m confused is it because the no stack probing or 8 MB limit? Do you know which one exactly?

The release mode doesn’t optimize out the loop, I just placed println there to see it. Here is the result

[dev@localhost zig]# ./zig-out/bin/zig
=== Test 1: Basic call ===
caller(42) = 42
=== Test 2: Recursive (depth=50) ===
depth: 200
depth: 199
depth: 198
depth: 197
depth: 196
depth: 195
depth: 194
depth: 193
depth: 192
depth: 191
depth: 190
depth: 189
depth: 188
depth: 187
Segmentation fault at address 0x7fcba784e0
/root/system/zig/zig-aarch64-linux-0.16.0/lib/std/Io/Threaded.zig:13787: 0x1059da8 in lockStderr (zig)
fn lockStderr(userdata: ?*anyopaque, terminal_mode: ?Io.Terminal.Mode) Io.Cancelable!Io.LockedStderr {

/root/system/zig/zig-aarch64-linux-0.16.0/lib/std/Io.zig:2440:40: 0x1067d07 in lockStderr (zig)
    const ls = try io.vtable.lockStderr(io.userdata, terminal_mode);
                                       ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:25:14: 0x1067e6f in recursive (zig)
    recursive(depth - 1, val);
             ^
/root/zig/src/main.zig:36:14: 0x10679bf in main (zig)
    recursive(200, 55);
             ^
/root/system/zig/zig-aarch64-linux-0.16.0/lib/std/start.zig:698:59: 0x1022caf in callMain (zig)
    if (fn_info.params.len == 0) return wrapMain(root.main());
                                                          ^
Aborted                    ./zig-out/bin/zig
[dev@localhost zig]#

The println “depth: number” is printed repeately before the crash happened, meaning the recursive call is there

By the pattern of the output, the println output success 15x, the data is 1 MB, so it kinda at the 8x it already violates the stack, then it continue silently overwriting whatever next memory there until 7x then crash. It kinda suggest the cause is the normal Linux stack limit, but I’m also not so sure

Due to you putting the print there it’s definitely not optimized out.

You can’t really check something like this in this way. The best way is to simply look at the assembly.

Memset touches every byte in order, so it substitutes a stack check.

It crashed because you did a huge recursion.

Also, you don’t have to stack check. You could simply not use reserved stack space. That is, commit all the space you’re going to need. This should be the default everywhere now, but it isn’t. Stack space today is a drop in the ocean of memory a computer has. It’s a waste of time handling the segfaults and calling the stack check function. If a function with stack check is called in a loop, you’re going to run the check every time, even though only the first time actually did something.
You could also have the caller allocate enough space for the return value, and then they would have to do the checking.

1 Like

Yeah, I just found it out. The println has side effect printing to terminal, could that side effect is the one that prevent the resursive being removed?

I retested it with the update, now in all release mode consistently crash not silent

In case my question is misunderstood, I wanted to ask the

mov edx, 1048576

Since that happened before the memset and that 1048576 is 1 MB. So did you meant that just doing that alone is safe?

A bit correction if I’m not wrong, the specific cause is stack memory limit touched, that could happen even without recursion, so recursion is not neccerery the needs, but anything that exhaus the 8 MB limit in Linux

I wonder could it be prevented using comptime machinery, could the limit size of stack is fetched at compile time then size the allocation size for stack is known at compile time, thus a compile time if else check could be done?

There is some confusion in this thread. Linux and windows use “guard pages” differently, so the microsoft blog links are not applicable to linux. Linux OSes often default to a stack limit of 8MB, but that doesn’t mean that’s what will definitely be the stack size of the process. E.g. uname -s gives me 8192 (8MB), but with a test zig program I get try std.posix.getrlimit(std.posix.rlimit_resource.STACK) 16384 (16MB). “it kinda at the 8x it already violates the stack” will not happen: the process has access to some pages. The ranges are not next to each other, e.g. on my system with cat /proc/$PID/maps the stack start is 128MB away from the next range [vdso], so you’d need to bridge that gap (and iirc that range is read only). Also just guessing how much stack you use in your experiments is not a good strategy, e.g. the caller allocates BigData as a return value on the stack and the callee might allocate another BigData on the stack for it’s own use and then copy it into the caller’s frame, so you used 2x BigData space. Especially with throwing recursion into this experimentation mix, you’ll just cause more headache. Finally, if you look at the disassembly, you’ll even see a call to __zig_probe_stack, so it’s all taken care of:

compiler_rt/stack_probe.zig:40
// Versions of the Linux kernel before 5.1 treat any access below SP as
// invalid so let's update it on the go, otherwise we'll get a segfault
// instead of triggering the stack growth.

More generally “read in Google, it is said that performing this return value writes larger than 4KB in a single pass is a violation”, would be nice to get a source, because without context this doesn’t argue for anything. If you write assembly on windows (or linux before 5.1 as the comment), yeah, this might be sound advice. If you use any programming language, it’s taken care of by the compiler.

1 Like

The source that makes me wrote the title like that are many included I also asked AI. Its all said that the guard page sit at each 4kb, writing > 4kb directly that skip touching the guard page violates it