Skip to content
Merged
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
45 changes: 32 additions & 13 deletions compiler/rustc_codegen_ssa/src/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,7 @@ pub fn link_binary(
&crate_info,
&metadata,
path.as_ref(),
outputs,
codegen_backend,
);
}
Expand Down Expand Up @@ -1236,6 +1237,7 @@ fn link_natively(
crate_info: &CrateInfo,
metadata: &EncodedMetadata,
tmpdir: &Path,
outputs: &OutputFilenames,
codegen_backend: &'static str,
) {
info!("preparing {:?} to {:?}", crate_type, out_filename);
Expand All @@ -1251,6 +1253,18 @@ fn link_natively(
should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so"));
let temp_filename = archive_member.as_deref().unwrap_or(out_filename);

// Follow the same naming convention as regular codegen objects.
let metadata_object = outputs.temp_path_for_cgu(OutputType::Object, "rustc_link_metadata");
let symbols_object = outputs.temp_path_for_cgu(OutputType::Object, "rustc_link_symbols");

// Clean up the generated linker inputs even if linking fails.
let _cleanup = rustc_data_structures::defer(|| {
if !sess.opts.cg.save_temps {
ensure_removed(sess.dcx(), &metadata_object);
ensure_removed(sess.dcx(), &symbols_object);
}
});

let (mut cmd, jobserver_tokens) = linker_with_args(
&linker_path,
flavor,
Expand All @@ -1259,6 +1273,8 @@ fn link_natively(
rmeta_link_cache,
crate_type,
tmpdir,
&metadata_object,
&symbols_object,
temp_filename,
compiled_modules,
crate_info,
Expand Down Expand Up @@ -2534,7 +2550,7 @@ fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor
fn add_linked_symbol_object(
cmd: &mut dyn Linker,
sess: &Session,
tmpdir: &Path,
symbols_path: &Path,
crate_type: CrateType,
linked_symbols: &[(String, SymbolExportKind)],
exported_symbols: &[SymbolExport],
Expand Down Expand Up @@ -2669,12 +2685,11 @@ fn add_linked_symbol_object(
file.append_section_data(section, drectve.as_bytes(), 1);
}

let path = tmpdir.join("symbols.o");
let result = std::fs::write(&path, file.write().unwrap());
if let Err(error) = result {
sess.dcx().emit_fatal(diagnostics::FailedToWrite { path, error });
}
cmd.add_object(&path);
fs::write(symbols_path, file.write().unwrap()).unwrap_or_else(|error| {
sess.dcx()
.emit_fatal(diagnostics::FailedToWrite { path: symbols_path.to_path_buf(), error })
});
cmd.add_object(symbols_path);
}

/// Add object files containing code from the current crate.
Expand Down Expand Up @@ -2714,7 +2729,7 @@ fn add_local_crate_metadata_objects(
sess: &Session,
archive_builder_builder: &dyn ArchiveBuilderBuilder,
crate_type: CrateType,
tmpdir: &Path,
metadata_path: &Path,
crate_info: &CrateInfo,
metadata: &EncodedMetadata,
) {
Expand All @@ -2727,9 +2742,11 @@ fn add_local_crate_metadata_objects(
&metadata,
&crate_info.metadata_symbol,
);
let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o");

cmd.add_object(&obj);
fs::write(metadata_path, data).unwrap_or_else(|error| {
sess.dcx()
.emit_fatal(diagnostics::FailedToWrite { path: metadata_path.to_path_buf(), error })
});
cmd.add_object(metadata_path);
}
}

Expand Down Expand Up @@ -2912,6 +2929,8 @@ fn linker_with_args(
rmeta_link_cache: &mut RmetaLinkCache,
crate_type: CrateType,
tmpdir: &Path,
metadata_object: &Path,
symbols_object: &Path,
out_filename: &Path,
compiled_modules: &CompiledModules,
crate_info: &CrateInfo,
Expand Down Expand Up @@ -2972,7 +2991,7 @@ fn linker_with_args(
add_linked_symbol_object(
cmd,
sess,
tmpdir,
symbols_object,
crate_type,
&crate_info.linked_symbols[&crate_type],
&export_symbols,
Expand Down Expand Up @@ -3014,7 +3033,7 @@ fn linker_with_args(
sess,
archive_builder_builder,
crate_type,
tmpdir,
metadata_object,
crate_info,
metadata,
);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/const_eval/valtrees.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ fn branches<'tcx>(
}

for i in 0..field_count {
let field = ecx.project_field(&place, FieldIdx::from_usize(i)).unwrap();
let field = ecx.project_field(&place, FieldIdx::from_usize(i)).report_err()?;
let valtree = const_to_valtree_inner(ecx, &field, num_nodes, visited, settled)?;
branches.push(ty::Const::new_value(*ecx.tcx, valtree, field.layout.ty));
}
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ impl<'tcx, 'ptcx> PatCtxt<'tcx, 'ptcx> {
match c.kind() {
ty::ConstKind::Alias(_, alias_const) => convert.alias_to_pat(alias_const, ty),
ty::ConstKind::Value(value) => convert.valtree_to_pat(value),
ty::ConstKind::Error(guard) => {
Box::new(Pat { span, ty, kind: PatKind::Error(guard), extra: None })
}
_ => span_bug!(span, "Invalid `ConstKind` for `const_to_pat`: {:?}", c),
}
}
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_type_ir/src/region_constraint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1339,7 +1339,8 @@ fn alias_outlives_candidates_from_assumptions<Infcx: InferCtxtLike<Interner = I>
// FIXME(#155345): Both sides should be rigid in the future.
// Currently we can't guarantee that.
if let Ok(_) = relation.relate(
alias.to_ty(infcx.cx(), IsRigid::No),
set_aliases_to_non_rigid(infcx.cx(), alias.to_ty(infcx.cx(), IsRigid::No))
.skip_norm_wip(),
set_aliases_to_non_rigid(infcx.cx(), alias2).skip_norm_wip(),
) {
candidates.push(And::new(relation.region_constraints));
Expand Down
82 changes: 82 additions & 0 deletions library/std/src/os/unix/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -828,3 +828,85 @@ impl From<OwnedFd> for process::ChildStderr {
pub fn parent_id() -> u32 {
crate::sys::process::getppid()
}

/// Returns the real user ID of the current process.
///
/// # Example
///
#[cfg_attr(target_family = "unix", doc = "```")]
#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
/// #![feature(unix_process_user_group_ids)]
/// use std::os::unix::process;
///
/// fn main() {
/// let uid = process::uid();
/// println!("The current process has UID {}", uid);
/// }
/// ```
#[must_use]
#[unstable(feature = "unix_process_user_group_ids", issue = "166252")]
pub fn uid() -> u32 {
crate::sys::process::getuid()
}

/// Returns the effective user ID of the current process.
///
/// # Example
///
#[cfg_attr(target_family = "unix", doc = "```")]
#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
/// #![feature(unix_process_user_group_ids)]
/// use std::os::unix::process;
///
/// fn main() {
/// let euid = process::effective_uid();
/// println!("The current process has effective UID {}", euid);
/// }
/// ```
#[must_use]
#[unstable(feature = "unix_process_user_group_ids", issue = "166252")]
pub fn effective_uid() -> u32 {
crate::sys::process::geteuid()
}

/// Returns the real group ID of the current process.
///
/// # Example
///
#[cfg_attr(target_family = "unix", doc = "```")]
#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
/// #![feature(unix_process_user_group_ids)]
/// use std::os::unix::process;
///
/// fn main() {
/// # if cfg!(skip_unsupported_miri_tests) { return; }
/// let gid = process::gid();
/// println!("The current process has GID {}", gid);
/// }
/// ```
#[must_use]
#[unstable(feature = "unix_process_user_group_ids", issue = "166252")]
pub fn gid() -> u32 {
crate::sys::process::getgid()
}

/// Returns the effective group ID of the current process.
///
/// # Example
///
#[cfg_attr(target_family = "unix", doc = "```")]
#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
/// #![feature(unix_process_user_group_ids)]
/// use std::os::unix::process;
///
/// fn main() {
/// # if cfg!(skip_unsupported_miri_tests) { return; }
/// let egid = process::effective_gid();
/// println!("The current process has effective GID {}", egid);
/// }
/// ```
#[must_use]
#[unstable(feature = "unix_process_user_group_ids", issue = "166252")]
pub fn effective_gid() -> u32 {
crate::sys::process::getegid()
}
4 changes: 2 additions & 2 deletions library/std/src/sys/process/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ pub use env::CommandEnvs;
pub use env::CommandResolvedEnvs;
#[cfg(target_os = "linux")]
pub use imp::PidFd;
#[cfg(target_family = "unix")]
pub use imp::getppid;
pub use imp::{
ChildPipe, Command, CommandArgs, EnvKey, ExitCode, ExitStatus, ExitStatusError, Process, Stdio,
getpid, read_output,
};
#[cfg(target_family = "unix")]
pub use imp::{getegid, geteuid, getgid, getppid, getuid};

#[cfg(any(
all(
Expand Down
16 changes: 16 additions & 0 deletions library/std/src/sys/process/unix/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -695,3 +695,19 @@ pub fn getpid() -> u32 {
pub fn getppid() -> u32 {
unsafe { libc::getppid() as u32 }
}

pub fn getuid() -> u32 {
unsafe { libc::getuid() as u32 }
}

pub fn geteuid() -> u32 {
unsafe { libc::geteuid() as u32 }
}

pub fn getgid() -> u32 {
unsafe { libc::getgid() as u32 }
}

pub fn getegid() -> u32 {
unsafe { libc::getegid() as u32 }
}
3 changes: 2 additions & 1 deletion library/std/src/sys/process/unix/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub use imp::{ExitStatus, ExitStatusError, Process};
pub use pidfd::PidFd;

pub use self::common::{
ChildPipe, Command, CommandArgs, ExitCode, Stdio, getpid, getppid, read_output,
ChildPipe, Command, CommandArgs, ExitCode, Stdio, getegid, geteuid, getgid, getpid, getppid,
getuid, read_output,
};
pub use crate::ffi::OsString as EnvKey;
6 changes: 0 additions & 6 deletions tests/crashes/148890.rs

This file was deleted.

9 changes: 7 additions & 2 deletions tests/run-make/comment-section/rmake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,15 @@ fn main() {
.run()
.assert_stdout_contains("rustc version 1.");

// Check all object files (including temporary outputs) have a `.comment`
// Check codegen object files (including temporary outputs) have a `.comment`
// section with the expected content.
rfs::read_dir_entries(cwd(), |f| {
if !f.extension().is_some_and(|ext| ext == "o") {
// Synthetic linker inputs are not codegen objects and have no `.comment`.
let name = f.file_name().unwrap().to_string_lossy();
if !f.extension().is_some_and(|ext| ext == "o")
|| name.contains(".rustc_link_metadata.")
|| name.contains(".rustc_link_symbols.")
{
return;
}

Expand Down
3 changes: 3 additions & 0 deletions tests/run-make/linker-map-determinism/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub fn answer() -> u32 {
42
}
72 changes: 72 additions & 0 deletions tests/run-make/linker-map-determinism/rmake.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Repeated dylib links must produce identical linker maps.
//
// Regression test for #142989: rustc used to pass a metadata object
// from a randomly named temporary directory to the linker, leaking
// that directory name into the map file.
//
//@ only-linux
//@ ignore-cross-compile
//@ ignore-backends: gcc

use std::fs;

use run_make_support::rustc;

fn main() {
let build = |map: &str| -> Vec<u8> {
let map_arg = format!("-Wl,-Map={map}");

rustc().input("lib.rs").crate_type("dylib").output("libfoo.so").link_arg(&map_arg).run();

fs::read("libfoo.so").unwrap()
};

let first_binary = build("first.map");
let second_binary = build("second.map");

// Linker maps must be identical across repeated builds, including the
// paths recorded for synthetic metadata and linked-symbol objects.
assert_eq!(
fs::read("first.map").unwrap(),
fs::read("second.map").unwrap(),
"complete linker maps differ between identical builds"
);

// The metadata object is linked for this dylib, while the symbols
// object is only generated when linked symbols need to be retained.
let metadata = "libfoo.rustc_link_metadata.rcgu.o";
let symbols = "libfoo.rustc_link_symbols.rcgu.o";

for map in ["first.map", "second.map"] {
let contents = fs::read_to_string(map).unwrap();
assert!(contents.contains(metadata), "metadata object missing from {map}");
}

assert_eq!(first_binary, second_binary, "linked dylibs differ between identical builds");

// Normal linking removes synthetic objects.
assert!(!fs::exists(metadata).unwrap());
assert!(!fs::exists(symbols).unwrap());

// -C save-temps retains them.
rustc().input("lib.rs").crate_type("dylib").output("libfoo.so").arg("-Csave-temps").run();

assert!(fs::exists(metadata).unwrap());

// A subsequent normal build removes them again.
rustc().input("lib.rs").crate_type("dylib").output("libfoo.so").run();

assert!(!fs::exists(metadata).unwrap());
assert!(!fs::exists(symbols).unwrap());

// A linker failure must also clean up the generated objects.
rustc()
.input("lib.rs")
.crate_type("dylib")
.output("libfoo.so")
.arg("-Clink-arg=-Wl,--invalid-linker-map-test-option")
.run_fail();

assert!(!fs::exists(metadata).unwrap());
assert!(!fs::exists(symbols).unwrap());
}
1 change: 0 additions & 1 deletion tests/run-make/linker-warning/rmake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ fn main() {
"/build-root",
)
.normalize("libpanic_abort", "libpanic_unwind")
.normalize(r#""[^"]*\/symbols.o""#, "\"/symbols.o\"")
.normalize(r#""[^"]*\/raw-dylibs""#, "\"/raw-dylibs\"")
.normalize("\"-fno-lto\" ", "")
.run();
Expand Down
2 changes: 1 addition & 1 deletion tests/run-make/linker-warning/short-error.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
error: linking with `./fake-linker` failed: exit status: 1
|
= note: "./fake-linker" "-m64" "/symbols.o" "<2 object files omitted>" "-Wl,--as-needed" "-Wl,-Bstatic" "/build-root/test/run-make/linker-warning/rmake_out/{libfoo,libbar}.rlib" "<sysroot>/lib/rustlib/x86_64-unknown-linux-gnu/lib/{libstd-*,libpanic_unwind-*,libobject-*,libmemchr-*,libaddr2line-*,libgimli-*,libcfg_if-*,librustc_demangle-*,libstd_detect-*,libhashbrown-*,librustc_std_workspace_alloc-*,libminiz_oxide-*,libadler2-*,libunwind-*,liblibc-*,librustc_std_workspace_core-*,liballoc-*,libcore-*,libcompiler_builtins-*}.rlib" "-Wl,-Bdynamic" "-lgcc_s" "-lutil" "-lrt" "-lpthread" "-lm" "-ldl" "-lc" "-L" "/raw-dylibs" "-Wl,--eh-frame-hdr" "-Wl,-z,noexecstack" "-L" "/build-root/test/run-make/linker-warning/rmake_out" "-L" "<sysroot>/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-o" "main" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-nodefaultlibs" "run_make_error"
= note: "./fake-linker" "-m64" "<3 object files omitted>" "-Wl,--as-needed" "-Wl,-Bstatic" "/build-root/test/run-make/linker-warning/rmake_out/{libfoo,libbar}.rlib" "<sysroot>/lib/rustlib/x86_64-unknown-linux-gnu/lib/{libstd-*,libpanic_unwind-*,libobject-*,libmemchr-*,libaddr2line-*,libgimli-*,libcfg_if-*,librustc_demangle-*,libstd_detect-*,libhashbrown-*,librustc_std_workspace_alloc-*,libminiz_oxide-*,libadler2-*,libunwind-*,liblibc-*,librustc_std_workspace_core-*,liballoc-*,libcore-*,libcompiler_builtins-*}.rlib" "-Wl,-Bdynamic" "-lgcc_s" "-lutil" "-lrt" "-lpthread" "-lm" "-ldl" "-lc" "-L" "/raw-dylibs" "-Wl,--eh-frame-hdr" "-Wl,-z,noexecstack" "-L" "/build-root/test/run-make/linker-warning/rmake_out" "-L" "<sysroot>/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-o" "main" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-nodefaultlibs" "run_make_error"
= note: some arguments are omitted. use `--verbose` to show all linker arguments
= note: error: baz

Expand Down
Loading
Loading