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.

@RalfJung
Copy link
Member

RalfJung commented Jul 9, 2025

Oh, damn...

if init.no_bytes_init() {
// Fast path: If all bytes are `uninit` then there is nothing to copy. The target range
// is marked as uninitialized but we otherwise omit changing the byte representation which may
// be arbitrary for uninitialized bytes.
// This also avoids writing to the target bytes so that the backing allocation is never
// touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary
// operating system this can avoid physically allocating the page.
dest_alloc
.write_uninit(&tcx, dest_range)
.map_err(|e| e.to_interp_error(dest_alloc_id))?;
// We can forget about the provenance, this is all not initialized anyway.
return interp_ok(());
}

@bors r-

I am not sure what to do about that. The comment there explicitly says we do not want to write a bunch of 0s into the buffer, which is exactly what we are doing now.

@bors bors 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-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. labels Jul 9, 2025
@RalfJung RalfJung force-pushed the init-and-wildcards branch from de15924 to 60e7104 Compare July 9, 2025 20:17
@rustbot
Copy link
Collaborator

rustbot commented Jul 9, 2025

Some changes occurred to the CTFE / Miri interpreter

cc @rust-lang/miri

Some changes occurred to the CTFE machinery

cc @RalfJung, @oli-obk, @lcnr

@RalfJung
Copy link
Member

RalfJung commented Jul 9, 2025

Let's see if we see this in perf.

@bors2 try
@rust-timer queue

@rust-timer

This comment has been minimized.

@rust-bors
Copy link

rust-bors bot commented Jul 9, 2025

⌛ Trying commit 60e7104 with merge e6c1026

To cancel the try build, run the command @bors2 try cancel.

rust-bors bot added a commit that referenced this pull request Jul 9, 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`
@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Jul 9, 2025
@nia-e
Copy link
Contributor Author

nia-e commented Jul 9, 2025

Why not just gate the zero write behind some condition (e.g. being in Miri proper and not the CTFE machine)? Seems like that function gets an &InterpCx, is that condition somehow testable?

@nia-e
Copy link
Contributor Author

nia-e commented Jul 9, 2025

Actually it seems like only Miri sets OFFSET_IS_ADDR = true so maybe just test against that. It's flaky, sure, but it's a performance and not correctness thing so hopefully ok?

@RalfJung
Copy link
Member

RalfJung commented Jul 9, 2025

Even Miri only needs this if native-lib mode is enabled...

@nia-e
Copy link
Contributor Author

nia-e commented Jul 9, 2025

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...

@rust-bors
Copy link

rust-bors bot commented Jul 9, 2025

☀️ Try build successful (CI)
Build commit: e6c1026 (e6c1026ff3aca3b225ff96c082dbe923ef8d4761, parent: e3fccdd4a16bf3aa223749efef1fa981589e43ae)

@rust-timer

This comment has been minimized.

@rust-timer
Copy link
Collaborator

Finished benchmarking commit (e6c1026): comparison URL.

Overall result: ✅ improvements - no action needed

Benchmarking this pull request means it may be perf-sensitive – we'll automatically label it not fit for rolling up. You can override this, but we strongly advise not to, due to possible changes in compiler perf.

@bors rollup=never
@rustbot label: -S-waiting-on-perf -perf-regression

Instruction count

Our most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-0.5% [-0.5%, -0.4%] 3
All ❌✅ (primary) - - 0

Max RSS (memory usage)

Results (secondary -1.5%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
2.1% [1.8%, 2.2%] 3
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-3.6% [-5.4%, -1.9%] 5
All ❌✅ (primary) - - 0

Cycles

This benchmark run did not return any relevant results for this metric.

Binary size

This benchmark run did not return any relevant results for this metric.

Bootstrap: 464.444s -> 464.79s (0.07%)
Artifact size: 374.45 MiB -> 374.43 MiB (-0.00%)

@rustbot rustbot removed the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Jul 9, 2025
@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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
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.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants