Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: local array clobbered by PRNG call? #8889

Closed
david-vanderson opened this issue May 24, 2021 · 2 comments
Closed

Bug: local array clobbered by PRNG call? #8889

david-vanderson opened this issue May 24, 2021 · 2 comments
Milestone

Comments

@david-vanderson
Copy link
Contributor

This reproduces for me on zig-macos-x86_64-0.8.0-dev.2641+55811d8da but seems quite sensitive to rearranging statements. I looked at the assembly for a while but it's my first time trying to debug something like this. Any help or pointers would be appreciated. Can anyone reproduce this?

const std = @import( "std" );

pub fn main( ) void {
    // Problem only happens with Xoroshira128, not other PRNGs
    // Problem happens regardless of PRNG seed
    var g = std.rand.Xoroshiro128.init( 0 ).random;

    // Problem happens with some array sizes but not others
    var array = [_]i32 { 0, 0 };

    // Prints "0x0, 0x0"
    std.debug.print( "before: 0x{x}, 0x{x}\n", .{ array[0], array[1] } );

    // Problem happens regardless of what PRNG call we make here
    var x = g.int( i32 );

    // Prints garbage
    std.debug.print( " after: 0x{x}, 0x{x}\n", .{ array[0], array[1] } );
}
@SpexGuy
Copy link
Contributor

SpexGuy commented May 24, 2021

var g = std.rand.Xoroshiro128.init( 0 ).random;

This line "truncates" the random interface, creating a copy of the vtable but not the extra data needed for the implementation. When you call g.int() it tries to get the extended data relative to g, which accesses stack memory that in this case happens to overlap with array.

The recommended way to write this to avoid truncation is

var rand_impl = std.rand.Xoroshiro128.init( 0 );
const rand = &rand_impl.random;

Once implemented, pinned structs (#7769) will make this mistake a compile error.

@david-vanderson
Copy link
Contributor Author

Ahhh - Thank you!

stacktracer added a commit to stacktracer/sproingy that referenced this issue May 27, 2021
@andrewrk andrewrk added this to the 0.8.0 milestone Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants