rustc_target/
lib.rs

1//! Some stuff used by rustc that doesn't have many dependencies
2//!
3//! Originally extracted from rustc::back, which was nominally the
4//! compiler 'backend', though LLVM is rustc's backend, so rustc_target
5//! is really just odds-and-ends relating to code gen and linking.
6//! This crate mostly exists to make rustc smaller, so we might put
7//! more 'stuff' here in the future. It does not have a dependency on
8//! LLVM.
9
10// tidy-alphabetical-start
11#![cfg_attr(bootstrap, feature(debug_closure_helpers))]
12#![expect(internal_features)]
13#![feature(iter_intersperse)]
14#![feature(rustc_attrs)]
15// tidy-alphabetical-end
16
17use std::path::{Path, PathBuf};
18
19pub mod asm;
20pub mod callconv;
21pub mod json;
22pub mod spec;
23pub mod target_features;
24
25#[cfg(test)]
26mod tests;
27
28use rustc_abi::HashStableContext;
29
30/// The name of rustc's own place to organize libraries.
31///
32/// Used to be `rustc`, now the default is `rustlib`.
33const RUST_LIB_DIR: &str = "rustlib";
34
35/// Returns a `rustlib` path for this particular target, relative to the provided sysroot.
36///
37/// For example: `target_sysroot_path("/usr", "x86_64-unknown-linux-gnu")` =>
38/// `"lib*/rustlib/x86_64-unknown-linux-gnu"`.
39pub fn relative_target_rustlib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
40    let libdir = find_relative_libdir(sysroot);
41    Path::new(libdir.as_ref()).join(RUST_LIB_DIR).join(target_triple)
42}
43
44/// The name of the directory rustc expects libraries to be located.
45fn find_relative_libdir(sysroot: &Path) -> std::borrow::Cow<'static, str> {
46    // FIXME: This is a quick hack to make the rustc binary able to locate
47    // Rust libraries in Linux environments where libraries might be installed
48    // to lib64/lib32. This would be more foolproof by basing the sysroot off
49    // of the directory where `librustc_driver` is located, rather than
50    // where the rustc binary is.
51    // If --libdir is set during configuration to the value other than
52    // "lib" (i.e., non-default), this value is used (see issue #16552).
53
54    #[cfg(target_pointer_width = "64")]
55    const PRIMARY_LIB_DIR: &str = "lib64";
56
57    #[cfg(target_pointer_width = "32")]
58    const PRIMARY_LIB_DIR: &str = "lib32";
59
60    const SECONDARY_LIB_DIR: &str = "lib";
61
62    match option_env!("CFG_LIBDIR_RELATIVE") {
63        None | Some("lib") => {
64            if sysroot.join(PRIMARY_LIB_DIR).join(RUST_LIB_DIR).exists() {
65                PRIMARY_LIB_DIR.into()
66            } else {
67                SECONDARY_LIB_DIR.into()
68            }
69        }
70        Some(libdir) => libdir.into(),
71    }
72}
73
74macro_rules! target_spec_enum {
75    (
76        $( #[$attr:meta] )*
77        pub enum $Name:ident {
78            $(
79                $( #[$variant_attr:meta] )*
80                $Variant:ident = $string:literal,
81            )*
82        }
83        parse_error_type = $parse_error_type:literal;
84    ) => {
85        $( #[$attr] )*
86        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
87        #[derive(schemars::JsonSchema)]
88        pub enum $Name {
89            $(
90                $( #[$variant_attr] )*
91                #[serde(rename = $string)] // for JSON schema generation only
92                $Variant,
93            )*
94        }
95
96        impl FromStr for $Name {
97            type Err = String;
98
99            fn from_str(s: &str) -> Result<Self, Self::Err> {
100                Ok(match s {
101                    $( $string => Self::$Variant, )*
102                    _ => {
103                        let all = [$( concat!("'", $string, "'") ),*].join(", ");
104                        return Err(format!("invalid {}: '{s}'. allowed values: {all}", $parse_error_type));
105                    }
106                })
107            }
108        }
109
110        impl $Name {
111            pub const ALL: &'static [$Name] = &[ $( $Name::$Variant, )* ];
112            pub fn desc(&self) -> &'static str {
113                match self {
114                    $( Self::$Variant => $string, )*
115                }
116            }
117        }
118
119        crate::target_spec_enum!(@common_impls $Name);
120    };
121
122    (
123        $( #[$attr:meta] )*
124        pub enum $Name:ident {
125            $(
126                $( #[$variant_attr:meta] )*
127                $Variant:ident = $string:literal,
128            )*
129        }
130        $( #[$other_variant_attr:meta] )*
131        other_variant = $OtherVariant:ident;
132    ) => {
133        $( #[$attr] )*
134        #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
135        pub enum $Name {
136            $(
137                $( #[$variant_attr:meta] )*
138                $Variant,
139            )*
140            /// The vast majority of the time, the compiler deals with a fixed
141            /// set of values, so it is convenient for them to be represented in
142            /// an enum. However, it is possible to have arbitrary values in a
143            /// target JSON file (which can be parsed when `--target` is
144            /// specified). This might occur, for example, for an out-of-tree
145            /// codegen backend that supports a value (e.g. architecture or OS)
146            /// that rustc currently doesn't know about. This variant exists as
147            /// an escape hatch for such cases.
148            $( #[$other_variant_attr] )*
149            $OtherVariant(crate::spec::StaticCow<str>),
150        }
151
152        impl schemars::JsonSchema for $Name {
153            fn schema_name() -> std::borrow::Cow<'static, str> {
154                std::borrow::Cow::Borrowed(stringify!($Name))
155            }
156
157            fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
158                schemars::json_schema!({
159                    "type": "string"
160                })
161            }
162        }
163
164        impl FromStr for $Name {
165            type Err = core::convert::Infallible;
166
167            fn from_str(s: &str) -> Result<Self, Self::Err> {
168                Ok(match s {
169                    $( $string => Self::$Variant, )*
170                    _ => Self::$OtherVariant(s.to_owned().into()),
171                })
172            }
173        }
174
175        impl $Name {
176            pub fn desc(&self) -> &str {
177                match self {
178                    $( Self::$Variant => $string, )*
179                    Self::$OtherVariant(name) => name.as_ref(),
180                }
181            }
182        }
183
184        crate::target_spec_enum!(@common_impls $Name);
185    };
186
187    (@common_impls $Name:ident) => {
188        impl crate::json::ToJson for $Name {
189            fn to_json(&self) -> crate::json::Json {
190                self.desc().to_json()
191            }
192        }
193
194        crate::json::serde_deserialize_from_str!($Name);
195
196
197        impl std::fmt::Display for $Name {
198            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199                f.write_str(self.desc())
200            }
201        }
202    };
203}
204use target_spec_enum;