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