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

Identifier::new_unchecked() writes to null pointer on allocation failure #290

Closed
LegionMammal978 opened this issue Sep 15, 2022 · 2 comments · Fixed by #291
Closed

Identifier::new_unchecked() writes to null pointer on allocation failure #290

LegionMammal978 opened this issue Sep 15, 2022 · 2 comments · Fixed by #291

Comments

@LegionMammal978
Copy link

Identifier::new_unchecked() calls alloc::alloc::alloc() to create a buffer on the heap if the string is 9 bytes or longer. However, if the global allocator fails and returns a null pointer, the function attempts to write to it, resulting in a segmentation fault.

/*
[dependencies]
semver = "=1.0.13"
*/

use semver::Version;
use std::{
    alloc::{GlobalAlloc, Layout, System},
    ptr,
    sync::atomic::{AtomicBool, Ordering},
};

struct ToggleAlloc(AtomicBool);

#[global_allocator]
static ALLOC: ToggleAlloc = ToggleAlloc(AtomicBool::new(true));

// SAFETY: Wraps `System`'s methods, possibly indicating failure.
unsafe impl GlobalAlloc for ToggleAlloc {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        if self.0.load(Ordering::Relaxed) {
            System.alloc(layout)
        } else {
            ptr::null_mut()
        }
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        System.dealloc(ptr, layout)
    }
}

fn main() {
    ALLOC.0.store(false, Ordering::Relaxed);
    "0.0.0-100000000".parse::<Version>().unwrap(); // Segmentation fault
}
@dtolnay
Copy link
Owner

dtolnay commented Sep 15, 2022

Good catch! I've published a fix in 1.0.14.

@dtolnay
Copy link
Owner

dtolnay commented Sep 15, 2022

Before:

Segmentation fault (core dumped)

After:

memory allocation of 10 bytes failed
Aborted (core dumped)

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

Successfully merging a pull request may close this issue.

2 participants