rustc_session/
utils.rs

1use std::path::{Path, PathBuf};
2use std::sync::OnceLock;
3
4use rustc_data_structures::profiling::VerboseTimingGuard;
5use rustc_fs_util::try_canonicalize;
6use rustc_macros::{Decodable, Encodable, HashStable_Generic};
7
8use crate::session::Session;
9
10impl Session {
11    pub fn timer(&self, what: &'static str) -> VerboseTimingGuard<'_> {
12        self.prof.verbose_generic_activity(what)
13    }
14    /// Used by `-Z self-profile`.
15    pub fn time<R>(&self, what: &'static str, f: impl FnOnce() -> R) -> R {
16        self.prof.verbose_generic_activity(what).run(f)
17    }
18}
19
20#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
21#[derive(HashStable_Generic)]
22pub enum NativeLibKind {
23    /// Static library (e.g. `libfoo.a` on Linux or `foo.lib` on Windows/MSVC)
24    Static {
25        /// Whether to bundle objects from static library into produced rlib
26        bundle: Option<bool>,
27        /// Whether to link static library without throwing any object files away
28        whole_archive: Option<bool>,
29    },
30    /// Dynamic library (e.g. `libfoo.so` on Linux)
31    /// or an import library corresponding to a dynamic library (e.g. `foo.lib` on Windows/MSVC).
32    Dylib {
33        /// Whether the dynamic library will be linked only if it satisfies some undefined symbols
34        as_needed: Option<bool>,
35    },
36    /// Dynamic library (e.g. `foo.dll` on Windows) without a corresponding import library.
37    RawDylib,
38    /// A macOS-specific kind of dynamic libraries.
39    Framework {
40        /// Whether the framework will be linked only if it satisfies some undefined symbols
41        as_needed: Option<bool>,
42    },
43    /// Argument which is passed to linker, relative order with libraries and other arguments
44    /// is preserved
45    LinkArg,
46
47    /// Module imported from WebAssembly
48    WasmImportModule,
49
50    /// The library kind wasn't specified, `Dylib` is currently used as a default.
51    Unspecified,
52}
53
54impl NativeLibKind {
55    pub fn has_modifiers(&self) -> bool {
56        match self {
57            NativeLibKind::Static { bundle, whole_archive } => {
58                bundle.is_some() || whole_archive.is_some()
59            }
60            NativeLibKind::Dylib { as_needed } | NativeLibKind::Framework { as_needed } => {
61                as_needed.is_some()
62            }
63            NativeLibKind::RawDylib
64            | NativeLibKind::Unspecified
65            | NativeLibKind::LinkArg
66            | NativeLibKind::WasmImportModule => false,
67        }
68    }
69
70    pub fn is_statically_included(&self) -> bool {
71        matches!(self, NativeLibKind::Static { .. })
72    }
73
74    pub fn is_dllimport(&self) -> bool {
75        matches!(
76            self,
77            NativeLibKind::Dylib { .. } | NativeLibKind::RawDylib | NativeLibKind::Unspecified
78        )
79    }
80}
81
82#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
83#[derive(HashStable_Generic)]
84pub struct NativeLib {
85    pub name: String,
86    pub new_name: Option<String>,
87    pub kind: NativeLibKind,
88    pub verbatim: Option<bool>,
89}
90
91impl NativeLib {
92    pub fn has_modifiers(&self) -> bool {
93        self.verbatim.is_some() || self.kind.has_modifiers()
94    }
95}
96
97/// A path that has been canonicalized along with its original, non-canonicalized form
98#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
99pub struct CanonicalizedPath {
100    // Optional since canonicalization can sometimes fail
101    canonicalized: Option<PathBuf>,
102    original: PathBuf,
103}
104
105impl CanonicalizedPath {
106    pub fn new(path: &Path) -> Self {
107        Self { original: path.to_owned(), canonicalized: try_canonicalize(path).ok() }
108    }
109
110    pub fn canonicalized(&self) -> &PathBuf {
111        self.canonicalized.as_ref().unwrap_or(self.original())
112    }
113
114    pub fn original(&self) -> &PathBuf {
115        &self.original
116    }
117}
118
119/// Gets a list of extra command-line flags provided by the user, as strings.
120///
121/// This function is used during ICEs to show more information useful for
122/// debugging, since some ICEs only happens with non-default compiler flags
123/// (and the users don't always report them).
124pub fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
125    const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["-Z", "-C", "--crate-type"];
126
127    const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
128
129    const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
130
131    let mut args = std::env::args_os().map(|arg| arg.to_string_lossy().to_string());
132
133    let mut result = Vec::new();
134    let mut excluded_cargo_defaults = false;
135    while let Some(arg) = args.next() {
136        if let Some(a) = ICE_REPORT_COMPILER_FLAGS.iter().find(|a| arg.starts_with(*a)) {
137            let content = if arg.len() == a.len() {
138                // A space-separated option, like `-C incremental=foo` or `--crate-type rlib`
139                match args.next() {
140                    Some(arg) => arg,
141                    None => continue,
142                }
143            } else if arg.get(a.len()..a.len() + 1) == Some("=") {
144                // An equals option, like `--crate-type=rlib`
145                arg[a.len() + 1..].to_string()
146            } else {
147                // A non-space option, like `-Cincremental=foo`
148                arg[a.len()..].to_string()
149            };
150            let option = content.split_once('=').map(|s| s.0).unwrap_or(&content);
151            if ICE_REPORT_COMPILER_FLAGS_EXCLUDE.iter().any(|exc| option == *exc) {
152                excluded_cargo_defaults = true;
153            } else {
154                result.push(a.to_string());
155                match ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.iter().find(|s| option == **s) {
156                    Some(s) => result.push(format!("{s}=[REDACTED]")),
157                    None => result.push(content),
158                }
159            }
160        }
161    }
162
163    if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
164}
165
166/// Returns whenever rustc was launched by Cargo as opposed to another build system.
167///
168/// To be used in diagnostics to avoid printing Cargo specific suggestions to other
169/// build systems (like Bazel, Buck2, Makefile, ...).
170pub fn was_invoked_from_cargo() -> bool {
171    static FROM_CARGO: OnceLock<bool> = OnceLock::new();
172
173    // To be able to detect Cargo, we use the simplest and least intrusive
174    // way: we check whenever the `CARGO_CRATE_NAME` env is set.
175    //
176    // Note that it is common in Makefiles to define the `CARGO` env even
177    // though we may not have been called by Cargo, so we avoid using it.
178    *FROM_CARGO.get_or_init(|| std::env::var_os("CARGO_CRATE_NAME").is_some())
179}