Skip to content

Can uninitialized memory come from the outside world? #527

@ChayimFriedman2

Description

@ChayimFriedman2

For example, suppose we have the following C function:

int* get_uninit() {
    return malloc(sizeof(int));
}

Which we call from Rust:

extern "C" {
    fn get_uninit() -> *mut c_int;
}

let v = *get_uninit();

Is this code UB? We don't initialize the value, but it comes from C, not Rust.

It's pretty clear for me that this needs to be UB, since (I believe) LLVM will optimize that with LTO. But then, what about cases where LLVM will not optimize? For example, what about assembly?

get_uninit:
    mov rax, rsp

We don't initialize the value of [rsp], but LLVM has no way to know that: is it UB?

Furthermore, if it is UB, then we have to define what is considered "initialization": if we are sure we called a function that used the stack space of [rsp], does that mean it is initialized? And what if assembly code wrote into it?

After all (assuming the memory is allocated to the process, so no page faults), at the machine level there is no concept of uninitialized memory. So this brings the question, what happens when the machine and the Rust AM intersect?

Inspired by a question on Reddit.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions