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

LLVM misoptimization causes segfault #30816

Closed
mahkoh opened this issue Jan 11, 2016 · 2 comments
Closed

LLVM misoptimization causes segfault #30816

mahkoh opened this issue Jan 11, 2016 · 2 comments

Comments

@mahkoh
Copy link
Contributor

mahkoh commented Jan 11, 2016

Consider the following code:

#[no_mangle]
pub unsafe extern fn memset(mut s: *mut u8, c: c_int, n: usize) -> *mut u8 {
    let end = s.add(n);
    let c = c as u8;
    while s != end {
        *s = c;
        s = s.add(1);
    }
    end.sub(n)
}

LLVM misoptimizes this function into an infinite recursion because it recognizes that the inner loop can be replaced by a call to memset. Normally this optimization is disabled inside functions called memset but since the body of the function is moved to a function with rust abi, this check doesn't work.

@rphmeier
Copy link
Contributor

Confirmed here on stable, beta, and nightly using libc 0.2.4. I rewrote your function to use offset instead of "add", along with a relatively minimal test case.

extern crate libc;
#[no_mangle]
pub unsafe extern fn memset(mut s: *mut u8, c: libc::c_int, n: usize) -> *mut u8 {
    let end = s.offset(n as isize);
    let c = c as u8;
    while s != end {
        *s = c;
        s = s.offset(1);
    }
    s
}

fn main() {
    let mut arr = [0u8; 32];
    unsafe { memset(&mut arr[0], 1, arr.len()); }
    assert_eq!(arr, [1u8; 32]);
}

@huonw
Copy link
Member

huonw commented Jan 11, 2016

Dupe of #10116 and #18785, but thanks for filing! You may be interested in the no_builtins attribute (as a work-around until #10116 is fixed).

@huonw huonw closed this as completed Jan 11, 2016
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