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

Rollup of 5 pull requests #99412

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions compiler/rustc_borrowck/src/type_check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKi
use rustc_infer::infer::{
InferCtxt, InferOk, LateBoundRegion, LateBoundRegionConversionTime, NllRegionVariableOrigin,
};
use rustc_infer::traits::ObligationCause;
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
use rustc_middle::mir::AssertKind;
Expand Down Expand Up @@ -224,6 +225,26 @@ pub(crate) fn type_check<'mir, 'tcx>(
)
.unwrap();
let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
// Check that RPITs are only constrained in their outermost
// function, otherwise report a mismatched types error.
if let OpaqueTyOrigin::FnReturn(parent) | OpaqueTyOrigin::AsyncFn(parent)
= infcx.opaque_ty_origin_unchecked(opaque_type_key.def_id, hidden_type.span)
&& parent.to_def_id() != body.source.def_id()
{
infcx
.report_mismatched_types(
&ObligationCause::misc(
hidden_type.span,
infcx.tcx.hir().local_def_id_to_hir_id(
body.source.def_id().expect_local(),
),
),
infcx.tcx.mk_opaque(opaque_type_key.def_id, opaque_type_key.substs),
hidden_type.ty,
ty::error::TypeError::Mismatch,
)
.emit();
}
trace!(
"finalized opaque type {:?} to {:#?}",
opaque_type_key,
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_const_eval/src/interpret/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,9 @@ macro_rules! make_value_visitor {
// The second `Box` field is the allocator, which we recursively check for validity
// like in regular structs.
self.visit_field(v, 1, &alloc)?;

// We visited all parts of this one.
return Ok(());
}
_ => {},
};
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/infer/opaque_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}

#[instrument(skip(self), level = "trace")]
fn opaque_ty_origin_unchecked(&self, opaque_def_id: DefId, span: Span) -> OpaqueTyOrigin {
pub fn opaque_ty_origin_unchecked(&self, opaque_def_id: DefId, span: Span) -> OpaqueTyOrigin {
let def_id = opaque_def_id.as_local().unwrap();
let origin = match self.tcx.hir().expect_item(def_id).kind {
hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => origin,
Expand Down
5 changes: 4 additions & 1 deletion library/alloc/src/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,14 @@ pub use std::alloc::Global;
/// # Examples
///
/// ```
/// use std::alloc::{alloc, dealloc, Layout};
/// use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
///
/// unsafe {
/// let layout = Layout::new::<u16>();
/// let ptr = alloc(layout);
/// if ptr.is_null() {
/// handle_alloc_error(layout);
/// }
///
/// *(ptr as *mut u16) = 42;
/// assert_eq!(*(ptr as *mut u16), 42);
Expand Down
2 changes: 2 additions & 0 deletions library/core/src/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,8 @@ pub fn copy<T: Copy>(x: &T) -> T {
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_transmute_copy", issue = "83165")]
pub const unsafe fn transmute_copy<T, U>(src: &T) -> U {
assert!(size_of::<T>() >= size_of::<U>(), "cannot transmute_copy if U is larger than T");

// If U has a higher alignment requirement, src might not be suitably aligned.
if align_of::<U>() > align_of::<T>() {
// SAFETY: `src` is a reference which is guaranteed to be valid for reads.
Expand Down
40 changes: 40 additions & 0 deletions library/core/tests/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,46 @@ fn test_transmute_copy() {
assert_eq!(1, unsafe { transmute_copy(&1) });
}

#[test]
fn test_transmute_copy_shrink() {
assert_eq!(0_u8, unsafe { transmute_copy(&0_u64) });
}

#[test]
fn test_transmute_copy_unaligned() {
#[repr(C)]
#[derive(Default)]
struct Unaligned {
a: u8,
b: [u8; 8],
}

let u = Unaligned::default();
assert_eq!(0_u64, unsafe { transmute_copy(&u.b) });
}

#[test]
#[cfg(panic = "unwind")]
fn test_transmute_copy_grow_panics() {
use std::panic;

let err = panic::catch_unwind(panic::AssertUnwindSafe(|| unsafe {
let _unused: u64 = transmute_copy(&1_u8);
}));

match err {
Ok(_) => unreachable!(),
Err(payload) => {
payload
.downcast::<&'static str>()
.and_then(|s| {
if *s == "cannot transmute_copy if U is larger than T" { Ok(s) } else { Err(s) }
})
.unwrap_or_else(|p| panic::resume_unwind(p));
}
}
}

#[test]
#[allow(dead_code)]
fn test_discriminant_send_sync() {
Expand Down
14 changes: 14 additions & 0 deletions library/std/src/fs/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1534,3 +1534,17 @@ fn read_large_dir() {
entry.unwrap();
}
}

/// Test the fallback for getting the metadata of files like hiberfil.sys that
/// Windows holds a special lock on, preventing normal means of querying
/// metadata. See #96980.
#[test]
#[cfg(windows)]
fn hiberfil_sys() {
let hiberfil = Path::new(r"C:\hiberfil.sys");

assert_eq!(true, hiberfil.try_exists().unwrap());
fs::symlink_metadata(hiberfil).unwrap();
fs::metadata(hiberfil).unwrap();
assert_eq!(true, hiberfil.exists());
}
108 changes: 82 additions & 26 deletions library/std/src/sys/windows/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,22 +155,7 @@ impl DirEntry {
}

pub fn metadata(&self) -> io::Result<FileAttr> {
Ok(FileAttr {
attributes: self.data.dwFileAttributes,
creation_time: self.data.ftCreationTime,
last_access_time: self.data.ftLastAccessTime,
last_write_time: self.data.ftLastWriteTime,
file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64),
reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
// reserved unless this is a reparse point
self.data.dwReserved0
} else {
0
},
volume_serial_number: None,
number_of_links: None,
file_index: None,
})
Ok(self.data.into())
}
}

Expand Down Expand Up @@ -879,6 +864,26 @@ impl FileAttr {
self.file_index
}
}
impl From<c::WIN32_FIND_DATAW> for FileAttr {
fn from(wfd: c::WIN32_FIND_DATAW) -> Self {
FileAttr {
attributes: wfd.dwFileAttributes,
creation_time: wfd.ftCreationTime,
last_access_time: wfd.ftLastAccessTime,
last_write_time: wfd.ftLastWriteTime,
file_size: ((wfd.nFileSizeHigh as u64) << 32) | (wfd.nFileSizeLow as u64),
reparse_tag: if wfd.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
// reserved unless this is a reparse point
wfd.dwReserved0
} else {
0
},
volume_serial_number: None,
number_of_links: None,
file_index: None,
}
}
}

fn to_u64(ft: &c::FILETIME) -> u64 {
(ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)
Expand Down Expand Up @@ -1145,22 +1150,73 @@ pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
}

pub fn stat(path: &Path) -> io::Result<FileAttr> {
let mut opts = OpenOptions::new();
// No read or write permissions are necessary
opts.access_mode(0);
// This flag is so we can open directories too
opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
let file = File::open(path, &opts)?;
file.file_attr()
metadata(path, ReparsePoint::Follow)
}

pub fn lstat(path: &Path) -> io::Result<FileAttr> {
metadata(path, ReparsePoint::Open)
}

#[repr(u32)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum ReparsePoint {
Follow = 0,
Open = c::FILE_FLAG_OPEN_REPARSE_POINT,
}
impl ReparsePoint {
fn as_flag(self) -> u32 {
self as u32
}
}

fn metadata(path: &Path, reparse: ReparsePoint) -> io::Result<FileAttr> {
let mut opts = OpenOptions::new();
// No read or write permissions are necessary
opts.access_mode(0);
opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT);
let file = File::open(path, &opts)?;
file.file_attr()
opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | reparse.as_flag());

// Attempt to open the file normally.
// If that fails with `ERROR_SHARING_VIOLATION` then retry using `FindFirstFileW`.
// If the fallback fails for any reason we return the original error.
match File::open(path, &opts) {
Ok(file) => file.file_attr(),
Err(e) if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as _) => {
// `ERROR_SHARING_VIOLATION` will almost never be returned.
// Usually if a file is locked you can still read some metadata.
// However, there are special system files, such as
// `C:\hiberfil.sys`, that are locked in a way that denies even that.
unsafe {
let path = maybe_verbatim(path)?;

// `FindFirstFileW` accepts wildcard file names.
// Fortunately wildcards are not valid file names and
// `ERROR_SHARING_VIOLATION` means the file exists (but is locked)
// therefore it's safe to assume the file name given does not
// include wildcards.
let mut wfd = mem::zeroed();
let handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);

if handle == c::INVALID_HANDLE_VALUE {
// This can fail if the user does not have read access to the
// directory.
Err(e)
} else {
// We no longer need the find handle.
c::FindClose(handle);

// `FindFirstFileW` reads the cached file information from the
// directory. The downside is that this metadata may be outdated.
let attrs = FileAttr::from(wfd);
if reparse == ReparsePoint::Follow && attrs.file_type().is_symlink() {
Err(e)
} else {
Ok(attrs)
}
}
}
}
Err(e) => Err(e),
}
}

pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
Expand Down
17 changes: 17 additions & 0 deletions src/test/ui/impl-trait/issue-99073-2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use std::fmt::Display;

fn main() {
test("hi", true);
}

fn test<T: Display>(t: T, recurse: bool) -> impl Display {
let f = || {
let i: u32 = test::<i32>(-1, false);
//~^ ERROR mismatched types
println!("{i}");
};
if recurse {
f();
}
t
}
15 changes: 15 additions & 0 deletions src/test/ui/impl-trait/issue-99073-2.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
error[E0308]: mismatched types
--> $DIR/issue-99073-2.rs:9:22
|
LL | fn test<T: Display>(t: T, recurse: bool) -> impl Display {
| ------------ the expected opaque type
LL | let f = || {
LL | let i: u32 = test::<i32>(-1, false);
| ^^^^^^^^^^^^^^^^^^^^^^ types differ
|
= note: expected opaque type `impl std::fmt::Display`
found type `u32`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
8 changes: 8 additions & 0 deletions src/test/ui/impl-trait/issue-99073.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
fn main() {
let _ = fix(|_: &dyn Fn()| {});
}

fn fix<F: Fn(G), G: Fn()>(f: F) -> impl Fn() {
move || f(fix(&f))
//~^ ERROR mismatched types
}
14 changes: 14 additions & 0 deletions src/test/ui/impl-trait/issue-99073.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
error[E0308]: mismatched types
--> $DIR/issue-99073.rs:6:13
|
LL | fn fix<F: Fn(G), G: Fn()>(f: F) -> impl Fn() {
| --------- the expected opaque type
LL | move || f(fix(&f))
| ^^^^^^^^^^ types differ
|
= note: expected opaque type `impl Fn()`
found type parameter `G`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.