1 use libloading::Library;
3 use rustc_codegen_ssa::traits::CodegenBackend;
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 #[cfg(parallel_compiler)]
6 use rustc_data_structures::jobserver;
7 use rustc_data_structures::sync::Lrc;
8 use rustc_errors::registry::Registry;
9 #[cfg(parallel_compiler)]
10 use rustc_middle::ty::tls;
11 use rustc_parse::validate_attr;
12 #[cfg(parallel_compiler)]
13 use rustc_query_impl::{QueryContext, QueryCtxt};
14 use rustc_session as session;
15 use rustc_session::config::CheckCfg;
16 use rustc_session::config::{self, CrateType};
17 use rustc_session::config::{ErrorOutputType, Input, OutputFilenames};
18 use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
19 use rustc_session::parse::CrateConfig;
20 use rustc_session::{early_error, filesearch, output, DiagnosticOutput, Session};
21 use rustc_span::edition::Edition;
22 use rustc_span::lev_distance::find_best_match_for_name;
23 use rustc_span::source_map::FileLoader;
24 use rustc_span::symbol::{sym, Symbol};
26 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
28 #[cfg(not(parallel_compiler))]
30 use std::path::{Path, PathBuf};
31 use std::sync::atomic::{AtomicBool, Ordering};
32 use std::sync::OnceLock;
36 /// Function pointer type that constructs a new CodegenBackend.
37 pub type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
39 /// Adds `target_feature = "..."` cfgs for a variety of platform
40 /// specific features (SSE, NEON etc.).
42 /// This is performed by checking whether a set of permitted features
43 /// is available on the target machine, by querying LLVM.
44 pub fn add_configuration(
45 cfg: &mut CrateConfig,
47 codegen_backend: &dyn CodegenBackend,
49 let tf = sym::target_feature;
51 let unstable_target_features = codegen_backend.target_features(sess, true);
52 sess.unstable_target_features.extend(unstable_target_features.iter().cloned());
54 let target_features = codegen_backend.target_features(sess, false);
55 sess.target_features.extend(target_features.iter().cloned());
57 cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
59 if sess.crt_static(None) {
60 cfg.insert((tf, Some(sym::crt_dash_static)));
64 pub fn create_session(
65 sopts: config::Options,
66 cfg: FxHashSet<(String, Option<String>)>,
68 diagnostic_output: DiagnosticOutput,
69 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
70 input_path: Option<PathBuf>,
71 lint_caps: FxHashMap<lint::LintId, lint::Level>,
72 make_codegen_backend: Option<
73 Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
75 descriptions: Registry,
76 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>) {
77 let codegen_backend = if let Some(make_codegen_backend) = make_codegen_backend {
78 make_codegen_backend(&sopts)
82 sopts.unstable_opts.codegen_backend.as_ref().map(|name| &name[..]),
86 // target_override is documented to be called before init(), so this is okay
87 let target_override = codegen_backend.target_override(&sopts);
89 let bundle = match rustc_errors::fluent_bundle(
90 sopts.maybe_sysroot.clone(),
92 sopts.unstable_opts.translate_lang.clone(),
93 sopts.unstable_opts.translate_additional_ftl.as_deref(),
94 sopts.unstable_opts.translate_directionality_markers,
98 early_error(sopts.error_format, &format!("failed to load fluent bundle: {e}"));
102 let mut sess = session::build_session(
113 codegen_backend.init(&sess);
115 let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
116 add_configuration(&mut cfg, &mut sess, &*codegen_backend);
118 let mut check_cfg = config::to_crate_check_config(check_cfg);
119 check_cfg.fill_well_known();
120 check_cfg.fill_actual(&cfg);
122 sess.parse_sess.config = cfg;
123 sess.parse_sess.check_config = check_cfg;
125 (Lrc::new(sess), Lrc::new(codegen_backend))
128 const STACK_SIZE: usize = 8 * 1024 * 1024;
130 fn get_stack_size() -> Option<usize> {
131 // FIXME: Hacks on hacks. If the env is trying to override the stack size
132 // then *don't* set it explicitly.
133 env::var_os("RUST_MIN_STACK").is_none().then_some(STACK_SIZE)
136 /// Like a `thread::Builder::spawn` followed by a `join()`, but avoids the need
137 /// for `'static` bounds.
138 #[cfg(not(parallel_compiler))]
139 fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
140 // SAFETY: join() is called immediately, so any closure captures are still
142 match unsafe { cfg.spawn_unchecked(f) }.unwrap().join() {
144 Err(e) => panic::resume_unwind(e),
148 #[cfg(not(parallel_compiler))]
149 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
154 let mut cfg = thread::Builder::new().name("rustc".to_string());
156 if let Some(size) = get_stack_size() {
157 cfg = cfg.stack_size(size);
160 let main_handler = move || rustc_span::create_session_globals_then(edition, f);
162 scoped_thread(cfg, main_handler)
165 /// Creates a new thread and forwards information in thread locals to it.
166 /// The new thread runs the deadlock handler.
167 /// Must only be called when a deadlock is about to happen.
168 #[cfg(parallel_compiler)]
169 unsafe fn handle_deadlock() {
170 let registry = rustc_rayon_core::Registry::current();
172 let query_map = tls::with(|tcx| {
173 QueryCtxt::from_tcx(tcx)
174 .try_collect_active_jobs()
175 .expect("active jobs shouldn't be locked in deadlock handler")
177 thread::spawn(move || rustc_query_impl::deadlock(query_map, ®istry));
180 #[cfg(parallel_compiler)]
181 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
186 let mut config = rayon::ThreadPoolBuilder::new()
187 .thread_name(|_| "rustc".to_string())
188 .acquire_thread_handler(jobserver::acquire_thread)
189 .release_thread_handler(jobserver::release_thread)
190 .num_threads(threads)
191 .deadlock_handler(|| unsafe { handle_deadlock() });
193 if let Some(size) = get_stack_size() {
194 config = config.stack_size(size);
197 let with_pool = move |pool: &rayon::ThreadPool| pool.install(f);
199 rustc_span::create_session_globals_then(edition, || {
200 rustc_span::with_session_globals(|session_globals| {
201 // The main handler runs for each Rayon worker thread and sets up
202 // the thread local rustc uses. `session_globals` is captured and set
203 // on the new threads.
204 let main_handler = move |thread: rayon::ThreadBuilder| {
205 rustc_span::set_session_globals_then(session_globals, || thread.run())
208 config.build_scoped(main_handler, with_pool).unwrap()
213 fn load_backend_from_dylib(path: &Path) -> MakeBackendFn {
214 let lib = unsafe { Library::new(path) }.unwrap_or_else(|err| {
215 let err = format!("couldn't load codegen backend {:?}: {}", path, err);
216 early_error(ErrorOutputType::default(), &err);
219 let backend_sym = unsafe { lib.get::<MakeBackendFn>(b"__rustc_codegen_backend") }
220 .unwrap_or_else(|e| {
221 let err = format!("couldn't load codegen backend: {}", e);
222 early_error(ErrorOutputType::default(), &err);
225 // Intentionally leak the dynamic library. We can't ever unload it
226 // since the library can make things that will live arbitrarily long.
227 let backend_sym = unsafe { backend_sym.into_raw() };
233 /// Get the codegen backend based on the name and specified sysroot.
235 /// A name of `None` indicates that the default backend should be used.
236 pub fn get_codegen_backend(
237 maybe_sysroot: &Option<PathBuf>,
238 backend_name: Option<&str>,
239 ) -> Box<dyn CodegenBackend> {
240 static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
242 let load = LOAD.get_or_init(|| {
243 let default_codegen_backend = option_env!("CFG_DEFAULT_CODEGEN_BACKEND").unwrap_or("llvm");
245 match backend_name.unwrap_or(default_codegen_backend) {
246 filename if filename.contains('.') => load_backend_from_dylib(filename.as_ref()),
247 #[cfg(feature = "llvm")]
248 "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
249 backend_name => get_codegen_sysroot(maybe_sysroot, backend_name),
253 // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
254 // backend we hope that the backend links against the same rustc_driver version. If this is not
255 // the case, we get UB.
259 // This is used for rustdoc, but it uses similar machinery to codegen backend
260 // loading, so we leave the code here. It is potentially useful for other tools
261 // that want to invoke the rustc binary while linking to rustc as well.
262 pub fn rustc_path<'a>() -> Option<&'a Path> {
263 static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
265 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
267 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
270 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
271 sysroot_candidates().iter().find_map(|sysroot| {
272 let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
277 candidate.exists().then_some(candidate)
281 fn sysroot_candidates() -> Vec<PathBuf> {
282 let target = session::config::host_triple();
283 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
284 let path = current_dll_path().and_then(|s| s.canonicalize().ok());
285 if let Some(dll) = path {
286 // use `parent` twice to chop off the file name and then also the
287 // directory containing the dll which should be either `lib` or `bin`.
288 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
289 // The original `path` pointed at the `rustc_driver` crate's dll.
290 // Now that dll should only be in one of two locations. The first is
291 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
292 // other is the target's libdir, for example
293 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
295 // We don't know which, so let's assume that if our `path` above
296 // ends in `$target` we *could* be in the target libdir, and always
297 // assume that we may be in the main libdir.
298 sysroot_candidates.push(path.to_owned());
300 if path.ends_with(target) {
301 sysroot_candidates.extend(
302 path.parent() // chop off `$target`
303 .and_then(|p| p.parent()) // chop off `rustlib`
304 .and_then(|p| p.parent()) // chop off `lib`
305 .map(|s| s.to_owned()),
311 return sysroot_candidates;
314 fn current_dll_path() -> Option<PathBuf> {
315 use std::ffi::{CStr, OsStr};
316 use std::os::unix::prelude::*;
319 let addr = current_dll_path as usize as *mut _;
320 let mut info = mem::zeroed();
321 if libc::dladdr(addr, &mut info) == 0 {
322 info!("dladdr failed");
325 if info.dli_fname.is_null() {
326 info!("dladdr returned null pointer");
329 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
330 let os = OsStr::from_bytes(bytes);
331 Some(PathBuf::from(os))
336 fn current_dll_path() -> Option<PathBuf> {
337 use std::ffi::OsString;
339 use std::os::windows::prelude::*;
342 use winapi::um::libloaderapi::{
343 GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
347 let mut module = ptr::null_mut();
348 let r = GetModuleHandleExW(
349 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
350 current_dll_path as usize as *mut _,
354 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
357 let mut space = Vec::with_capacity(1024);
358 let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32);
360 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
364 if r >= space.capacity() {
365 info!("our buffer was too small? {}", io::Error::last_os_error());
369 let os = OsString::from_wide(&space);
370 Some(PathBuf::from(os))
375 fn get_codegen_sysroot(maybe_sysroot: &Option<PathBuf>, backend_name: &str) -> MakeBackendFn {
376 // For now we only allow this function to be called once as it'll dlopen a
377 // few things, which seems to work best if we only do that once. In
378 // general this assertion never trips due to the once guard in `get_codegen_backend`,
379 // but there's a few manual calls to this function in this file we protect
381 static LOADED: AtomicBool = AtomicBool::new(false);
383 !LOADED.fetch_or(true, Ordering::SeqCst),
384 "cannot load the default codegen backend twice"
387 let target = session::config::host_triple();
388 let sysroot_candidates = sysroot_candidates();
390 let sysroot = maybe_sysroot
392 .chain(sysroot_candidates.iter())
394 filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
397 info!("codegen backend candidate: {}", f.display());
400 let sysroot = sysroot.unwrap_or_else(|| {
401 let candidates = sysroot_candidates
403 .map(|p| p.display().to_string())
407 "failed to find a `codegen-backends` folder \
408 in the sysroot candidates:\n* {}",
411 early_error(ErrorOutputType::default(), &err);
413 info!("probing {} for a codegen backend", sysroot.display());
415 let d = sysroot.read_dir().unwrap_or_else(|e| {
417 "failed to load default codegen backend, couldn't \
422 early_error(ErrorOutputType::default(), &err);
425 let mut file: Option<PathBuf> = None;
427 let expected_names = &[
428 format!("rustc_codegen_{}-{}", backend_name, release_str().expect("CFG_RELEASE")),
429 format!("rustc_codegen_{}", backend_name),
431 for entry in d.filter_map(|e| e.ok()) {
432 let path = entry.path();
433 let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
434 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
437 let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
438 if !expected_names.iter().any(|expected| expected == name) {
441 if let Some(ref prev) = file {
443 "duplicate codegen backends found\n\
450 early_error(ErrorOutputType::default(), &err);
452 file = Some(path.clone());
456 Some(ref s) => load_backend_from_dylib(s),
458 let err = format!("unsupported builtin codegen backend `{}`", backend_name);
459 early_error(ErrorOutputType::default(), &err);
464 pub(crate) fn check_attr_crate_type(
466 attrs: &[ast::Attribute],
467 lint_buffer: &mut LintBuffer,
469 // Unconditionally collect crate types from attributes to make them used
470 for a in attrs.iter() {
471 if a.has_name(sym::crate_type) {
472 if let Some(n) = a.value_str() {
473 if categorize_crate_type(n).is_some() {
477 if let ast::MetaItemKind::NameValue(spanned) = a.meta_kind().unwrap() {
478 let span = spanned.span;
479 let lev_candidate = find_best_match_for_name(
480 &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
484 if let Some(candidate) = lev_candidate {
485 lint_buffer.buffer_lint_with_diagnostic(
486 lint::builtin::UNKNOWN_CRATE_TYPES,
489 "invalid `crate_type` value",
490 BuiltinLintDiagnostics::UnknownCrateTypes(
492 "did you mean".to_string(),
493 format!("\"{}\"", candidate),
497 lint_buffer.buffer_lint(
498 lint::builtin::UNKNOWN_CRATE_TYPES,
501 "invalid `crate_type` value",
506 // This is here mainly to check for using a macro, such as
507 // #![crate_type = foo!()]. That is not supported since the
508 // crate type needs to be known very early in compilation long
509 // before expansion. Otherwise, validation would normally be
510 // caught in AstValidator (via `check_builtin_attribute`), but
511 // by the time that runs the macro is expanded, and it doesn't
513 validate_attr::emit_fatal_malformed_builtin_attribute(
523 const CRATE_TYPES: &[(Symbol, CrateType)] = &[
524 (sym::rlib, CrateType::Rlib),
525 (sym::dylib, CrateType::Dylib),
526 (sym::cdylib, CrateType::Cdylib),
527 (sym::lib, config::default_lib_output()),
528 (sym::staticlib, CrateType::Staticlib),
529 (sym::proc_dash_macro, CrateType::ProcMacro),
530 (sym::bin, CrateType::Executable),
533 fn categorize_crate_type(s: Symbol) -> Option<CrateType> {
534 Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
537 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<CrateType> {
538 // Unconditionally collect crate types from attributes to make them used
539 let attr_types: Vec<CrateType> = attrs
542 if a.has_name(sym::crate_type) {
543 match a.value_str() {
544 Some(s) => categorize_crate_type(s),
553 // If we're generating a test executable, then ignore all other output
554 // styles at all other locations
555 if session.opts.test {
556 return vec![CrateType::Executable];
559 // Only check command line flags if present. If no types are specified by
560 // command line, then reuse the empty `base` Vec to hold the types that
561 // will be found in crate attributes.
562 let mut base = session.opts.crate_types.clone();
564 base.extend(attr_types);
566 base.push(output::default_output_for_target(session));
573 base.retain(|crate_type| {
574 let res = !output::invalid_output_for_target(session, *crate_type);
577 session.warn(&format!(
578 "dropping unsupported crate type `{}` for target `{}`",
579 *crate_type, session.opts.target_triple
589 pub fn build_output_filenames(
591 odir: &Option<PathBuf>,
592 ofile: &Option<PathBuf>,
593 temps_dir: &Option<PathBuf>,
594 attrs: &[ast::Attribute],
596 ) -> OutputFilenames {
599 // "-" as input file will cause the parser to read from stdin so we
600 // have to make up a name
601 // We want to toss everything after the final '.'
602 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
604 // If a crate name is present, we use it as the link name
609 .or_else(|| rustc_attr::find_crate_name(sess, attrs).map(|n| n.to_string()))
610 .unwrap_or_else(|| input.filestem().to_owned());
612 OutputFilenames::new(
617 sess.opts.cg.extra_filename.clone(),
618 sess.opts.output_types.clone(),
622 Some(ref out_file) => {
623 let unnamed_output_types =
624 sess.opts.output_types.values().filter(|a| a.is_none()).count();
625 let ofile = if unnamed_output_types > 1 {
627 "due to multiple output types requested, the explicitly specified \
628 output file name will be adapted for each output type",
632 if !sess.opts.cg.extra_filename.is_empty() {
633 sess.warn("ignoring -C extra-filename flag due to -o flag");
635 Some(out_file.clone())
638 sess.warn("ignoring --out-dir flag due to -o flag");
641 OutputFilenames::new(
642 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
643 out_file.file_stem().unwrap_or_default().to_str().unwrap().to_string(),
646 sess.opts.cg.extra_filename.clone(),
647 sess.opts.output_types.clone(),
653 /// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)"
654 pub fn version_str() -> Option<&'static str> {
655 option_env!("CFG_VERSION")
658 /// Returns a version string such as "0.12.0-dev".
659 pub fn release_str() -> Option<&'static str> {
660 option_env!("CFG_RELEASE")
663 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
664 pub fn commit_hash_str() -> Option<&'static str> {
665 option_env!("CFG_VER_HASH")
668 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
669 pub fn commit_date_str() -> Option<&'static str> {
670 option_env!("CFG_VER_DATE")