Skip to content

interpret/allocation: expose init + write_wildcards on a range #143634

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

nia-e
Copy link
Contributor

@nia-e nia-e commented Jul 8, 2025

Part of rust-lang/miri#4456, so that we can mark down when a foreign access to our memory happened. Should this also move prepare_for_native_access() itself into Miri, given that everything there can be implemented on Miri's side?

r? @RalfJung

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Jul 8, 2025
@rustbot
Copy link
Collaborator

rustbot commented Jul 8, 2025

Some changes occurred to the CTFE / Miri interpreter

cc @rust-lang/miri, @RalfJung, @oli-obk, @lcnr

Copy link
Member

@RalfJung RalfJung left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rustbot author

There's also something missing: either you need an operation that fills uninit bytes with 0 without doing the mark_foreign_write steps, or you need to patch write_uninit to enforce the general invariant that uninit bytes are 0. I think we should do the latter.

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 9, 2025
@rustbot
Copy link
Collaborator

rustbot commented Jul 9, 2025

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@nia-e
Copy link
Contributor Author

nia-e commented Jul 9, 2025

either you need an operation that fills uninit bytes with 0 without doing the mark_foreign_write steps

I think I implemented that in rust-lang/miri#4456 directly in Miri; under call_native_fn():

// Prepare for possible write from native code if mutable.
if info.mutbl.is_mut() {
    let alloc = this.get_alloc_raw_mut(alloc_id)?.0;
    if tracing {
        let full_range =
            AllocRange { start: Size::ZERO, size: Size::from_bytes(alloc.len()) };
        // Overwrite uninitialized bytes with 0, to ensure we don't leak whatever their value happens to be.
        for chunk in alloc.init_mask().clone().range_as_init_chunks(full_range) {
            if !chunk.is_init() {
                let uninit_bytes = unsafe {
                    let start = chunk.range().start.bytes_usize();
                    let len = chunk.range().end.bytes_usize().strict_sub(start);
                    let ptr = alloc.get_bytes_unchecked_raw_mut().add(start);
                    std::slice::from_raw_parts_mut(ptr, len)
                };
                uninit_bytes.fill(0);
            }
        }
    } else {
        // FIXME: Make this take an arg to determine whether it actually
        // writes wildcard prov & marks init, so we don't duplicate code above.
        alloc.prepare_for_native_access();
    }
    // Also expose *mutable* provenance for the interpreter-level allocation.
    std::hint::black_box(alloc.get_bytes_unchecked_raw_mut().expose_provenance());
}

Though there is a FIXME about this, I considered moving prepare_for_native_access() as a whole into Miri and avoiding code duplication that way. Making all uninit bytes be 0 feels like a notable perf hit, no?

@RalfJung
Copy link
Member

RalfJung commented Jul 9, 2025

I think I implemented that in rust-lang/miri#4456 directly in Miri; under call_native_fn():

Please don't. That's just unnecessary code duplication. Also, just because you now can access all these private parts of the allocation from Miri doesn't mean you should.

Making all uninit bytes be 0 feels like a notable perf hit, no?

Indeed, which is why I suggested a way that it can be avoided. :)

@rustbot
Copy link
Collaborator

rustbot commented Jul 9, 2025

The Miri subtree was changed

cc @rust-lang/miri

@nia-e
Copy link
Contributor Author

nia-e commented Jul 9, 2025

Can't test locally but seems to build

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 9, 2025
/// Initialize all previously uninitialized bytes in the entire allocation, and set
/// provenance of everything to `Wildcard`. Before calling this, make sure all
/// Initialize all previously uninitialized bytes in the entire allocation, but
/// do not actually mark them as init. Before calling this, make sure all
/// provenance in this allocation is exposed!
pub fn prepare_for_native_access(&mut self) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought we had agreed that this function should just disappear entirely? I guess I was not clear enough, so here we go:

  • please adjust write_uninit to fill the range with 0s
  • then remove prepare_for_native_access, it is not not needed any more.

Copy link
Contributor Author

@nia-e nia-e Jul 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh! Sorry, I thought you meant the opposite - I was concerned that having write_uninit() write zeroes by default would be a perf hit. But sure, I'll do that if you think it's an okay tradeoff

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, that was the misunderstanding then. :)

write_uninit already does some things that are probably more expensive than writing a few 0s, so I think it's fine.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should mark_init(false) also inherit this behaviour?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a private function... no, it doesn't need to.

@RalfJung
Copy link
Member

RalfJung commented Jul 9, 2025

@rustbot author

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 9, 2025
@nia-e
Copy link
Contributor Author

nia-e commented Jul 9, 2025

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 9, 2025
@rust-log-analyzer

This comment has been minimized.

@RalfJung
Copy link
Member

RalfJung commented Jul 9, 2025

(ignore CI, there was an oopsie and everything is broken)

@RalfJung RalfJung closed this Jul 9, 2025
@rustbot rustbot removed the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jul 9, 2025
@RalfJung RalfJung reopened this Jul 9, 2025
@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jul 9, 2025
@RalfJung RalfJung force-pushed the init-and-wildcards branch from 33a6382 to de15924 Compare July 9, 2025 19:58
@RalfJung
Copy link
Member

RalfJung commented Jul 9, 2025

Thanks!
I did some minor changes, mostly just comment tweaks.

@bors r+ rollup

@bors
Copy link
Collaborator

bors commented Jul 9, 2025

📌 Commit de15924 has been approved by RalfJung

It is now in the queue for this repository.

@nia-e
Copy link
Contributor Author

nia-e commented Jul 9, 2025

...well I can't say I expected that but I'm not complaining!

@RalfJung
Copy link
Member

I don't see a decent way to do this directly; best I can think of is extending Machine with fn uninit_is_zero(&self) -> bool and then using that since every callsite for Allocation::write_uninit() seems to be very close to having / already has an &impl Machine? Not the prettiest solution but I imagine the perf impact might be noticeable in cases relying on large lazily-initialised allocations. Though, I doubt many of those are const...

The Machine trait is not in scope in the file where Allocation is defined so this will not work in a clean way.


I will take this mostly as a null result, this is not that much above the usual noise level.

@oli-obk what do you think? Is it worth preserving the optimization where if you copy a large amount of uninitialized memory somewhere, we avoid actually touching the target memory and filling it with 0s? This was apparently added in #67658. I guess it was added for a reason but we don't have a benchmark for a large uninit array being copied around. Seems like a shame to regress this.

Maybe we should just say that it's entirely fine for native code to see non-0 leftover values in uninit memory. It's uninit after all...

@oli-obk
Copy link
Contributor

oli-obk commented Jul 10, 2025

Maybe we should just say that it's entirely fine for native code to see non-0 leftover values in uninit memory. It's uninit after all...

yes, I think that is the right behaviour. I haven't read the rest of the PR yet, will do so now

@oli-obk
Copy link
Contributor

oli-obk commented Jul 10, 2025

Yea we should just keep the bytes at whatever they were, even if that exposes some non-zero bytes.

@RalfJung
Copy link
Member

@nia-e okay, so can you remove the filling-with-0s, and the comment stating that as an invariant, and add a comment in Miri in the native-lib code saying that yes this exposes whatever bytes happen to be in the "uninitialized" part to the C code but, well, it's uninitialized so it's arbitrary garbage anyway.

(The invariant about there being no provenance on uninit bytes is still true AFAIK. I don't think we need it but it's probably a good invariant to have and it doesn't hurt documenting it.)

@RalfJung
Copy link
Member

@rustbot author

@nia-e nia-e force-pushed the init-and-wildcards branch from 60e7104 to 8d0e0c6 Compare July 10, 2025 14:35
@nia-e
Copy link
Contributor Author

nia-e commented Jul 10, 2025

Force-pushed, hope that's ok given it's tiny?

@nia-e
Copy link
Contributor Author

nia-e commented Jul 10, 2025

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 10, 2025
@RalfJung
Copy link
Member

Looks good, thanks. :)

@bors r+ rollup

@bors
Copy link
Collaborator

bors commented Jul 11, 2025

📌 Commit 8d0e0c6 has been approved by RalfJung

It is now in the queue for this repository.

@bors bors added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 11, 2025
jhpratt added a commit to jhpratt/rust that referenced this pull request Jul 12, 2025
interpret/allocation: expose init + write_wildcards on a range

Part of rust-lang/miri#4456, so that we can mark down when a foreign access to our memory happened. Should this also move `prepare_for_native_access()` itself into Miri, given that everything there can be implemented on Miri's side?

r? `@RalfJung`
bors added a commit that referenced this pull request Jul 12, 2025
Rollup of 15 pull requests

Successful merges:

 - #143554 (slice: Mark `rotate_left`, `rotate_right` unstably const)
 - #143634 (interpret/allocation: expose init + write_wildcards on a range)
 - #143710 (Updates to random number generation APIs)
 - #143774 (constify `From` and `Into`)
 - #143776 (std: move NuttX to use arc4random for random number generation)
 - #143778 (Some const_trait_impl test cleanups)
 - #143782 (Disambiguate between rustc vs std having debug assertions in `run-make-support` and `run-make` tests)
 - #143791 (Update sysinfo version to `0.36.0`)
 - #143796 (Fix ICE for parsed attributes with longer path not handled by CheckAttribute)
 - #143798 (Remove format short command trait)
 - #143803 (New tracking issues for const_ops and const_cmp)
 - #143814 (htmldocck: better error messages for some negative directives)
 - #143817 (Access `wasi_sdk_path` instead of reading environment variable in bootstrap)
 - #143822 (./x test miri: fix cleaning the miri_ui directory)
 - #143823 ([COMPILETEST-UNTANGLE 5/N] Test mode adjustments and other assorted cleanups)

r? `@ghost`
`@rustbot` modify labels: rollup
fmease added a commit to fmease/rust that referenced this pull request Jul 13, 2025
interpret/allocation: expose init + write_wildcards on a range

Part of rust-lang/miri#4456, so that we can mark down when a foreign access to our memory happened. Should this also move `prepare_for_native_access()` itself into Miri, given that everything there can be implemented on Miri's side?

r? ``@RalfJung``
bors added a commit that referenced this pull request Jul 13, 2025
Rollup of 14 pull requests

Successful merges:

 - #143301 (`tests/ui`: A New Order [26/N])
 - #143461 (make `cfg_select` a builtin macro)
 - #143519 (Check assoc consts and tys later like assoc fns)
 - #143554 (slice: Mark `rotate_left`, `rotate_right` unstably const)
 - #143634 (interpret/allocation: expose init + write_wildcards on a range)
 - #143679 (Preserve the .debug_gdb_scripts section)
 - #143685 (Resolve: merge `source_bindings` and `target_bindings` into `bindings`)
 - #143704 (Be a bit more careful around exotic cycles in in the inliner)
 - #143734 (Refactor resolve resolution bindings)
 - #143774 (constify `From` and `Into`)
 - #143785 (Add --compile-time-deps argument for x check)
 - #143786 (Fix fallback for CI_JOB_NAME)
 - #143825 (clippy: fix test filtering when TESTNAME is empty)
 - #143826 (Fix command trace)

r? `@ghost`
`@rustbot` modify labels: rollup
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this pull request Jul 13, 2025
interpret/allocation: expose init + write_wildcards on a range

Part of rust-lang/miri#4456, so that we can mark down when a foreign access to our memory happened. Should this also move `prepare_for_native_access()` itself into Miri, given that everything there can be implemented on Miri's side?

r? ```@RalfJung```
bors added a commit that referenced this pull request Jul 13, 2025
Rollup of 13 pull requests

Successful merges:

 - #143301 (`tests/ui`: A New Order [26/N])
 - #143461 (make `cfg_select` a builtin macro)
 - #143519 (Check assoc consts and tys later like assoc fns)
 - #143554 (slice: Mark `rotate_left`, `rotate_right` unstably const)
 - #143634 (interpret/allocation: expose init + write_wildcards on a range)
 - #143679 (Preserve the .debug_gdb_scripts section)
 - #143685 (Resolve: merge `source_bindings` and `target_bindings` into `bindings`)
 - #143734 (Refactor resolve resolution bindings)
 - #143774 (constify `From` and `Into`)
 - #143785 (Add --compile-time-deps argument for x check)
 - #143786 (Fix fallback for CI_JOB_NAME)
 - #143825 (clippy: fix test filtering when TESTNAME is empty)
 - #143826 (Fix command trace)

r? `@ghost`
`@rustbot` modify labels: rollup
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this pull request Jul 13, 2025
interpret/allocation: expose init + write_wildcards on a range

Part of rust-lang/miri#4456, so that we can mark down when a foreign access to our memory happened. Should this also move `prepare_for_native_access()` itself into Miri, given that everything there can be implemented on Miri's side?

r? ````@RalfJung````
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this pull request Jul 13, 2025
interpret/allocation: expose init + write_wildcards on a range

Part of rust-lang/miri#4456, so that we can mark down when a foreign access to our memory happened. Should this also move `prepare_for_native_access()` itself into Miri, given that everything there can be implemented on Miri's side?

r? `````@RalfJung`````
bors added a commit that referenced this pull request Jul 13, 2025
Rollup of 11 pull requests

Successful merges:

 - #143301 (`tests/ui`: A New Order [26/N])
 - #143519 (Check assoc consts and tys later like assoc fns)
 - #143554 (slice: Mark `rotate_left`, `rotate_right` unstably const)
 - #143634 (interpret/allocation: expose init + write_wildcards on a range)
 - #143685 (Resolve: merge `source_bindings` and `target_bindings` into `bindings`)
 - #143734 (Refactor resolve resolution bindings)
 - #143774 (constify `From` and `Into`)
 - #143785 (Add --compile-time-deps argument for x check)
 - #143786 (Fix fallback for CI_JOB_NAME)
 - #143825 (clippy: fix test filtering when TESTNAME is empty)
 - #143826 (Fix command trace)

r? `@ghost`
`@rustbot` modify labels: rollup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants