1use core::result::Result;
41use std::borrow::Cow;
42use std::collections::BTreeMap;
43use std::hash::{Hash, Hasher};
44use std::ops::{Deref, DerefMut};
45use std::path::{Path, PathBuf};
46use std::str::FromStr;
47use std::{fmt, io};
48
49use rustc_abi::{
50 Align, CanonAbi, Endian, ExternAbi, Integer, Size, TargetDataLayout, TargetDataLayoutErrors,
51};
52use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
53use rustc_error_messages::{DiagArgValue, IntoDiagArg, into_diag_arg_using_display};
54use rustc_fs_util::try_canonicalize;
55use rustc_macros::{Decodable, Encodable, HashStable_Generic};
56use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
57use rustc_span::{Symbol, kw, sym};
58use serde_json::Value;
59use tracing::debug;
60
61use crate::json::{Json, ToJson};
62use crate::spec::crt_objects::CrtObjects;
63
64pub mod crt_objects;
65
66mod abi_map;
67mod base;
68mod json;
69
70pub use abi_map::{AbiMap, AbiMapping};
71pub use base::apple;
72pub use base::avr::ef_avr_arch;
73
74#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
76pub enum Cc {
77 Yes,
78 No,
79}
80
81#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
83pub enum Lld {
84 Yes,
85 No,
86}
87
88#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
109pub enum LinkerFlavor {
110 Gnu(Cc, Lld),
114 Darwin(Cc, Lld),
117 WasmLld(Cc),
121 Unix(Cc),
125 Msvc(Lld),
127 EmCc,
130 Bpf,
133 Ptx,
135 Llbc,
137}
138
139#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
144pub enum LinkerFlavorCli {
145 Gnu(Cc, Lld),
147 Darwin(Cc, Lld),
148 WasmLld(Cc),
149 Unix(Cc),
150 Msvc(Lld),
152 EmCc,
153 Bpf,
154 Ptx,
155 Llbc,
156
157 Gcc,
159 Ld,
160 Lld(LldFlavor),
161 Em,
162}
163
164impl LinkerFlavorCli {
165 pub fn is_unstable(&self) -> bool {
167 match self {
168 LinkerFlavorCli::Gnu(..)
169 | LinkerFlavorCli::Darwin(..)
170 | LinkerFlavorCli::WasmLld(..)
171 | LinkerFlavorCli::Unix(..)
172 | LinkerFlavorCli::Msvc(Lld::Yes)
173 | LinkerFlavorCli::EmCc
174 | LinkerFlavorCli::Bpf
175 | LinkerFlavorCli::Llbc
176 | LinkerFlavorCli::Ptx => true,
177 LinkerFlavorCli::Gcc
178 | LinkerFlavorCli::Ld
179 | LinkerFlavorCli::Lld(..)
180 | LinkerFlavorCli::Msvc(Lld::No)
181 | LinkerFlavorCli::Em => false,
182 }
183 }
184}
185
186#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
187pub enum LldFlavor {
188 Wasm,
189 Ld64,
190 Ld,
191 Link,
192}
193
194impl LldFlavor {
195 pub fn as_str(&self) -> &'static str {
196 match self {
197 LldFlavor::Wasm => "wasm",
198 LldFlavor::Ld64 => "darwin",
199 LldFlavor::Ld => "gnu",
200 LldFlavor::Link => "link",
201 }
202 }
203}
204
205impl FromStr for LldFlavor {
206 type Err = String;
207
208 fn from_str(s: &str) -> Result<Self, Self::Err> {
209 Ok(match s {
210 "darwin" => LldFlavor::Ld64,
211 "gnu" => LldFlavor::Ld,
212 "link" => LldFlavor::Link,
213 "wasm" => LldFlavor::Wasm,
214 _ => {
215 return Err(
216 "invalid value for lld flavor: '{s}', expected one of 'darwin', 'gnu', 'link', 'wasm'"
217 .into(),
218 );
219 }
220 })
221 }
222}
223
224crate::json::serde_deserialize_from_str!(LldFlavor);
225
226impl ToJson for LldFlavor {
227 fn to_json(&self) -> Json {
228 self.as_str().to_json()
229 }
230}
231
232impl LinkerFlavor {
233 fn from_cli_json(cli: LinkerFlavorCli, lld_flavor: LldFlavor, is_gnu: bool) -> LinkerFlavor {
238 match cli {
239 LinkerFlavorCli::Gnu(cc, lld) => LinkerFlavor::Gnu(cc, lld),
240 LinkerFlavorCli::Darwin(cc, lld) => LinkerFlavor::Darwin(cc, lld),
241 LinkerFlavorCli::WasmLld(cc) => LinkerFlavor::WasmLld(cc),
242 LinkerFlavorCli::Unix(cc) => LinkerFlavor::Unix(cc),
243 LinkerFlavorCli::Msvc(lld) => LinkerFlavor::Msvc(lld),
244 LinkerFlavorCli::EmCc => LinkerFlavor::EmCc,
245 LinkerFlavorCli::Bpf => LinkerFlavor::Bpf,
246 LinkerFlavorCli::Llbc => LinkerFlavor::Llbc,
247 LinkerFlavorCli::Ptx => LinkerFlavor::Ptx,
248
249 LinkerFlavorCli::Gcc => match lld_flavor {
251 LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::Yes, Lld::No),
252 LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::Yes, Lld::No),
253 LldFlavor::Wasm => LinkerFlavor::WasmLld(Cc::Yes),
254 LldFlavor::Ld | LldFlavor::Link => LinkerFlavor::Unix(Cc::Yes),
255 },
256 LinkerFlavorCli::Ld => match lld_flavor {
257 LldFlavor::Ld if is_gnu => LinkerFlavor::Gnu(Cc::No, Lld::No),
258 LldFlavor::Ld64 => LinkerFlavor::Darwin(Cc::No, Lld::No),
259 LldFlavor::Ld | LldFlavor::Wasm | LldFlavor::Link => LinkerFlavor::Unix(Cc::No),
260 },
261 LinkerFlavorCli::Lld(LldFlavor::Ld) => LinkerFlavor::Gnu(Cc::No, Lld::Yes),
262 LinkerFlavorCli::Lld(LldFlavor::Ld64) => LinkerFlavor::Darwin(Cc::No, Lld::Yes),
263 LinkerFlavorCli::Lld(LldFlavor::Wasm) => LinkerFlavor::WasmLld(Cc::No),
264 LinkerFlavorCli::Lld(LldFlavor::Link) => LinkerFlavor::Msvc(Lld::Yes),
265 LinkerFlavorCli::Em => LinkerFlavor::EmCc,
266 }
267 }
268
269 fn to_cli(self) -> LinkerFlavorCli {
271 match self {
272 LinkerFlavor::Gnu(Cc::Yes, _)
273 | LinkerFlavor::Darwin(Cc::Yes, _)
274 | LinkerFlavor::WasmLld(Cc::Yes)
275 | LinkerFlavor::Unix(Cc::Yes) => LinkerFlavorCli::Gcc,
276 LinkerFlavor::Gnu(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld),
277 LinkerFlavor::Darwin(_, Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Ld64),
278 LinkerFlavor::WasmLld(..) => LinkerFlavorCli::Lld(LldFlavor::Wasm),
279 LinkerFlavor::Gnu(..) | LinkerFlavor::Darwin(..) | LinkerFlavor::Unix(..) => {
280 LinkerFlavorCli::Ld
281 }
282 LinkerFlavor::Msvc(Lld::Yes) => LinkerFlavorCli::Lld(LldFlavor::Link),
283 LinkerFlavor::Msvc(..) => LinkerFlavorCli::Msvc(Lld::No),
284 LinkerFlavor::EmCc => LinkerFlavorCli::Em,
285 LinkerFlavor::Bpf => LinkerFlavorCli::Bpf,
286 LinkerFlavor::Llbc => LinkerFlavorCli::Llbc,
287 LinkerFlavor::Ptx => LinkerFlavorCli::Ptx,
288 }
289 }
290
291 fn to_cli_counterpart(self) -> LinkerFlavorCli {
293 match self {
294 LinkerFlavor::Gnu(cc, lld) => LinkerFlavorCli::Gnu(cc, lld),
295 LinkerFlavor::Darwin(cc, lld) => LinkerFlavorCli::Darwin(cc, lld),
296 LinkerFlavor::WasmLld(cc) => LinkerFlavorCli::WasmLld(cc),
297 LinkerFlavor::Unix(cc) => LinkerFlavorCli::Unix(cc),
298 LinkerFlavor::Msvc(lld) => LinkerFlavorCli::Msvc(lld),
299 LinkerFlavor::EmCc => LinkerFlavorCli::EmCc,
300 LinkerFlavor::Bpf => LinkerFlavorCli::Bpf,
301 LinkerFlavor::Llbc => LinkerFlavorCli::Llbc,
302 LinkerFlavor::Ptx => LinkerFlavorCli::Ptx,
303 }
304 }
305
306 fn infer_cli_hints(cli: LinkerFlavorCli) -> (Option<Cc>, Option<Lld>) {
307 match cli {
308 LinkerFlavorCli::Gnu(cc, lld) | LinkerFlavorCli::Darwin(cc, lld) => {
309 (Some(cc), Some(lld))
310 }
311 LinkerFlavorCli::WasmLld(cc) => (Some(cc), Some(Lld::Yes)),
312 LinkerFlavorCli::Unix(cc) => (Some(cc), None),
313 LinkerFlavorCli::Msvc(lld) => (Some(Cc::No), Some(lld)),
314 LinkerFlavorCli::EmCc => (Some(Cc::Yes), Some(Lld::Yes)),
315 LinkerFlavorCli::Bpf | LinkerFlavorCli::Ptx => (None, None),
316 LinkerFlavorCli::Llbc => (None, None),
317
318 LinkerFlavorCli::Gcc => (Some(Cc::Yes), None),
320 LinkerFlavorCli::Ld => (Some(Cc::No), Some(Lld::No)),
321 LinkerFlavorCli::Lld(_) => (Some(Cc::No), Some(Lld::Yes)),
322 LinkerFlavorCli::Em => (Some(Cc::Yes), Some(Lld::Yes)),
323 }
324 }
325
326 fn infer_linker_hints(linker_stem: &str) -> Result<Self, (Option<Cc>, Option<Lld>)> {
327 let stem = linker_stem
329 .rsplit_once('-')
330 .and_then(|(lhs, rhs)| rhs.chars().all(char::is_numeric).then_some(lhs))
331 .unwrap_or(linker_stem);
332
333 if stem == "llvm-bitcode-linker" {
334 Ok(Self::Llbc)
335 } else if stem == "emcc" || stem == "gcc"
337 || stem.ends_with("-gcc")
338 || stem == "g++"
339 || stem.ends_with("-g++")
340 || stem == "clang"
341 || stem.ends_with("-clang")
342 || stem == "clang++"
343 || stem.ends_with("-clang++")
344 {
345 Err((Some(Cc::Yes), Some(Lld::No)))
346 } else if stem == "wasm-ld"
347 || stem.ends_with("-wasm-ld")
348 || stem == "ld.lld"
349 || stem == "lld"
350 || stem == "rust-lld"
351 || stem == "lld-link"
352 {
353 Err((Some(Cc::No), Some(Lld::Yes)))
354 } else if stem == "ld" || stem.ends_with("-ld") || stem == "link" {
355 Err((Some(Cc::No), Some(Lld::No)))
356 } else {
357 Err((None, None))
358 }
359 }
360
361 fn with_hints(self, (cc_hint, lld_hint): (Option<Cc>, Option<Lld>)) -> LinkerFlavor {
362 match self {
363 LinkerFlavor::Gnu(cc, lld) => {
364 LinkerFlavor::Gnu(cc_hint.unwrap_or(cc), lld_hint.unwrap_or(lld))
365 }
366 LinkerFlavor::Darwin(cc, lld) => {
367 LinkerFlavor::Darwin(cc_hint.unwrap_or(cc), lld_hint.unwrap_or(lld))
368 }
369 LinkerFlavor::WasmLld(cc) => LinkerFlavor::WasmLld(cc_hint.unwrap_or(cc)),
370 LinkerFlavor::Unix(cc) => LinkerFlavor::Unix(cc_hint.unwrap_or(cc)),
371 LinkerFlavor::Msvc(lld) => LinkerFlavor::Msvc(lld_hint.unwrap_or(lld)),
372 LinkerFlavor::EmCc | LinkerFlavor::Bpf | LinkerFlavor::Llbc | LinkerFlavor::Ptx => self,
373 }
374 }
375
376 pub fn with_cli_hints(self, cli: LinkerFlavorCli) -> LinkerFlavor {
377 self.with_hints(LinkerFlavor::infer_cli_hints(cli))
378 }
379
380 pub fn with_linker_hints(self, linker_stem: &str) -> LinkerFlavor {
381 match LinkerFlavor::infer_linker_hints(linker_stem) {
382 Ok(linker_flavor) => linker_flavor,
383 Err(hints) => self.with_hints(hints),
384 }
385 }
386
387 pub fn check_compatibility(self, cli: LinkerFlavorCli) -> Option<String> {
388 let compatible = |cli| {
389 match (self, cli) {
391 (LinkerFlavor::Gnu(..), LinkerFlavorCli::Gnu(..))
393 | (LinkerFlavor::Darwin(..), LinkerFlavorCli::Darwin(..))
394 | (LinkerFlavor::WasmLld(..), LinkerFlavorCli::WasmLld(..))
395 | (LinkerFlavor::Unix(..), LinkerFlavorCli::Unix(..))
396 | (LinkerFlavor::Msvc(..), LinkerFlavorCli::Msvc(..))
397 | (LinkerFlavor::EmCc, LinkerFlavorCli::EmCc)
398 | (LinkerFlavor::Bpf, LinkerFlavorCli::Bpf)
399 | (LinkerFlavor::Llbc, LinkerFlavorCli::Llbc)
400 | (LinkerFlavor::Ptx, LinkerFlavorCli::Ptx) => return true,
401 (LinkerFlavor::Ptx, LinkerFlavorCli::Llbc) => return true,
403 _ => {}
404 }
405
406 cli == self.with_cli_hints(cli).to_cli()
408 };
409 (!compatible(cli)).then(|| {
410 LinkerFlavorCli::all()
411 .iter()
412 .filter(|cli| compatible(**cli))
413 .map(|cli| cli.desc())
414 .intersperse(", ")
415 .collect()
416 })
417 }
418
419 pub fn lld_flavor(self) -> LldFlavor {
420 match self {
421 LinkerFlavor::Gnu(..)
422 | LinkerFlavor::Unix(..)
423 | LinkerFlavor::EmCc
424 | LinkerFlavor::Bpf
425 | LinkerFlavor::Llbc
426 | LinkerFlavor::Ptx => LldFlavor::Ld,
427 LinkerFlavor::Darwin(..) => LldFlavor::Ld64,
428 LinkerFlavor::WasmLld(..) => LldFlavor::Wasm,
429 LinkerFlavor::Msvc(..) => LldFlavor::Link,
430 }
431 }
432
433 pub fn is_gnu(self) -> bool {
434 matches!(self, LinkerFlavor::Gnu(..))
435 }
436
437 pub fn uses_lld(self) -> bool {
439 match self {
441 LinkerFlavor::Gnu(_, Lld::Yes)
442 | LinkerFlavor::Darwin(_, Lld::Yes)
443 | LinkerFlavor::WasmLld(..)
444 | LinkerFlavor::EmCc
445 | LinkerFlavor::Msvc(Lld::Yes) => true,
446 LinkerFlavor::Gnu(..)
447 | LinkerFlavor::Darwin(..)
448 | LinkerFlavor::Msvc(_)
449 | LinkerFlavor::Unix(_)
450 | LinkerFlavor::Bpf
451 | LinkerFlavor::Llbc
452 | LinkerFlavor::Ptx => false,
453 }
454 }
455
456 pub fn uses_cc(self) -> bool {
458 match self {
460 LinkerFlavor::Gnu(Cc::Yes, _)
461 | LinkerFlavor::Darwin(Cc::Yes, _)
462 | LinkerFlavor::WasmLld(Cc::Yes)
463 | LinkerFlavor::Unix(Cc::Yes)
464 | LinkerFlavor::EmCc => true,
465 LinkerFlavor::Gnu(..)
466 | LinkerFlavor::Darwin(..)
467 | LinkerFlavor::WasmLld(_)
468 | LinkerFlavor::Msvc(_)
469 | LinkerFlavor::Unix(_)
470 | LinkerFlavor::Bpf
471 | LinkerFlavor::Llbc
472 | LinkerFlavor::Ptx => false,
473 }
474 }
475
476 pub fn with_lld_enabled(self) -> LinkerFlavor {
479 match self {
480 LinkerFlavor::Gnu(cc, Lld::No) => LinkerFlavor::Gnu(cc, Lld::Yes),
481 LinkerFlavor::Darwin(cc, Lld::No) => LinkerFlavor::Darwin(cc, Lld::Yes),
482 LinkerFlavor::Msvc(Lld::No) => LinkerFlavor::Msvc(Lld::Yes),
483 _ => self,
484 }
485 }
486
487 pub fn with_lld_disabled(self) -> LinkerFlavor {
490 match self {
491 LinkerFlavor::Gnu(cc, Lld::Yes) => LinkerFlavor::Gnu(cc, Lld::No),
492 LinkerFlavor::Darwin(cc, Lld::Yes) => LinkerFlavor::Darwin(cc, Lld::No),
493 LinkerFlavor::Msvc(Lld::Yes) => LinkerFlavor::Msvc(Lld::No),
494 _ => self,
495 }
496 }
497}
498
499macro_rules! linker_flavor_cli_impls {
500 ($(($($flavor:tt)*) $string:literal)*) => (
501 impl LinkerFlavorCli {
502 const fn all() -> &'static [LinkerFlavorCli] {
503 &[$($($flavor)*,)*]
504 }
505
506 pub const fn one_of() -> &'static str {
507 concat!("one of: ", $($string, " ",)*)
508 }
509
510 pub fn desc(self) -> &'static str {
511 match self {
512 $($($flavor)* => $string,)*
513 }
514 }
515 }
516
517 impl FromStr for LinkerFlavorCli {
518 type Err = String;
519
520 fn from_str(s: &str) -> Result<LinkerFlavorCli, Self::Err> {
521 Ok(match s {
522 $($string => $($flavor)*,)*
523 _ => return Err(format!("invalid linker flavor, allowed values: {}", Self::one_of())),
524 })
525 }
526 }
527 )
528}
529
530linker_flavor_cli_impls! {
531 (LinkerFlavorCli::Gnu(Cc::No, Lld::No)) "gnu"
532 (LinkerFlavorCli::Gnu(Cc::No, Lld::Yes)) "gnu-lld"
533 (LinkerFlavorCli::Gnu(Cc::Yes, Lld::No)) "gnu-cc"
534 (LinkerFlavorCli::Gnu(Cc::Yes, Lld::Yes)) "gnu-lld-cc"
535 (LinkerFlavorCli::Darwin(Cc::No, Lld::No)) "darwin"
536 (LinkerFlavorCli::Darwin(Cc::No, Lld::Yes)) "darwin-lld"
537 (LinkerFlavorCli::Darwin(Cc::Yes, Lld::No)) "darwin-cc"
538 (LinkerFlavorCli::Darwin(Cc::Yes, Lld::Yes)) "darwin-lld-cc"
539 (LinkerFlavorCli::WasmLld(Cc::No)) "wasm-lld"
540 (LinkerFlavorCli::WasmLld(Cc::Yes)) "wasm-lld-cc"
541 (LinkerFlavorCli::Unix(Cc::No)) "unix"
542 (LinkerFlavorCli::Unix(Cc::Yes)) "unix-cc"
543 (LinkerFlavorCli::Msvc(Lld::Yes)) "msvc-lld"
544 (LinkerFlavorCli::Msvc(Lld::No)) "msvc"
545 (LinkerFlavorCli::EmCc) "em-cc"
546 (LinkerFlavorCli::Bpf) "bpf"
547 (LinkerFlavorCli::Llbc) "llbc"
548 (LinkerFlavorCli::Ptx) "ptx"
549
550 (LinkerFlavorCli::Gcc) "gcc"
552 (LinkerFlavorCli::Ld) "ld"
553 (LinkerFlavorCli::Lld(LldFlavor::Ld)) "ld.lld"
554 (LinkerFlavorCli::Lld(LldFlavor::Ld64)) "ld64.lld"
555 (LinkerFlavorCli::Lld(LldFlavor::Link)) "lld-link"
556 (LinkerFlavorCli::Lld(LldFlavor::Wasm)) "wasm-ld"
557 (LinkerFlavorCli::Em) "em"
558}
559
560crate::json::serde_deserialize_from_str!(LinkerFlavorCli);
561
562impl ToJson for LinkerFlavorCli {
563 fn to_json(&self) -> Json {
564 self.desc().to_json()
565 }
566}
567
568#[derive(Clone, Copy, PartialEq, Debug)]
575pub enum LinkSelfContainedDefault {
576 True,
578
579 False,
581
582 InferredForMusl,
584
585 InferredForMingw,
587
588 WithComponents(LinkSelfContainedComponents),
591}
592
593impl FromStr for LinkSelfContainedDefault {
595 type Err = String;
596
597 fn from_str(s: &str) -> Result<LinkSelfContainedDefault, Self::Err> {
598 Ok(match s {
599 "false" => LinkSelfContainedDefault::False,
600 "true" | "wasm" => LinkSelfContainedDefault::True,
601 "musl" => LinkSelfContainedDefault::InferredForMusl,
602 "mingw" => LinkSelfContainedDefault::InferredForMingw,
603 _ => {
604 return Err(format!(
605 "'{s}' is not a valid `-Clink-self-contained` default. \
606 Use 'false', 'true', 'wasm', 'musl' or 'mingw'",
607 ));
608 }
609 })
610 }
611}
612
613crate::json::serde_deserialize_from_str!(LinkSelfContainedDefault);
614
615impl ToJson for LinkSelfContainedDefault {
616 fn to_json(&self) -> Json {
617 match *self {
618 LinkSelfContainedDefault::WithComponents(components) => {
619 let mut map = BTreeMap::new();
623 map.insert("components", components);
624 map.to_json()
625 }
626
627 LinkSelfContainedDefault::True => "true".to_json(),
629 LinkSelfContainedDefault::False => "false".to_json(),
630 LinkSelfContainedDefault::InferredForMusl => "musl".to_json(),
631 LinkSelfContainedDefault::InferredForMingw => "mingw".to_json(),
632 }
633 }
634}
635
636impl LinkSelfContainedDefault {
637 pub fn is_disabled(self) -> bool {
640 self == LinkSelfContainedDefault::False
641 }
642
643 fn json_key(self) -> &'static str {
647 match self {
648 LinkSelfContainedDefault::WithComponents(_) => "link-self-contained",
649 _ => "crt-objects-fallback",
650 }
651 }
652
653 pub fn with_linker() -> LinkSelfContainedDefault {
656 LinkSelfContainedDefault::WithComponents(LinkSelfContainedComponents::LINKER)
657 }
658}
659
660bitflags::bitflags! {
661 #[derive(Clone, Copy, PartialEq, Eq, Default)]
662 pub struct LinkSelfContainedComponents: u8 {
664 const CRT_OBJECTS = 1 << 0;
666 const LIBC = 1 << 1;
668 const UNWIND = 1 << 2;
670 const LINKER = 1 << 3;
672 const SANITIZERS = 1 << 4;
674 const MINGW = 1 << 5;
676 }
677}
678rustc_data_structures::external_bitflags_debug! { LinkSelfContainedComponents }
679
680impl LinkSelfContainedComponents {
681 pub fn as_str(self) -> Option<&'static str> {
685 Some(match self {
686 LinkSelfContainedComponents::CRT_OBJECTS => "crto",
687 LinkSelfContainedComponents::LIBC => "libc",
688 LinkSelfContainedComponents::UNWIND => "unwind",
689 LinkSelfContainedComponents::LINKER => "linker",
690 LinkSelfContainedComponents::SANITIZERS => "sanitizers",
691 LinkSelfContainedComponents::MINGW => "mingw",
692 _ => return None,
693 })
694 }
695
696 fn all_components() -> [LinkSelfContainedComponents; 6] {
698 [
699 LinkSelfContainedComponents::CRT_OBJECTS,
700 LinkSelfContainedComponents::LIBC,
701 LinkSelfContainedComponents::UNWIND,
702 LinkSelfContainedComponents::LINKER,
703 LinkSelfContainedComponents::SANITIZERS,
704 LinkSelfContainedComponents::MINGW,
705 ]
706 }
707
708 pub fn are_any_components_enabled(self) -> bool {
710 !self.is_empty()
711 }
712
713 pub fn is_linker_enabled(self) -> bool {
715 self.contains(LinkSelfContainedComponents::LINKER)
716 }
717
718 pub fn is_crt_objects_enabled(self) -> bool {
720 self.contains(LinkSelfContainedComponents::CRT_OBJECTS)
721 }
722}
723
724impl FromStr for LinkSelfContainedComponents {
725 type Err = String;
726
727 fn from_str(s: &str) -> Result<Self, Self::Err> {
729 Ok(match s {
730 "crto" => LinkSelfContainedComponents::CRT_OBJECTS,
731 "libc" => LinkSelfContainedComponents::LIBC,
732 "unwind" => LinkSelfContainedComponents::UNWIND,
733 "linker" => LinkSelfContainedComponents::LINKER,
734 "sanitizers" => LinkSelfContainedComponents::SANITIZERS,
735 "mingw" => LinkSelfContainedComponents::MINGW,
736 _ => {
737 return Err(format!(
738 "'{s}' is not a valid link-self-contained component, expected 'crto', 'libc', 'unwind', 'linker', 'sanitizers', 'mingw'"
739 ));
740 }
741 })
742 }
743}
744
745crate::json::serde_deserialize_from_str!(LinkSelfContainedComponents);
746
747impl ToJson for LinkSelfContainedComponents {
748 fn to_json(&self) -> Json {
749 let components: Vec<_> = Self::all_components()
750 .into_iter()
751 .filter(|c| self.contains(*c))
752 .map(|c| {
753 c.as_str().unwrap().to_owned()
756 })
757 .collect();
758
759 components.to_json()
760 }
761}
762
763bitflags::bitflags! {
764 #[derive(Clone, Copy, PartialEq, Eq, Default)]
785 pub struct LinkerFeatures: u8 {
786 const CC = 1 << 0;
788 const LLD = 1 << 1;
790 }
791}
792rustc_data_structures::external_bitflags_debug! { LinkerFeatures }
793
794impl LinkerFeatures {
795 pub fn from_str(s: &str) -> Option<LinkerFeatures> {
797 Some(match s {
798 "cc" => LinkerFeatures::CC,
799 "lld" => LinkerFeatures::LLD,
800 _ => return None,
801 })
802 }
803
804 pub fn as_str(self) -> Option<&'static str> {
808 Some(match self {
809 LinkerFeatures::CC => "cc",
810 LinkerFeatures::LLD => "lld",
811 _ => return None,
812 })
813 }
814
815 pub fn is_lld_enabled(self) -> bool {
817 self.contains(LinkerFeatures::LLD)
818 }
819
820 pub fn is_cc_enabled(self) -> bool {
822 self.contains(LinkerFeatures::CC)
823 }
824}
825
826#[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
827pub enum PanicStrategy {
828 Unwind,
829 Abort,
830}
831
832#[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
833pub enum OnBrokenPipe {
834 Default,
835 Kill,
836 Error,
837 Inherit,
838}
839
840impl PanicStrategy {
841 pub fn desc(&self) -> &str {
842 match *self {
843 PanicStrategy::Unwind => "unwind",
844 PanicStrategy::Abort => "abort",
845 }
846 }
847
848 pub const fn desc_symbol(&self) -> Symbol {
849 match *self {
850 PanicStrategy::Unwind => sym::unwind,
851 PanicStrategy::Abort => sym::abort,
852 }
853 }
854
855 pub const fn all() -> [Symbol; 2] {
856 [Self::Abort.desc_symbol(), Self::Unwind.desc_symbol()]
857 }
858}
859
860impl FromStr for PanicStrategy {
861 type Err = String;
862 fn from_str(s: &str) -> Result<Self, Self::Err> {
863 Ok(match s {
864 "unwind" => PanicStrategy::Unwind,
865 "abort" => PanicStrategy::Abort,
866 _ => {
867 return Err(format!(
868 "'{}' is not a valid value for \
869 panic-strategy. Use 'unwind' or 'abort'.",
870 s
871 ));
872 }
873 })
874 }
875}
876
877crate::json::serde_deserialize_from_str!(PanicStrategy);
878
879impl IntoDiagArg for PanicStrategy {
880 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
881 DiagArgValue::Str(Cow::Owned(self.desc().to_string()))
882 }
883}
884
885impl ToJson for PanicStrategy {
886 fn to_json(&self) -> Json {
887 match *self {
888 PanicStrategy::Abort => "abort".to_json(),
889 PanicStrategy::Unwind => "unwind".to_json(),
890 }
891 }
892}
893
894#[derive(Clone, Copy, Debug, PartialEq, Hash)]
895pub enum RelroLevel {
896 Full,
897 Partial,
898 Off,
899 None,
900}
901
902impl RelroLevel {
903 pub fn desc(&self) -> &str {
904 match *self {
905 RelroLevel::Full => "full",
906 RelroLevel::Partial => "partial",
907 RelroLevel::Off => "off",
908 RelroLevel::None => "none",
909 }
910 }
911}
912
913#[derive(Clone, Copy, Debug, PartialEq, Hash)]
914pub enum SymbolVisibility {
915 Hidden,
916 Protected,
917 Interposable,
918}
919
920impl SymbolVisibility {
921 pub fn desc(&self) -> &str {
922 match *self {
923 SymbolVisibility::Hidden => "hidden",
924 SymbolVisibility::Protected => "protected",
925 SymbolVisibility::Interposable => "interposable",
926 }
927 }
928}
929
930impl FromStr for SymbolVisibility {
931 type Err = String;
932
933 fn from_str(s: &str) -> Result<SymbolVisibility, Self::Err> {
934 match s {
935 "hidden" => Ok(SymbolVisibility::Hidden),
936 "protected" => Ok(SymbolVisibility::Protected),
937 "interposable" => Ok(SymbolVisibility::Interposable),
938 _ => Err(format!(
939 "'{}' is not a valid value for \
940 symbol-visibility. Use 'hidden', 'protected, or 'interposable'.",
941 s
942 )),
943 }
944 }
945}
946
947crate::json::serde_deserialize_from_str!(SymbolVisibility);
948
949impl ToJson for SymbolVisibility {
950 fn to_json(&self) -> Json {
951 match *self {
952 SymbolVisibility::Hidden => "hidden".to_json(),
953 SymbolVisibility::Protected => "protected".to_json(),
954 SymbolVisibility::Interposable => "interposable".to_json(),
955 }
956 }
957}
958
959impl FromStr for RelroLevel {
960 type Err = String;
961
962 fn from_str(s: &str) -> Result<RelroLevel, Self::Err> {
963 match s {
964 "full" => Ok(RelroLevel::Full),
965 "partial" => Ok(RelroLevel::Partial),
966 "off" => Ok(RelroLevel::Off),
967 "none" => Ok(RelroLevel::None),
968 _ => Err(format!(
969 "'{}' is not a valid value for \
970 relro-level. Use 'full', 'partial, 'off', or 'none'.",
971 s
972 )),
973 }
974 }
975}
976
977crate::json::serde_deserialize_from_str!(RelroLevel);
978
979impl ToJson for RelroLevel {
980 fn to_json(&self) -> Json {
981 match *self {
982 RelroLevel::Full => "full".to_json(),
983 RelroLevel::Partial => "partial".to_json(),
984 RelroLevel::Off => "off".to_json(),
985 RelroLevel::None => "None".to_json(),
986 }
987 }
988}
989
990#[derive(Clone, Debug, PartialEq, Hash)]
991pub enum SmallDataThresholdSupport {
992 None,
993 DefaultForArch,
994 LlvmModuleFlag(StaticCow<str>),
995 LlvmArg(StaticCow<str>),
996}
997
998impl FromStr for SmallDataThresholdSupport {
999 type Err = String;
1000
1001 fn from_str(s: &str) -> Result<Self, Self::Err> {
1002 if s == "none" {
1003 Ok(Self::None)
1004 } else if s == "default-for-arch" {
1005 Ok(Self::DefaultForArch)
1006 } else if let Some(flag) = s.strip_prefix("llvm-module-flag=") {
1007 Ok(Self::LlvmModuleFlag(flag.to_string().into()))
1008 } else if let Some(arg) = s.strip_prefix("llvm-arg=") {
1009 Ok(Self::LlvmArg(arg.to_string().into()))
1010 } else {
1011 Err(format!("'{s}' is not a valid value for small-data-threshold-support."))
1012 }
1013 }
1014}
1015
1016crate::json::serde_deserialize_from_str!(SmallDataThresholdSupport);
1017
1018impl ToJson for SmallDataThresholdSupport {
1019 fn to_json(&self) -> Value {
1020 match self {
1021 Self::None => "none".to_json(),
1022 Self::DefaultForArch => "default-for-arch".to_json(),
1023 Self::LlvmModuleFlag(flag) => format!("llvm-module-flag={flag}").to_json(),
1024 Self::LlvmArg(arg) => format!("llvm-arg={arg}").to_json(),
1025 }
1026 }
1027}
1028
1029#[derive(Clone, Copy, Debug, PartialEq, Hash)]
1030pub enum MergeFunctions {
1031 Disabled,
1032 Trampolines,
1033 Aliases,
1034}
1035
1036impl MergeFunctions {
1037 pub fn desc(&self) -> &str {
1038 match *self {
1039 MergeFunctions::Disabled => "disabled",
1040 MergeFunctions::Trampolines => "trampolines",
1041 MergeFunctions::Aliases => "aliases",
1042 }
1043 }
1044}
1045
1046impl FromStr for MergeFunctions {
1047 type Err = String;
1048
1049 fn from_str(s: &str) -> Result<MergeFunctions, Self::Err> {
1050 match s {
1051 "disabled" => Ok(MergeFunctions::Disabled),
1052 "trampolines" => Ok(MergeFunctions::Trampolines),
1053 "aliases" => Ok(MergeFunctions::Aliases),
1054 _ => Err(format!(
1055 "'{}' is not a valid value for \
1056 merge-functions. Use 'disabled', \
1057 'trampolines', or 'aliases'.",
1058 s
1059 )),
1060 }
1061 }
1062}
1063
1064crate::json::serde_deserialize_from_str!(MergeFunctions);
1065
1066impl ToJson for MergeFunctions {
1067 fn to_json(&self) -> Json {
1068 match *self {
1069 MergeFunctions::Disabled => "disabled".to_json(),
1070 MergeFunctions::Trampolines => "trampolines".to_json(),
1071 MergeFunctions::Aliases => "aliases".to_json(),
1072 }
1073 }
1074}
1075
1076#[derive(Clone, Copy, PartialEq, Hash, Debug)]
1077pub enum RelocModel {
1078 Static,
1079 Pic,
1080 Pie,
1081 DynamicNoPic,
1082 Ropi,
1083 Rwpi,
1084 RopiRwpi,
1085}
1086
1087impl RelocModel {
1088 pub fn desc(&self) -> &str {
1089 match *self {
1090 RelocModel::Static => "static",
1091 RelocModel::Pic => "pic",
1092 RelocModel::Pie => "pie",
1093 RelocModel::DynamicNoPic => "dynamic-no-pic",
1094 RelocModel::Ropi => "ropi",
1095 RelocModel::Rwpi => "rwpi",
1096 RelocModel::RopiRwpi => "ropi-rwpi",
1097 }
1098 }
1099 pub const fn desc_symbol(&self) -> Symbol {
1100 match *self {
1101 RelocModel::Static => kw::Static,
1102 RelocModel::Pic => sym::pic,
1103 RelocModel::Pie => sym::pie,
1104 RelocModel::DynamicNoPic => sym::dynamic_no_pic,
1105 RelocModel::Ropi => sym::ropi,
1106 RelocModel::Rwpi => sym::rwpi,
1107 RelocModel::RopiRwpi => sym::ropi_rwpi,
1108 }
1109 }
1110
1111 pub const fn all() -> [Symbol; 7] {
1112 [
1113 RelocModel::Static.desc_symbol(),
1114 RelocModel::Pic.desc_symbol(),
1115 RelocModel::Pie.desc_symbol(),
1116 RelocModel::DynamicNoPic.desc_symbol(),
1117 RelocModel::Ropi.desc_symbol(),
1118 RelocModel::Rwpi.desc_symbol(),
1119 RelocModel::RopiRwpi.desc_symbol(),
1120 ]
1121 }
1122}
1123
1124impl FromStr for RelocModel {
1125 type Err = String;
1126
1127 fn from_str(s: &str) -> Result<RelocModel, Self::Err> {
1128 Ok(match s {
1129 "static" => RelocModel::Static,
1130 "pic" => RelocModel::Pic,
1131 "pie" => RelocModel::Pie,
1132 "dynamic-no-pic" => RelocModel::DynamicNoPic,
1133 "ropi" => RelocModel::Ropi,
1134 "rwpi" => RelocModel::Rwpi,
1135 "ropi-rwpi" => RelocModel::RopiRwpi,
1136 _ => {
1137 return Err(format!(
1138 "invalid relocation model '{s}'.
1139 Run `rustc --print relocation-models` to \
1140 see the list of supported values.'"
1141 ));
1142 }
1143 })
1144 }
1145}
1146
1147crate::json::serde_deserialize_from_str!(RelocModel);
1148
1149impl ToJson for RelocModel {
1150 fn to_json(&self) -> Json {
1151 self.desc().to_json()
1152 }
1153}
1154
1155#[derive(Clone, Copy, PartialEq, Hash, Debug)]
1156pub enum CodeModel {
1157 Tiny,
1158 Small,
1159 Kernel,
1160 Medium,
1161 Large,
1162}
1163
1164impl FromStr for CodeModel {
1165 type Err = String;
1166
1167 fn from_str(s: &str) -> Result<CodeModel, Self::Err> {
1168 Ok(match s {
1169 "tiny" => CodeModel::Tiny,
1170 "small" => CodeModel::Small,
1171 "kernel" => CodeModel::Kernel,
1172 "medium" => CodeModel::Medium,
1173 "large" => CodeModel::Large,
1174 _ => {
1175 return Err(format!(
1176 "'{s}' is not a valid code model. \
1177 Run `rustc --print code-models` to \
1178 see the list of supported values."
1179 ));
1180 }
1181 })
1182 }
1183}
1184
1185crate::json::serde_deserialize_from_str!(CodeModel);
1186
1187impl ToJson for CodeModel {
1188 fn to_json(&self) -> Json {
1189 match *self {
1190 CodeModel::Tiny => "tiny",
1191 CodeModel::Small => "small",
1192 CodeModel::Kernel => "kernel",
1193 CodeModel::Medium => "medium",
1194 CodeModel::Large => "large",
1195 }
1196 .to_json()
1197 }
1198}
1199
1200#[derive(Clone, Copy, PartialEq, Hash, Debug)]
1202pub enum FloatAbi {
1203 Soft,
1204 Hard,
1205}
1206
1207impl FromStr for FloatAbi {
1208 type Err = String;
1209
1210 fn from_str(s: &str) -> Result<FloatAbi, Self::Err> {
1211 Ok(match s {
1212 "soft" => FloatAbi::Soft,
1213 "hard" => FloatAbi::Hard,
1214 _ => {
1215 return Err(format!(
1216 "'{}' is not a valid value for \
1217 llvm-floatabi. Use 'soft' or 'hard'.",
1218 s
1219 ));
1220 }
1221 })
1222 }
1223}
1224
1225crate::json::serde_deserialize_from_str!(FloatAbi);
1226
1227impl ToJson for FloatAbi {
1228 fn to_json(&self) -> Json {
1229 match *self {
1230 FloatAbi::Soft => "soft",
1231 FloatAbi::Hard => "hard",
1232 }
1233 .to_json()
1234 }
1235}
1236
1237#[derive(Clone, Copy, PartialEq, Hash, Debug)]
1239pub enum RustcAbi {
1240 X86Sse2,
1242 X86Softfloat,
1244}
1245
1246impl FromStr for RustcAbi {
1247 type Err = String;
1248
1249 fn from_str(s: &str) -> Result<RustcAbi, Self::Err> {
1250 Ok(match s {
1251 "x86-sse2" => RustcAbi::X86Sse2,
1252 "x86-softfloat" => RustcAbi::X86Softfloat,
1253 _ => {
1254 return Err(format!(
1255 "'{s}' is not a valid value for rustc-abi. \
1256 Use 'x86-softfloat' or leave the field unset."
1257 ));
1258 }
1259 })
1260 }
1261}
1262
1263crate::json::serde_deserialize_from_str!(RustcAbi);
1264
1265impl ToJson for RustcAbi {
1266 fn to_json(&self) -> Json {
1267 match *self {
1268 RustcAbi::X86Sse2 => "x86-sse2",
1269 RustcAbi::X86Softfloat => "x86-softfloat",
1270 }
1271 .to_json()
1272 }
1273}
1274
1275#[derive(Clone, Copy, PartialEq, Hash, Debug)]
1276pub enum TlsModel {
1277 GeneralDynamic,
1278 LocalDynamic,
1279 InitialExec,
1280 LocalExec,
1281 Emulated,
1282}
1283
1284impl FromStr for TlsModel {
1285 type Err = String;
1286
1287 fn from_str(s: &str) -> Result<TlsModel, Self::Err> {
1288 Ok(match s {
1289 "global-dynamic" => TlsModel::GeneralDynamic,
1292 "local-dynamic" => TlsModel::LocalDynamic,
1293 "initial-exec" => TlsModel::InitialExec,
1294 "local-exec" => TlsModel::LocalExec,
1295 "emulated" => TlsModel::Emulated,
1296 _ => {
1297 return Err(format!(
1298 "'{s}' is not a valid TLS model. \
1299 Run `rustc --print tls-models` to \
1300 see the list of supported values."
1301 ));
1302 }
1303 })
1304 }
1305}
1306
1307crate::json::serde_deserialize_from_str!(TlsModel);
1308
1309impl ToJson for TlsModel {
1310 fn to_json(&self) -> Json {
1311 match *self {
1312 TlsModel::GeneralDynamic => "global-dynamic",
1313 TlsModel::LocalDynamic => "local-dynamic",
1314 TlsModel::InitialExec => "initial-exec",
1315 TlsModel::LocalExec => "local-exec",
1316 TlsModel::Emulated => "emulated",
1317 }
1318 .to_json()
1319 }
1320}
1321
1322#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1324pub enum LinkOutputKind {
1325 DynamicNoPicExe,
1327 DynamicPicExe,
1329 StaticNoPicExe,
1331 StaticPicExe,
1333 DynamicDylib,
1335 StaticDylib,
1337 WasiReactorExe,
1339}
1340
1341impl LinkOutputKind {
1342 fn as_str(&self) -> &'static str {
1343 match self {
1344 LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
1345 LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
1346 LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
1347 LinkOutputKind::StaticPicExe => "static-pic-exe",
1348 LinkOutputKind::DynamicDylib => "dynamic-dylib",
1349 LinkOutputKind::StaticDylib => "static-dylib",
1350 LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
1351 }
1352 }
1353
1354 pub fn can_link_dylib(self) -> bool {
1355 match self {
1356 LinkOutputKind::StaticNoPicExe | LinkOutputKind::StaticPicExe => false,
1357 LinkOutputKind::DynamicNoPicExe
1358 | LinkOutputKind::DynamicPicExe
1359 | LinkOutputKind::DynamicDylib
1360 | LinkOutputKind::StaticDylib
1361 | LinkOutputKind::WasiReactorExe => true,
1362 }
1363 }
1364}
1365
1366impl FromStr for LinkOutputKind {
1367 type Err = String;
1368
1369 fn from_str(s: &str) -> Result<LinkOutputKind, Self::Err> {
1370 Ok(match s {
1371 "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
1372 "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
1373 "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
1374 "static-pic-exe" => LinkOutputKind::StaticPicExe,
1375 "dynamic-dylib" => LinkOutputKind::DynamicDylib,
1376 "static-dylib" => LinkOutputKind::StaticDylib,
1377 "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
1378 _ => {
1379 return Err(format!(
1380 "invalid value for CRT object kind. \
1381 Use '(dynamic,static)-(nopic,pic)-exe' or \
1382 '(dynamic,static)-dylib' or 'wasi-reactor-exe'"
1383 ));
1384 }
1385 })
1386 }
1387}
1388
1389crate::json::serde_deserialize_from_str!(LinkOutputKind);
1390
1391impl fmt::Display for LinkOutputKind {
1392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1393 f.write_str(self.as_str())
1394 }
1395}
1396
1397pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<StaticCow<str>>>;
1398pub type LinkArgsCli = BTreeMap<LinkerFlavorCli, Vec<StaticCow<str>>>;
1399
1400#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
1405pub enum DebuginfoKind {
1406 #[default]
1408 Dwarf,
1409 DwarfDsym,
1411 Pdb,
1413}
1414
1415impl DebuginfoKind {
1416 fn as_str(&self) -> &'static str {
1417 match self {
1418 DebuginfoKind::Dwarf => "dwarf",
1419 DebuginfoKind::DwarfDsym => "dwarf-dsym",
1420 DebuginfoKind::Pdb => "pdb",
1421 }
1422 }
1423}
1424
1425impl FromStr for DebuginfoKind {
1426 type Err = String;
1427
1428 fn from_str(s: &str) -> Result<Self, Self::Err> {
1429 Ok(match s {
1430 "dwarf" => DebuginfoKind::Dwarf,
1431 "dwarf-dsym" => DebuginfoKind::DwarfDsym,
1432 "pdb" => DebuginfoKind::Pdb,
1433 _ => {
1434 return Err(format!(
1435 "'{s}' is not a valid value for debuginfo-kind. Use 'dwarf', \
1436 'dwarf-dsym' or 'pdb'."
1437 ));
1438 }
1439 })
1440 }
1441}
1442
1443crate::json::serde_deserialize_from_str!(DebuginfoKind);
1444
1445impl ToJson for DebuginfoKind {
1446 fn to_json(&self) -> Json {
1447 self.as_str().to_json()
1448 }
1449}
1450
1451impl fmt::Display for DebuginfoKind {
1452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1453 f.write_str(self.as_str())
1454 }
1455}
1456
1457#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
1458pub enum SplitDebuginfo {
1459 #[default]
1467 Off,
1468
1469 Packed,
1476
1477 Unpacked,
1484}
1485
1486impl SplitDebuginfo {
1487 fn as_str(&self) -> &'static str {
1488 match self {
1489 SplitDebuginfo::Off => "off",
1490 SplitDebuginfo::Packed => "packed",
1491 SplitDebuginfo::Unpacked => "unpacked",
1492 }
1493 }
1494}
1495
1496impl FromStr for SplitDebuginfo {
1497 type Err = String;
1498
1499 fn from_str(s: &str) -> Result<Self, Self::Err> {
1500 Ok(match s {
1501 "off" => SplitDebuginfo::Off,
1502 "unpacked" => SplitDebuginfo::Unpacked,
1503 "packed" => SplitDebuginfo::Packed,
1504 _ => {
1505 return Err(format!(
1506 "'{s}' is not a valid value for \
1507 split-debuginfo. Use 'off', 'unpacked', or 'packed'.",
1508 ));
1509 }
1510 })
1511 }
1512}
1513
1514crate::json::serde_deserialize_from_str!(SplitDebuginfo);
1515
1516impl ToJson for SplitDebuginfo {
1517 fn to_json(&self) -> Json {
1518 self.as_str().to_json()
1519 }
1520}
1521
1522impl fmt::Display for SplitDebuginfo {
1523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1524 f.write_str(self.as_str())
1525 }
1526}
1527
1528into_diag_arg_using_display!(SplitDebuginfo);
1529
1530#[derive(Clone, Debug, PartialEq, Eq, serde_derive::Deserialize)]
1531#[serde(tag = "kind")]
1532#[serde(rename_all = "kebab-case")]
1533pub enum StackProbeType {
1534 None,
1536 Inline,
1540 Call,
1542 InlineOrCall {
1545 #[serde(rename = "min-llvm-version-for-inline")]
1546 min_llvm_version_for_inline: (u32, u32, u32),
1547 },
1548}
1549
1550impl ToJson for StackProbeType {
1551 fn to_json(&self) -> Json {
1552 Json::Object(match self {
1553 StackProbeType::None => {
1554 [(String::from("kind"), "none".to_json())].into_iter().collect()
1555 }
1556 StackProbeType::Inline => {
1557 [(String::from("kind"), "inline".to_json())].into_iter().collect()
1558 }
1559 StackProbeType::Call => {
1560 [(String::from("kind"), "call".to_json())].into_iter().collect()
1561 }
1562 StackProbeType::InlineOrCall { min_llvm_version_for_inline: (maj, min, patch) } => [
1563 (String::from("kind"), "inline-or-call".to_json()),
1564 (
1565 String::from("min-llvm-version-for-inline"),
1566 Json::Array(vec![maj.to_json(), min.to_json(), patch.to_json()]),
1567 ),
1568 ]
1569 .into_iter()
1570 .collect(),
1571 })
1572 }
1573}
1574
1575#[derive(Default, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, HashStable_Generic)]
1576pub struct SanitizerSet(u16);
1577bitflags::bitflags! {
1578 impl SanitizerSet: u16 {
1579 const ADDRESS = 1 << 0;
1580 const LEAK = 1 << 1;
1581 const MEMORY = 1 << 2;
1582 const THREAD = 1 << 3;
1583 const HWADDRESS = 1 << 4;
1584 const CFI = 1 << 5;
1585 const MEMTAG = 1 << 6;
1586 const SHADOWCALLSTACK = 1 << 7;
1587 const KCFI = 1 << 8;
1588 const KERNELADDRESS = 1 << 9;
1589 const SAFESTACK = 1 << 10;
1590 const DATAFLOW = 1 << 11;
1591 }
1592}
1593rustc_data_structures::external_bitflags_debug! { SanitizerSet }
1594
1595impl SanitizerSet {
1596 const MUTUALLY_EXCLUSIVE: &'static [(SanitizerSet, SanitizerSet)] = &[
1599 (SanitizerSet::ADDRESS, SanitizerSet::MEMORY),
1600 (SanitizerSet::ADDRESS, SanitizerSet::THREAD),
1601 (SanitizerSet::ADDRESS, SanitizerSet::HWADDRESS),
1602 (SanitizerSet::ADDRESS, SanitizerSet::MEMTAG),
1603 (SanitizerSet::ADDRESS, SanitizerSet::KERNELADDRESS),
1604 (SanitizerSet::ADDRESS, SanitizerSet::SAFESTACK),
1605 (SanitizerSet::LEAK, SanitizerSet::MEMORY),
1606 (SanitizerSet::LEAK, SanitizerSet::THREAD),
1607 (SanitizerSet::LEAK, SanitizerSet::KERNELADDRESS),
1608 (SanitizerSet::LEAK, SanitizerSet::SAFESTACK),
1609 (SanitizerSet::MEMORY, SanitizerSet::THREAD),
1610 (SanitizerSet::MEMORY, SanitizerSet::HWADDRESS),
1611 (SanitizerSet::MEMORY, SanitizerSet::KERNELADDRESS),
1612 (SanitizerSet::MEMORY, SanitizerSet::SAFESTACK),
1613 (SanitizerSet::THREAD, SanitizerSet::HWADDRESS),
1614 (SanitizerSet::THREAD, SanitizerSet::KERNELADDRESS),
1615 (SanitizerSet::THREAD, SanitizerSet::SAFESTACK),
1616 (SanitizerSet::HWADDRESS, SanitizerSet::MEMTAG),
1617 (SanitizerSet::HWADDRESS, SanitizerSet::KERNELADDRESS),
1618 (SanitizerSet::HWADDRESS, SanitizerSet::SAFESTACK),
1619 (SanitizerSet::CFI, SanitizerSet::KCFI),
1620 (SanitizerSet::MEMTAG, SanitizerSet::KERNELADDRESS),
1621 (SanitizerSet::KERNELADDRESS, SanitizerSet::SAFESTACK),
1622 ];
1623
1624 pub fn as_str(self) -> Option<&'static str> {
1628 Some(match self {
1629 SanitizerSet::ADDRESS => "address",
1630 SanitizerSet::CFI => "cfi",
1631 SanitizerSet::DATAFLOW => "dataflow",
1632 SanitizerSet::KCFI => "kcfi",
1633 SanitizerSet::KERNELADDRESS => "kernel-address",
1634 SanitizerSet::LEAK => "leak",
1635 SanitizerSet::MEMORY => "memory",
1636 SanitizerSet::MEMTAG => "memtag",
1637 SanitizerSet::SAFESTACK => "safestack",
1638 SanitizerSet::SHADOWCALLSTACK => "shadow-call-stack",
1639 SanitizerSet::THREAD => "thread",
1640 SanitizerSet::HWADDRESS => "hwaddress",
1641 _ => return None,
1642 })
1643 }
1644
1645 pub fn mutually_exclusive(self) -> Option<(SanitizerSet, SanitizerSet)> {
1646 Self::MUTUALLY_EXCLUSIVE
1647 .into_iter()
1648 .find(|&(a, b)| self.contains(*a) && self.contains(*b))
1649 .copied()
1650 }
1651}
1652
1653impl fmt::Display for SanitizerSet {
1655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1656 let mut first = true;
1657 for s in *self {
1658 let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {s:?}"));
1659 if !first {
1660 f.write_str(", ")?;
1661 }
1662 f.write_str(name)?;
1663 first = false;
1664 }
1665 Ok(())
1666 }
1667}
1668
1669impl FromStr for SanitizerSet {
1670 type Err = String;
1671 fn from_str(s: &str) -> Result<Self, Self::Err> {
1672 Ok(match s {
1673 "address" => SanitizerSet::ADDRESS,
1674 "cfi" => SanitizerSet::CFI,
1675 "dataflow" => SanitizerSet::DATAFLOW,
1676 "kcfi" => SanitizerSet::KCFI,
1677 "kernel-address" => SanitizerSet::KERNELADDRESS,
1678 "leak" => SanitizerSet::LEAK,
1679 "memory" => SanitizerSet::MEMORY,
1680 "memtag" => SanitizerSet::MEMTAG,
1681 "safestack" => SanitizerSet::SAFESTACK,
1682 "shadow-call-stack" => SanitizerSet::SHADOWCALLSTACK,
1683 "thread" => SanitizerSet::THREAD,
1684 "hwaddress" => SanitizerSet::HWADDRESS,
1685 s => return Err(format!("unknown sanitizer {s}")),
1686 })
1687 }
1688}
1689
1690crate::json::serde_deserialize_from_str!(SanitizerSet);
1691
1692impl ToJson for SanitizerSet {
1693 fn to_json(&self) -> Json {
1694 self.into_iter()
1695 .map(|v| Some(v.as_str()?.to_json()))
1696 .collect::<Option<Vec<_>>>()
1697 .unwrap_or_default()
1698 .to_json()
1699 }
1700}
1701
1702#[derive(Clone, Copy, PartialEq, Hash, Debug)]
1703pub enum FramePointer {
1704 Always,
1706 NonLeaf,
1709 MayOmit,
1713}
1714
1715impl FramePointer {
1716 #[inline]
1719 pub fn ratchet(&mut self, rhs: FramePointer) -> FramePointer {
1720 *self = match (*self, rhs) {
1721 (FramePointer::Always, _) | (_, FramePointer::Always) => FramePointer::Always,
1722 (FramePointer::NonLeaf, _) | (_, FramePointer::NonLeaf) => FramePointer::NonLeaf,
1723 _ => FramePointer::MayOmit,
1724 };
1725 *self
1726 }
1727}
1728
1729impl FromStr for FramePointer {
1730 type Err = String;
1731 fn from_str(s: &str) -> Result<Self, Self::Err> {
1732 Ok(match s {
1733 "always" => Self::Always,
1734 "non-leaf" => Self::NonLeaf,
1735 "may-omit" => Self::MayOmit,
1736 _ => return Err(format!("'{s}' is not a valid value for frame-pointer")),
1737 })
1738 }
1739}
1740
1741crate::json::serde_deserialize_from_str!(FramePointer);
1742
1743impl ToJson for FramePointer {
1744 fn to_json(&self) -> Json {
1745 match *self {
1746 Self::Always => "always",
1747 Self::NonLeaf => "non-leaf",
1748 Self::MayOmit => "may-omit",
1749 }
1750 .to_json()
1751 }
1752}
1753
1754#[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
1756pub enum StackProtector {
1757 None,
1759
1760 Basic,
1765
1766 Strong,
1771
1772 All,
1774}
1775
1776impl StackProtector {
1777 fn as_str(&self) -> &'static str {
1778 match self {
1779 StackProtector::None => "none",
1780 StackProtector::Basic => "basic",
1781 StackProtector::Strong => "strong",
1782 StackProtector::All => "all",
1783 }
1784 }
1785}
1786
1787impl FromStr for StackProtector {
1788 type Err = ();
1789
1790 fn from_str(s: &str) -> Result<StackProtector, ()> {
1791 Ok(match s {
1792 "none" => StackProtector::None,
1793 "basic" => StackProtector::Basic,
1794 "strong" => StackProtector::Strong,
1795 "all" => StackProtector::All,
1796 _ => return Err(()),
1797 })
1798 }
1799}
1800
1801impl fmt::Display for StackProtector {
1802 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1803 f.write_str(self.as_str())
1804 }
1805}
1806
1807into_diag_arg_using_display!(StackProtector);
1808
1809#[derive(PartialEq, Clone, Debug)]
1810pub enum BinaryFormat {
1811 Coff,
1812 Elf,
1813 MachO,
1814 Wasm,
1815 Xcoff,
1816}
1817
1818impl BinaryFormat {
1819 pub fn to_object(&self) -> object::BinaryFormat {
1821 match self {
1822 Self::Coff => object::BinaryFormat::Coff,
1823 Self::Elf => object::BinaryFormat::Elf,
1824 Self::MachO => object::BinaryFormat::MachO,
1825 Self::Wasm => object::BinaryFormat::Wasm,
1826 Self::Xcoff => object::BinaryFormat::Xcoff,
1827 }
1828 }
1829}
1830
1831impl FromStr for BinaryFormat {
1832 type Err = String;
1833 fn from_str(s: &str) -> Result<Self, Self::Err> {
1834 match s {
1835 "coff" => Ok(Self::Coff),
1836 "elf" => Ok(Self::Elf),
1837 "mach-o" => Ok(Self::MachO),
1838 "wasm" => Ok(Self::Wasm),
1839 "xcoff" => Ok(Self::Xcoff),
1840 _ => Err(format!(
1841 "'{s}' is not a valid value for binary_format. \
1842 Use 'coff', 'elf', 'mach-o', 'wasm' or 'xcoff' "
1843 )),
1844 }
1845 }
1846}
1847
1848crate::json::serde_deserialize_from_str!(BinaryFormat);
1849
1850impl ToJson for BinaryFormat {
1851 fn to_json(&self) -> Json {
1852 match self {
1853 Self::Coff => "coff",
1854 Self::Elf => "elf",
1855 Self::MachO => "mach-o",
1856 Self::Wasm => "wasm",
1857 Self::Xcoff => "xcoff",
1858 }
1859 .to_json()
1860 }
1861}
1862
1863impl ToJson for Align {
1864 fn to_json(&self) -> Json {
1865 self.bits().to_json()
1866 }
1867}
1868
1869macro_rules! supported_targets {
1870 ( $(($tuple:literal, $module:ident),)+ ) => {
1871 mod targets {
1872 $(pub(crate) mod $module;)+
1873 }
1874
1875 pub static TARGETS: &[&str] = &[$($tuple),+];
1877
1878 fn load_builtin(target: &str) -> Option<Target> {
1879 let t = match target {
1880 $( $tuple => targets::$module::target(), )+
1881 _ => return None,
1882 };
1883 debug!("got builtin target: {:?}", t);
1884 Some(t)
1885 }
1886
1887 fn load_all_builtins() -> impl Iterator<Item = Target> {
1888 [
1889 $( targets::$module::target, )+
1890 ]
1891 .into_iter()
1892 .map(|f| f())
1893 }
1894
1895 #[cfg(test)]
1896 mod tests {
1897 $(
1899 #[test] fn $module() {
1901 crate::spec::targets::$module::target().test_target()
1902 }
1903 )+
1904 }
1905 };
1906}
1907
1908supported_targets! {
1909 ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
1910 ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
1911 ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
1912 ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
1913 ("loongarch64-unknown-linux-gnu", loongarch64_unknown_linux_gnu),
1914 ("loongarch64-unknown-linux-musl", loongarch64_unknown_linux_musl),
1915 ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
1916 ("m68k-unknown-none-elf", m68k_unknown_none_elf),
1917 ("csky-unknown-linux-gnuabiv2", csky_unknown_linux_gnuabiv2),
1918 ("csky-unknown-linux-gnuabiv2hf", csky_unknown_linux_gnuabiv2hf),
1919 ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
1920 ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
1921 ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
1922 ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
1923 ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
1924 ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
1925 ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
1926 ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
1927 ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
1928 ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
1929 ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
1930 ("powerpc-unknown-linux-muslspe", powerpc_unknown_linux_muslspe),
1931 ("powerpc64-ibm-aix", powerpc64_ibm_aix),
1932 ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
1933 ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
1934 ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
1935 ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
1936 ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
1937 ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
1938 ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
1939 ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
1940 ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
1941 ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
1942 ("armeb-unknown-linux-gnueabi", armeb_unknown_linux_gnueabi),
1943 ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
1944 ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
1945 ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
1946 ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
1947 ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
1948 ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
1949 ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
1950 ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
1951 ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
1952 ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
1953 ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
1954 ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
1955 ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
1956 ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
1957 ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
1958 ("i686-unknown-linux-musl", i686_unknown_linux_musl),
1959 ("i586-unknown-linux-musl", i586_unknown_linux_musl),
1960 ("mips-unknown-linux-musl", mips_unknown_linux_musl),
1961 ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
1962 ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
1963 ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
1964 ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
1965 ("hexagon-unknown-none-elf", hexagon_unknown_none_elf),
1966
1967 ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
1968 ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
1969
1970 ("i686-linux-android", i686_linux_android),
1971 ("x86_64-linux-android", x86_64_linux_android),
1972 ("arm-linux-androideabi", arm_linux_androideabi),
1973 ("armv7-linux-androideabi", armv7_linux_androideabi),
1974 ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
1975 ("aarch64-linux-android", aarch64_linux_android),
1976 ("riscv64-linux-android", riscv64_linux_android),
1977
1978 ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
1979 ("armv6-unknown-freebsd", armv6_unknown_freebsd),
1980 ("armv7-unknown-freebsd", armv7_unknown_freebsd),
1981 ("i686-unknown-freebsd", i686_unknown_freebsd),
1982 ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
1983 ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
1984 ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
1985 ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
1986 ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
1987
1988 ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
1989
1990 ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
1991 ("i686-unknown-openbsd", i686_unknown_openbsd),
1992 ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
1993 ("powerpc64-unknown-openbsd", powerpc64_unknown_openbsd),
1994 ("riscv64gc-unknown-openbsd", riscv64gc_unknown_openbsd),
1995 ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
1996 ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
1997
1998 ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
1999 ("aarch64_be-unknown-netbsd", aarch64_be_unknown_netbsd),
2000 ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
2001 ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
2002 ("i586-unknown-netbsd", i586_unknown_netbsd),
2003 ("i686-unknown-netbsd", i686_unknown_netbsd),
2004 ("mipsel-unknown-netbsd", mipsel_unknown_netbsd),
2005 ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
2006 ("riscv64gc-unknown-netbsd", riscv64gc_unknown_netbsd),
2007 ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
2008 ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
2009
2010 ("i686-unknown-haiku", i686_unknown_haiku),
2011 ("x86_64-unknown-haiku", x86_64_unknown_haiku),
2012
2013 ("i686-unknown-hurd-gnu", i686_unknown_hurd_gnu),
2014 ("x86_64-unknown-hurd-gnu", x86_64_unknown_hurd_gnu),
2015
2016 ("aarch64-apple-darwin", aarch64_apple_darwin),
2017 ("arm64e-apple-darwin", arm64e_apple_darwin),
2018 ("x86_64-apple-darwin", x86_64_apple_darwin),
2019 ("x86_64h-apple-darwin", x86_64h_apple_darwin),
2020 ("i686-apple-darwin", i686_apple_darwin),
2021
2022 ("aarch64-unknown-fuchsia", aarch64_unknown_fuchsia),
2023 ("riscv64gc-unknown-fuchsia", riscv64gc_unknown_fuchsia),
2024 ("x86_64-unknown-fuchsia", x86_64_unknown_fuchsia),
2025
2026 ("avr-none", avr_none),
2027
2028 ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
2029
2030 ("aarch64-unknown-redox", aarch64_unknown_redox),
2031 ("i586-unknown-redox", i586_unknown_redox),
2032 ("x86_64-unknown-redox", x86_64_unknown_redox),
2033
2034 ("i386-apple-ios", i386_apple_ios),
2035 ("x86_64-apple-ios", x86_64_apple_ios),
2036 ("aarch64-apple-ios", aarch64_apple_ios),
2037 ("arm64e-apple-ios", arm64e_apple_ios),
2038 ("armv7s-apple-ios", armv7s_apple_ios),
2039 ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
2040 ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
2041 ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
2042
2043 ("aarch64-apple-tvos", aarch64_apple_tvos),
2044 ("aarch64-apple-tvos-sim", aarch64_apple_tvos_sim),
2045 ("arm64e-apple-tvos", arm64e_apple_tvos),
2046 ("x86_64-apple-tvos", x86_64_apple_tvos),
2047
2048 ("armv7k-apple-watchos", armv7k_apple_watchos),
2049 ("arm64_32-apple-watchos", arm64_32_apple_watchos),
2050 ("x86_64-apple-watchos-sim", x86_64_apple_watchos_sim),
2051 ("aarch64-apple-watchos", aarch64_apple_watchos),
2052 ("aarch64-apple-watchos-sim", aarch64_apple_watchos_sim),
2053
2054 ("aarch64-apple-visionos", aarch64_apple_visionos),
2055 ("aarch64-apple-visionos-sim", aarch64_apple_visionos_sim),
2056
2057 ("armebv7r-none-eabi", armebv7r_none_eabi),
2058 ("armebv7r-none-eabihf", armebv7r_none_eabihf),
2059 ("armv7r-none-eabi", armv7r_none_eabi),
2060 ("armv7r-none-eabihf", armv7r_none_eabihf),
2061 ("armv8r-none-eabihf", armv8r_none_eabihf),
2062
2063 ("armv7-rtems-eabihf", armv7_rtems_eabihf),
2064
2065 ("x86_64-pc-solaris", x86_64_pc_solaris),
2066 ("sparcv9-sun-solaris", sparcv9_sun_solaris),
2067
2068 ("x86_64-unknown-illumos", x86_64_unknown_illumos),
2069 ("aarch64-unknown-illumos", aarch64_unknown_illumos),
2070
2071 ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
2072 ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
2073 ("x86_64-win7-windows-gnu", x86_64_win7_windows_gnu),
2074 ("i686-pc-windows-gnu", i686_pc_windows_gnu),
2075 ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
2076 ("i686-win7-windows-gnu", i686_win7_windows_gnu),
2077
2078 ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
2079 ("i686-pc-windows-gnullvm", i686_pc_windows_gnullvm),
2080 ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
2081
2082 ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
2083 ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
2084 ("arm64ec-pc-windows-msvc", arm64ec_pc_windows_msvc),
2085 ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
2086 ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
2087 ("x86_64-win7-windows-msvc", x86_64_win7_windows_msvc),
2088 ("i686-pc-windows-msvc", i686_pc_windows_msvc),
2089 ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
2090 ("i686-win7-windows-msvc", i686_win7_windows_msvc),
2091 ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
2092 ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
2093
2094 ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
2095 ("wasm32-unknown-unknown", wasm32_unknown_unknown),
2096 ("wasm32v1-none", wasm32v1_none),
2097 ("wasm32-wasip1", wasm32_wasip1),
2098 ("wasm32-wasip2", wasm32_wasip2),
2099 ("wasm32-wasip1-threads", wasm32_wasip1_threads),
2100 ("wasm32-wali-linux-musl", wasm32_wali_linux_musl),
2101 ("wasm64-unknown-unknown", wasm64_unknown_unknown),
2102
2103 ("thumbv6m-none-eabi", thumbv6m_none_eabi),
2104 ("thumbv7m-none-eabi", thumbv7m_none_eabi),
2105 ("thumbv7em-none-eabi", thumbv7em_none_eabi),
2106 ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
2107 ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
2108 ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
2109 ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
2110
2111 ("armv7a-none-eabi", armv7a_none_eabi),
2112 ("armv7a-none-eabihf", armv7a_none_eabihf),
2113 ("armv7a-nuttx-eabi", armv7a_nuttx_eabi),
2114 ("armv7a-nuttx-eabihf", armv7a_nuttx_eabihf),
2115 ("armv7a-vex-v5", armv7a_vex_v5),
2116
2117 ("msp430-none-elf", msp430_none_elf),
2118
2119 ("aarch64_be-unknown-hermit", aarch64_be_unknown_hermit),
2120 ("aarch64-unknown-hermit", aarch64_unknown_hermit),
2121 ("riscv64gc-unknown-hermit", riscv64gc_unknown_hermit),
2122 ("x86_64-unknown-hermit", x86_64_unknown_hermit),
2123
2124 ("x86_64-unikraft-linux-musl", x86_64_unikraft_linux_musl),
2125
2126 ("armv7-unknown-trusty", armv7_unknown_trusty),
2127 ("aarch64-unknown-trusty", aarch64_unknown_trusty),
2128 ("x86_64-unknown-trusty", x86_64_unknown_trusty),
2129
2130 ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
2131 ("riscv32im-risc0-zkvm-elf", riscv32im_risc0_zkvm_elf),
2132 ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
2133 ("riscv32ima-unknown-none-elf", riscv32ima_unknown_none_elf),
2134 ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
2135 ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
2136 ("riscv32imac-esp-espidf", riscv32imac_esp_espidf),
2137 ("riscv32imafc-esp-espidf", riscv32imafc_esp_espidf),
2138
2139 ("riscv32e-unknown-none-elf", riscv32e_unknown_none_elf),
2140 ("riscv32em-unknown-none-elf", riscv32em_unknown_none_elf),
2141 ("riscv32emc-unknown-none-elf", riscv32emc_unknown_none_elf),
2142
2143 ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
2144 ("riscv32imafc-unknown-none-elf", riscv32imafc_unknown_none_elf),
2145 ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
2146 ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
2147 ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
2148 ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
2149 ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
2150 ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
2151 ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
2152
2153 ("sparc-unknown-none-elf", sparc_unknown_none_elf),
2154
2155 ("loongarch32-unknown-none", loongarch32_unknown_none),
2156 ("loongarch32-unknown-none-softfloat", loongarch32_unknown_none_softfloat),
2157 ("loongarch64-unknown-none", loongarch64_unknown_none),
2158 ("loongarch64-unknown-none-softfloat", loongarch64_unknown_none_softfloat),
2159
2160 ("aarch64-unknown-none", aarch64_unknown_none),
2161 ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
2162 ("aarch64_be-unknown-none-softfloat", aarch64_be_unknown_none_softfloat),
2163 ("aarch64-unknown-nuttx", aarch64_unknown_nuttx),
2164
2165 ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
2166
2167 ("x86_64-unknown-uefi", x86_64_unknown_uefi),
2168 ("i686-unknown-uefi", i686_unknown_uefi),
2169 ("aarch64-unknown-uefi", aarch64_unknown_uefi),
2170
2171 ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
2172
2173 ("amdgcn-amd-amdhsa", amdgcn_amd_amdhsa),
2174
2175 ("xtensa-esp32-none-elf", xtensa_esp32_none_elf),
2176 ("xtensa-esp32-espidf", xtensa_esp32_espidf),
2177 ("xtensa-esp32s2-none-elf", xtensa_esp32s2_none_elf),
2178 ("xtensa-esp32s2-espidf", xtensa_esp32s2_espidf),
2179 ("xtensa-esp32s3-none-elf", xtensa_esp32s3_none_elf),
2180 ("xtensa-esp32s3-espidf", xtensa_esp32s3_espidf),
2181
2182 ("i686-wrs-vxworks", i686_wrs_vxworks),
2183 ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
2184 ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
2185 ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
2186 ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
2187 ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
2188 ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
2189 ("riscv32-wrs-vxworks", riscv32_wrs_vxworks),
2190 ("riscv64-wrs-vxworks", riscv64_wrs_vxworks),
2191
2192 ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
2193 ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
2194 ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
2195
2196 ("mipsel-sony-psp", mipsel_sony_psp),
2197 ("mipsel-sony-psx", mipsel_sony_psx),
2198 ("mipsel-unknown-none", mipsel_unknown_none),
2199 ("mips-mti-none-elf", mips_mti_none_elf),
2200 ("mipsel-mti-none-elf", mipsel_mti_none_elf),
2201 ("thumbv4t-none-eabi", thumbv4t_none_eabi),
2202 ("armv4t-none-eabi", armv4t_none_eabi),
2203 ("thumbv5te-none-eabi", thumbv5te_none_eabi),
2204 ("armv5te-none-eabi", armv5te_none_eabi),
2205
2206 ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
2207 ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
2208 ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
2209
2210 ("bpfeb-unknown-none", bpfeb_unknown_none),
2211 ("bpfel-unknown-none", bpfel_unknown_none),
2212
2213 ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
2214
2215 ("aarch64-nintendo-switch-freestanding", aarch64_nintendo_switch_freestanding),
2216
2217 ("armv7-sony-vita-newlibeabihf", armv7_sony_vita_newlibeabihf),
2218
2219 ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
2220 ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
2221
2222 ("x86_64-unknown-none", x86_64_unknown_none),
2223
2224 ("aarch64-unknown-teeos", aarch64_unknown_teeos),
2225
2226 ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
2227
2228 ("aarch64-unknown-nto-qnx700", aarch64_unknown_nto_qnx700),
2229 ("aarch64-unknown-nto-qnx710", aarch64_unknown_nto_qnx710),
2230 ("aarch64-unknown-nto-qnx710_iosock", aarch64_unknown_nto_qnx710_iosock),
2231 ("aarch64-unknown-nto-qnx800", aarch64_unknown_nto_qnx800),
2232 ("x86_64-pc-nto-qnx710", x86_64_pc_nto_qnx710),
2233 ("x86_64-pc-nto-qnx710_iosock", x86_64_pc_nto_qnx710_iosock),
2234 ("x86_64-pc-nto-qnx800", x86_64_pc_nto_qnx800),
2235 ("i686-pc-nto-qnx700", i686_pc_nto_qnx700),
2236
2237 ("aarch64-unknown-linux-ohos", aarch64_unknown_linux_ohos),
2238 ("armv7-unknown-linux-ohos", armv7_unknown_linux_ohos),
2239 ("loongarch64-unknown-linux-ohos", loongarch64_unknown_linux_ohos),
2240 ("x86_64-unknown-linux-ohos", x86_64_unknown_linux_ohos),
2241
2242 ("x86_64-unknown-linux-none", x86_64_unknown_linux_none),
2243
2244 ("thumbv6m-nuttx-eabi", thumbv6m_nuttx_eabi),
2245 ("thumbv7a-nuttx-eabi", thumbv7a_nuttx_eabi),
2246 ("thumbv7a-nuttx-eabihf", thumbv7a_nuttx_eabihf),
2247 ("thumbv7m-nuttx-eabi", thumbv7m_nuttx_eabi),
2248 ("thumbv7em-nuttx-eabi", thumbv7em_nuttx_eabi),
2249 ("thumbv7em-nuttx-eabihf", thumbv7em_nuttx_eabihf),
2250 ("thumbv8m.base-nuttx-eabi", thumbv8m_base_nuttx_eabi),
2251 ("thumbv8m.main-nuttx-eabi", thumbv8m_main_nuttx_eabi),
2252 ("thumbv8m.main-nuttx-eabihf", thumbv8m_main_nuttx_eabihf),
2253 ("riscv32imc-unknown-nuttx-elf", riscv32imc_unknown_nuttx_elf),
2254 ("riscv32imac-unknown-nuttx-elf", riscv32imac_unknown_nuttx_elf),
2255 ("riscv32imafc-unknown-nuttx-elf", riscv32imafc_unknown_nuttx_elf),
2256 ("riscv64imac-unknown-nuttx-elf", riscv64imac_unknown_nuttx_elf),
2257 ("riscv64gc-unknown-nuttx-elf", riscv64gc_unknown_nuttx_elf),
2258 ("x86_64-lynx-lynxos178", x86_64_lynx_lynxos178),
2259
2260 ("x86_64-pc-cygwin", x86_64_pc_cygwin),
2261}
2262
2263macro_rules! cvs {
2265 () => {
2266 ::std::borrow::Cow::Borrowed(&[])
2267 };
2268 ($($x:expr),+ $(,)?) => {
2269 ::std::borrow::Cow::Borrowed(&[
2270 $(
2271 ::std::borrow::Cow::Borrowed($x),
2272 )*
2273 ])
2274 };
2275}
2276
2277pub(crate) use cvs;
2278
2279#[derive(Debug, PartialEq)]
2283pub struct TargetWarnings {
2284 unused_fields: Vec<String>,
2285}
2286
2287impl TargetWarnings {
2288 pub fn empty() -> Self {
2289 Self { unused_fields: Vec::new() }
2290 }
2291
2292 pub fn warning_messages(&self) -> Vec<String> {
2293 let mut warnings = vec![];
2294 if !self.unused_fields.is_empty() {
2295 warnings.push(format!(
2296 "target json file contains unused fields: {}",
2297 self.unused_fields.join(", ")
2298 ));
2299 }
2300 warnings
2301 }
2302}
2303
2304#[derive(Copy, Clone, Debug, PartialEq)]
2307enum TargetKind {
2308 Json,
2309 Builtin,
2310}
2311
2312#[derive(PartialEq, Clone, Debug)]
2316pub struct Target {
2317 pub llvm_target: StaticCow<str>,
2324 pub metadata: TargetMetadata,
2327 pub pointer_width: u32,
2329 pub arch: StaticCow<str>,
2332 pub data_layout: StaticCow<str>,
2334 pub options: TargetOptions,
2336}
2337
2338#[derive(Default, PartialEq, Clone, Debug)]
2342pub struct TargetMetadata {
2343 pub description: Option<StaticCow<str>>,
2346 pub tier: Option<u64>,
2348 pub host_tools: Option<bool>,
2350 pub std: Option<bool>,
2353}
2354
2355impl Target {
2356 pub fn parse_data_layout(&self) -> Result<TargetDataLayout, TargetDataLayoutErrors<'_>> {
2357 let mut dl = TargetDataLayout::parse_from_llvm_datalayout_string(
2358 &self.data_layout,
2359 self.options.default_address_space,
2360 )?;
2361
2362 if dl.endian != self.endian {
2364 return Err(TargetDataLayoutErrors::InconsistentTargetArchitecture {
2365 dl: dl.endian.as_str(),
2366 target: self.endian.as_str(),
2367 });
2368 }
2369
2370 let target_pointer_width: u64 = self.pointer_width.into();
2371 let dl_pointer_size: u64 = dl.pointer_size().bits();
2372 if dl_pointer_size != target_pointer_width {
2373 return Err(TargetDataLayoutErrors::InconsistentTargetPointerWidth {
2374 pointer_size: dl_pointer_size,
2375 target: self.pointer_width,
2376 });
2377 }
2378
2379 dl.c_enum_min_size = Integer::from_size(Size::from_bits(
2380 self.c_enum_min_bits.unwrap_or(self.c_int_width as _),
2381 ))
2382 .map_err(|err| TargetDataLayoutErrors::InvalidBitsSize { err })?;
2383
2384 Ok(dl)
2385 }
2386}
2387
2388pub trait HasTargetSpec {
2389 fn target_spec(&self) -> &Target;
2390}
2391
2392impl HasTargetSpec for Target {
2393 #[inline]
2394 fn target_spec(&self) -> &Target {
2395 self
2396 }
2397}
2398
2399#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
2401pub struct X86Abi {
2402 pub regparm: Option<u32>,
2405 pub reg_struct_return: bool,
2407}
2408
2409pub trait HasX86AbiOpt {
2410 fn x86_abi_opt(&self) -> X86Abi;
2411}
2412
2413type StaticCow<T> = Cow<'static, T>;
2414
2415#[derive(PartialEq, Clone, Debug)]
2424pub struct TargetOptions {
2425 pub endian: Endian,
2427 pub c_int_width: u16,
2429 pub os: StaticCow<str>,
2434 pub env: StaticCow<str>,
2436 pub abi: StaticCow<str>,
2441 pub vendor: StaticCow<str>,
2443
2444 pub linker: Option<StaticCow<str>>,
2446 pub linker_flavor: LinkerFlavor,
2449 linker_flavor_json: LinkerFlavorCli,
2450 lld_flavor_json: LldFlavor,
2451 linker_is_gnu_json: bool,
2452
2453 pub pre_link_objects: CrtObjects,
2455 pub post_link_objects: CrtObjects,
2456 pub pre_link_objects_self_contained: CrtObjects,
2458 pub post_link_objects_self_contained: CrtObjects,
2459 pub link_self_contained: LinkSelfContainedDefault,
2462
2463 pub pre_link_args: LinkArgs,
2465 pre_link_args_json: LinkArgsCli,
2466 pub late_link_args: LinkArgs,
2470 late_link_args_json: LinkArgsCli,
2471 pub late_link_args_dynamic: LinkArgs,
2474 late_link_args_dynamic_json: LinkArgsCli,
2475 pub late_link_args_static: LinkArgs,
2478 late_link_args_static_json: LinkArgsCli,
2479 pub post_link_args: LinkArgs,
2482 post_link_args_json: LinkArgsCli,
2483
2484 pub link_script: Option<StaticCow<str>>,
2488 pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
2490 pub link_env_remove: StaticCow<[StaticCow<str>]>,
2492
2493 pub asm_args: StaticCow<[StaticCow<str>]>,
2495
2496 pub cpu: StaticCow<str>,
2499 pub need_explicit_cpu: bool,
2502 pub features: StaticCow<str>,
2511 pub direct_access_external_data: Option<bool>,
2513 pub dynamic_linking: bool,
2515 pub dll_tls_export: bool,
2517 pub only_cdylib: bool,
2519 pub executables: bool,
2521 pub relocation_model: RelocModel,
2524 pub code_model: Option<CodeModel>,
2527 pub tls_model: TlsModel,
2530 pub disable_redzone: bool,
2532 pub frame_pointer: FramePointer,
2534 pub function_sections: bool,
2536 pub dll_prefix: StaticCow<str>,
2538 pub dll_suffix: StaticCow<str>,
2540 pub exe_suffix: StaticCow<str>,
2542 pub staticlib_prefix: StaticCow<str>,
2544 pub staticlib_suffix: StaticCow<str>,
2546 pub families: StaticCow<[StaticCow<str>]>,
2552 pub abi_return_struct_as_int: bool,
2554 pub is_like_aix: bool,
2557 pub is_like_darwin: bool,
2562 pub is_like_solaris: bool,
2566 pub is_like_windows: bool,
2574 pub is_like_msvc: bool,
2584 pub is_like_wasm: bool,
2586 pub is_like_android: bool,
2588 pub is_like_vexos: bool,
2590 pub binary_format: BinaryFormat,
2592 pub default_dwarf_version: u32,
2595 pub allows_weak_linkage: bool,
2602 pub has_rpath: bool,
2604 pub no_default_libraries: bool,
2607 pub position_independent_executables: bool,
2613 pub static_position_independent_executables: bool,
2615 pub plt_by_default: bool,
2618 pub relro_level: RelroLevel,
2622 pub archive_format: StaticCow<str>,
2627 pub allow_asm: bool,
2629 pub main_needs_argc_argv: bool,
2632
2633 pub has_thread_local: bool,
2635 pub obj_is_bitcode: bool,
2639
2640 pub min_atomic_width: Option<u64>,
2642
2643 pub max_atomic_width: Option<u64>,
2645
2646 pub atomic_cas: bool,
2648
2649 pub panic_strategy: PanicStrategy,
2651
2652 pub crt_static_allows_dylibs: bool,
2654 pub crt_static_default: bool,
2656 pub crt_static_respected: bool,
2658
2659 pub stack_probes: StackProbeType,
2661
2662 pub min_global_align: Option<Align>,
2664
2665 pub default_codegen_units: Option<u64>,
2667
2668 pub default_codegen_backend: Option<StaticCow<str>>,
2678
2679 pub trap_unreachable: bool,
2682
2683 pub requires_lto: bool,
2686
2687 pub singlethread: bool,
2689
2690 pub no_builtins: bool,
2693
2694 pub default_visibility: Option<SymbolVisibility>,
2700
2701 pub emit_debug_gdb_scripts: bool,
2703
2704 pub requires_uwtable: bool,
2708
2709 pub default_uwtable: bool,
2712
2713 pub simd_types_indirect: bool,
2718
2719 pub limit_rdylib_exports: bool,
2721
2722 pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
2725
2726 pub merge_functions: MergeFunctions,
2733
2734 pub mcount: StaticCow<str>,
2736
2737 pub llvm_mcount_intrinsic: Option<StaticCow<str>>,
2739
2740 pub llvm_abiname: StaticCow<str>,
2743
2744 pub llvm_floatabi: Option<FloatAbi>,
2751
2752 pub rustc_abi: Option<RustcAbi>,
2757
2758 pub relax_elf_relocations: bool,
2760
2761 pub llvm_args: StaticCow<[StaticCow<str>]>,
2763
2764 pub use_ctors_section: bool,
2767
2768 pub eh_frame_header: bool,
2772
2773 pub has_thumb_interworking: bool,
2776
2777 pub debuginfo_kind: DebuginfoKind,
2779 pub split_debuginfo: SplitDebuginfo,
2782 pub supported_split_debuginfo: StaticCow<[SplitDebuginfo]>,
2784
2785 pub supported_sanitizers: SanitizerSet,
2791
2792 pub c_enum_min_bits: Option<u64>,
2794
2795 pub generate_arange_section: bool,
2797
2798 pub supports_stack_protector: bool,
2801
2802 pub entry_name: StaticCow<str>,
2805
2806 pub entry_abi: CanonAbi,
2809
2810 pub supports_xray: bool,
2812
2813 pub default_address_space: rustc_abi::AddressSpace,
2817
2818 small_data_threshold_support: SmallDataThresholdSupport,
2820}
2821
2822fn add_link_args_iter(
2825 link_args: &mut LinkArgs,
2826 flavor: LinkerFlavor,
2827 args: impl Iterator<Item = StaticCow<str>> + Clone,
2828) {
2829 let mut insert = |flavor| link_args.entry(flavor).or_default().extend(args.clone());
2830 insert(flavor);
2831 match flavor {
2832 LinkerFlavor::Gnu(cc, lld) => {
2833 assert_eq!(lld, Lld::No);
2834 insert(LinkerFlavor::Gnu(cc, Lld::Yes));
2835 }
2836 LinkerFlavor::Darwin(cc, lld) => {
2837 assert_eq!(lld, Lld::No);
2838 insert(LinkerFlavor::Darwin(cc, Lld::Yes));
2839 }
2840 LinkerFlavor::Msvc(lld) => {
2841 assert_eq!(lld, Lld::No);
2842 insert(LinkerFlavor::Msvc(Lld::Yes));
2843 }
2844 LinkerFlavor::WasmLld(..)
2845 | LinkerFlavor::Unix(..)
2846 | LinkerFlavor::EmCc
2847 | LinkerFlavor::Bpf
2848 | LinkerFlavor::Llbc
2849 | LinkerFlavor::Ptx => {}
2850 }
2851}
2852
2853fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'static str]) {
2854 add_link_args_iter(link_args, flavor, args.iter().copied().map(Cow::Borrowed))
2855}
2856
2857impl TargetOptions {
2858 pub fn supports_comdat(&self) -> bool {
2859 !self.is_like_aix && !self.is_like_darwin
2861 }
2862}
2863
2864impl TargetOptions {
2865 fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
2866 let mut link_args = LinkArgs::new();
2867 add_link_args(&mut link_args, flavor, args);
2868 link_args
2869 }
2870
2871 fn add_pre_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
2872 add_link_args(&mut self.pre_link_args, flavor, args);
2873 }
2874
2875 fn update_from_cli(&mut self) {
2876 self.linker_flavor = LinkerFlavor::from_cli_json(
2877 self.linker_flavor_json,
2878 self.lld_flavor_json,
2879 self.linker_is_gnu_json,
2880 );
2881 for (args, args_json) in [
2882 (&mut self.pre_link_args, &self.pre_link_args_json),
2883 (&mut self.late_link_args, &self.late_link_args_json),
2884 (&mut self.late_link_args_dynamic, &self.late_link_args_dynamic_json),
2885 (&mut self.late_link_args_static, &self.late_link_args_static_json),
2886 (&mut self.post_link_args, &self.post_link_args_json),
2887 ] {
2888 args.clear();
2889 for (flavor, args_json) in args_json {
2890 let linker_flavor = self.linker_flavor.with_cli_hints(*flavor);
2891 let linker_flavor = match linker_flavor {
2893 LinkerFlavor::Gnu(cc, _) => LinkerFlavor::Gnu(cc, Lld::No),
2894 LinkerFlavor::Darwin(cc, _) => LinkerFlavor::Darwin(cc, Lld::No),
2895 LinkerFlavor::Msvc(_) => LinkerFlavor::Msvc(Lld::No),
2896 _ => linker_flavor,
2897 };
2898 if !args.contains_key(&linker_flavor) {
2899 add_link_args_iter(args, linker_flavor, args_json.iter().cloned());
2900 }
2901 }
2902 }
2903 }
2904
2905 fn update_to_cli(&mut self) {
2906 self.linker_flavor_json = self.linker_flavor.to_cli_counterpart();
2907 self.lld_flavor_json = self.linker_flavor.lld_flavor();
2908 self.linker_is_gnu_json = self.linker_flavor.is_gnu();
2909 for (args, args_json) in [
2910 (&self.pre_link_args, &mut self.pre_link_args_json),
2911 (&self.late_link_args, &mut self.late_link_args_json),
2912 (&self.late_link_args_dynamic, &mut self.late_link_args_dynamic_json),
2913 (&self.late_link_args_static, &mut self.late_link_args_static_json),
2914 (&self.post_link_args, &mut self.post_link_args_json),
2915 ] {
2916 *args_json = args
2917 .iter()
2918 .map(|(flavor, args)| (flavor.to_cli_counterpart(), args.clone()))
2919 .collect();
2920 }
2921 }
2922}
2923
2924impl Default for TargetOptions {
2925 fn default() -> TargetOptions {
2928 TargetOptions {
2929 endian: Endian::Little,
2930 c_int_width: 32,
2931 os: "none".into(),
2932 env: "".into(),
2933 abi: "".into(),
2934 vendor: "unknown".into(),
2935 linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
2936 linker_flavor: LinkerFlavor::Gnu(Cc::Yes, Lld::No),
2937 linker_flavor_json: LinkerFlavorCli::Gcc,
2938 lld_flavor_json: LldFlavor::Ld,
2939 linker_is_gnu_json: true,
2940 link_script: None,
2941 asm_args: cvs![],
2942 cpu: "generic".into(),
2943 need_explicit_cpu: false,
2944 features: "".into(),
2945 direct_access_external_data: None,
2946 dynamic_linking: false,
2947 dll_tls_export: true,
2948 only_cdylib: false,
2949 executables: true,
2950 relocation_model: RelocModel::Pic,
2951 code_model: None,
2952 tls_model: TlsModel::GeneralDynamic,
2953 disable_redzone: false,
2954 frame_pointer: FramePointer::MayOmit,
2955 function_sections: true,
2956 dll_prefix: "lib".into(),
2957 dll_suffix: ".so".into(),
2958 exe_suffix: "".into(),
2959 staticlib_prefix: "lib".into(),
2960 staticlib_suffix: ".a".into(),
2961 families: cvs![],
2962 abi_return_struct_as_int: false,
2963 is_like_aix: false,
2964 is_like_darwin: false,
2965 is_like_solaris: false,
2966 is_like_windows: false,
2967 is_like_msvc: false,
2968 is_like_wasm: false,
2969 is_like_android: false,
2970 is_like_vexos: false,
2971 binary_format: BinaryFormat::Elf,
2972 default_dwarf_version: 4,
2973 allows_weak_linkage: true,
2974 has_rpath: false,
2975 no_default_libraries: true,
2976 position_independent_executables: false,
2977 static_position_independent_executables: false,
2978 plt_by_default: true,
2979 relro_level: RelroLevel::None,
2980 pre_link_objects: Default::default(),
2981 post_link_objects: Default::default(),
2982 pre_link_objects_self_contained: Default::default(),
2983 post_link_objects_self_contained: Default::default(),
2984 link_self_contained: LinkSelfContainedDefault::False,
2985 pre_link_args: LinkArgs::new(),
2986 pre_link_args_json: LinkArgsCli::new(),
2987 late_link_args: LinkArgs::new(),
2988 late_link_args_json: LinkArgsCli::new(),
2989 late_link_args_dynamic: LinkArgs::new(),
2990 late_link_args_dynamic_json: LinkArgsCli::new(),
2991 late_link_args_static: LinkArgs::new(),
2992 late_link_args_static_json: LinkArgsCli::new(),
2993 post_link_args: LinkArgs::new(),
2994 post_link_args_json: LinkArgsCli::new(),
2995 link_env: cvs![],
2996 link_env_remove: cvs![],
2997 archive_format: "gnu".into(),
2998 main_needs_argc_argv: true,
2999 allow_asm: true,
3000 has_thread_local: false,
3001 obj_is_bitcode: false,
3002 min_atomic_width: None,
3003 max_atomic_width: None,
3004 atomic_cas: true,
3005 panic_strategy: PanicStrategy::Unwind,
3006 crt_static_allows_dylibs: false,
3007 crt_static_default: false,
3008 crt_static_respected: false,
3009 stack_probes: StackProbeType::None,
3010 min_global_align: None,
3011 default_codegen_units: None,
3012 default_codegen_backend: None,
3013 trap_unreachable: true,
3014 requires_lto: false,
3015 singlethread: false,
3016 no_builtins: false,
3017 default_visibility: None,
3018 emit_debug_gdb_scripts: true,
3019 requires_uwtable: false,
3020 default_uwtable: false,
3021 simd_types_indirect: true,
3022 limit_rdylib_exports: true,
3023 override_export_symbols: None,
3024 merge_functions: MergeFunctions::Aliases,
3025 mcount: "mcount".into(),
3026 llvm_mcount_intrinsic: None,
3027 llvm_abiname: "".into(),
3028 llvm_floatabi: None,
3029 rustc_abi: None,
3030 relax_elf_relocations: false,
3031 llvm_args: cvs![],
3032 use_ctors_section: false,
3033 eh_frame_header: true,
3034 has_thumb_interworking: false,
3035 debuginfo_kind: Default::default(),
3036 split_debuginfo: Default::default(),
3037 supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
3039 supported_sanitizers: SanitizerSet::empty(),
3040 c_enum_min_bits: None,
3041 generate_arange_section: true,
3042 supports_stack_protector: true,
3043 entry_name: "main".into(),
3044 entry_abi: CanonAbi::C,
3045 supports_xray: false,
3046 default_address_space: rustc_abi::AddressSpace::ZERO,
3047 small_data_threshold_support: SmallDataThresholdSupport::DefaultForArch,
3048 }
3049 }
3050}
3051
3052impl Deref for Target {
3056 type Target = TargetOptions;
3057
3058 #[inline]
3059 fn deref(&self) -> &Self::Target {
3060 &self.options
3061 }
3062}
3063impl DerefMut for Target {
3064 #[inline]
3065 fn deref_mut(&mut self) -> &mut Self::Target {
3066 &mut self.options
3067 }
3068}
3069
3070impl Target {
3071 pub fn is_abi_supported(&self, abi: ExternAbi) -> bool {
3072 let abi_map = AbiMap::from_target(self);
3073 abi_map.canonize_abi(abi, false).is_mapped()
3074 }
3075
3076 pub fn min_atomic_width(&self) -> u64 {
3079 self.min_atomic_width.unwrap_or(8)
3080 }
3081
3082 pub fn max_atomic_width(&self) -> u64 {
3085 self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
3086 }
3087
3088 fn check_consistency(&self, kind: TargetKind) -> Result<(), String> {
3091 macro_rules! check {
3092 ($b:expr, $($msg:tt)*) => {
3093 if !$b {
3094 return Err(format!($($msg)*));
3095 }
3096 }
3097 }
3098 macro_rules! check_eq {
3099 ($left:expr, $right:expr, $($msg:tt)*) => {
3100 if ($left) != ($right) {
3101 return Err(format!($($msg)*));
3102 }
3103 }
3104 }
3105 macro_rules! check_ne {
3106 ($left:expr, $right:expr, $($msg:tt)*) => {
3107 if ($left) == ($right) {
3108 return Err(format!($($msg)*));
3109 }
3110 }
3111 }
3112 macro_rules! check_matches {
3113 ($left:expr, $right:pat, $($msg:tt)*) => {
3114 if !matches!($left, $right) {
3115 return Err(format!($($msg)*));
3116 }
3117 }
3118 }
3119
3120 check_eq!(
3121 self.is_like_darwin,
3122 self.vendor == "apple",
3123 "`is_like_darwin` must be set if and only if `vendor` is `apple`"
3124 );
3125 check_eq!(
3126 self.is_like_solaris,
3127 self.os == "solaris" || self.os == "illumos",
3128 "`is_like_solaris` must be set if and only if `os` is `solaris` or `illumos`"
3129 );
3130 check_eq!(
3131 self.is_like_windows,
3132 self.os == "windows" || self.os == "uefi" || self.os == "cygwin",
3133 "`is_like_windows` must be set if and only if `os` is `windows`, `uefi` or `cygwin`"
3134 );
3135 check_eq!(
3136 self.is_like_wasm,
3137 self.arch == "wasm32" || self.arch == "wasm64",
3138 "`is_like_wasm` must be set if and only if `arch` is `wasm32` or `wasm64`"
3139 );
3140 if self.is_like_msvc {
3141 check!(self.is_like_windows, "if `is_like_msvc` is set, `is_like_windows` must be set");
3142 }
3143 if self.os == "emscripten" {
3144 check!(self.is_like_wasm, "the `emcscripten` os only makes sense on wasm-like targets");
3145 }
3146
3147 check_eq!(
3149 self.is_like_darwin,
3150 matches!(self.linker_flavor, LinkerFlavor::Darwin(..)),
3151 "`linker_flavor` must be `darwin` if and only if `is_like_darwin` is set"
3152 );
3153 check_eq!(
3154 self.is_like_msvc,
3155 matches!(self.linker_flavor, LinkerFlavor::Msvc(..)),
3156 "`linker_flavor` must be `msvc` if and only if `is_like_msvc` is set"
3157 );
3158 check_eq!(
3159 self.is_like_wasm && self.os != "emscripten",
3160 matches!(self.linker_flavor, LinkerFlavor::WasmLld(..)),
3161 "`linker_flavor` must be `wasm-lld` if and only if `is_like_wasm` is set and the `os` is not `emscripten`",
3162 );
3163 check_eq!(
3164 self.os == "emscripten",
3165 matches!(self.linker_flavor, LinkerFlavor::EmCc),
3166 "`linker_flavor` must be `em-cc` if and only if `os` is `emscripten`"
3167 );
3168 check_eq!(
3169 self.arch == "bpf",
3170 matches!(self.linker_flavor, LinkerFlavor::Bpf),
3171 "`linker_flavor` must be `bpf` if and only if `arch` is `bpf`"
3172 );
3173 check_eq!(
3174 self.arch == "nvptx64",
3175 matches!(self.linker_flavor, LinkerFlavor::Ptx),
3176 "`linker_flavor` must be `ptc` if and only if `arch` is `nvptx64`"
3177 );
3178
3179 for args in [
3180 &self.pre_link_args,
3181 &self.late_link_args,
3182 &self.late_link_args_dynamic,
3183 &self.late_link_args_static,
3184 &self.post_link_args,
3185 ] {
3186 for (&flavor, flavor_args) in args {
3187 check!(
3188 !flavor_args.is_empty() || self.arch == "avr",
3189 "linker flavor args must not be empty"
3190 );
3191 match self.linker_flavor {
3193 LinkerFlavor::Gnu(..) => {
3194 check_matches!(
3195 flavor,
3196 LinkerFlavor::Gnu(..),
3197 "mixing GNU and non-GNU linker flavors"
3198 );
3199 }
3200 LinkerFlavor::Darwin(..) => {
3201 check_matches!(
3202 flavor,
3203 LinkerFlavor::Darwin(..),
3204 "mixing Darwin and non-Darwin linker flavors"
3205 )
3206 }
3207 LinkerFlavor::WasmLld(..) => {
3208 check_matches!(
3209 flavor,
3210 LinkerFlavor::WasmLld(..),
3211 "mixing wasm and non-wasm linker flavors"
3212 )
3213 }
3214 LinkerFlavor::Unix(..) => {
3215 check_matches!(
3216 flavor,
3217 LinkerFlavor::Unix(..),
3218 "mixing unix and non-unix linker flavors"
3219 );
3220 }
3221 LinkerFlavor::Msvc(..) => {
3222 check_matches!(
3223 flavor,
3224 LinkerFlavor::Msvc(..),
3225 "mixing MSVC and non-MSVC linker flavors"
3226 );
3227 }
3228 LinkerFlavor::EmCc
3229 | LinkerFlavor::Bpf
3230 | LinkerFlavor::Ptx
3231 | LinkerFlavor::Llbc => {
3232 check_eq!(flavor, self.linker_flavor, "mixing different linker flavors")
3233 }
3234 }
3235
3236 let check_noncc = |noncc_flavor| -> Result<(), String> {
3238 if let Some(noncc_args) = args.get(&noncc_flavor) {
3239 for arg in flavor_args {
3240 if let Some(suffix) = arg.strip_prefix("-Wl,") {
3241 check!(
3242 noncc_args.iter().any(|a| a == suffix),
3243 " link args for cc and non-cc versions of flavors are not consistent"
3244 );
3245 }
3246 }
3247 }
3248 Ok(())
3249 };
3250
3251 match self.linker_flavor {
3252 LinkerFlavor::Gnu(Cc::Yes, lld) => check_noncc(LinkerFlavor::Gnu(Cc::No, lld))?,
3253 LinkerFlavor::WasmLld(Cc::Yes) => check_noncc(LinkerFlavor::WasmLld(Cc::No))?,
3254 LinkerFlavor::Unix(Cc::Yes) => check_noncc(LinkerFlavor::Unix(Cc::No))?,
3255 _ => {}
3256 }
3257 }
3258
3259 for cc in [Cc::No, Cc::Yes] {
3261 check_eq!(
3262 args.get(&LinkerFlavor::Gnu(cc, Lld::No)),
3263 args.get(&LinkerFlavor::Gnu(cc, Lld::Yes)),
3264 "link args for lld and non-lld versions of flavors are not consistent",
3265 );
3266 check_eq!(
3267 args.get(&LinkerFlavor::Darwin(cc, Lld::No)),
3268 args.get(&LinkerFlavor::Darwin(cc, Lld::Yes)),
3269 "link args for lld and non-lld versions of flavors are not consistent",
3270 );
3271 }
3272 check_eq!(
3273 args.get(&LinkerFlavor::Msvc(Lld::No)),
3274 args.get(&LinkerFlavor::Msvc(Lld::Yes)),
3275 "link args for lld and non-lld versions of flavors are not consistent",
3276 );
3277 }
3278
3279 if self.link_self_contained.is_disabled() {
3280 check!(
3281 self.pre_link_objects_self_contained.is_empty()
3282 && self.post_link_objects_self_contained.is_empty(),
3283 "if `link_self_contained` is disabled, then `pre_link_objects_self_contained` and `post_link_objects_self_contained` must be empty",
3284 );
3285 }
3286
3287 check_ne!(self.vendor, "", "`vendor` cannot be empty");
3291 check_ne!(self.os, "", "`os` cannot be empty");
3292 if !self.can_use_os_unknown() {
3293 check_ne!(
3295 self.os,
3296 "unknown",
3297 "`unknown` os can only be used on particular targets; use `none` for bare-metal targets"
3298 );
3299 }
3300
3301 if kind == TargetKind::Builtin {
3307 if self.os == "none"
3311 && (self.arch != "bpf"
3312 && self.arch != "hexagon"
3313 && self.arch != "wasm32"
3314 && self.arch != "wasm64")
3315 {
3316 check!(
3317 !self.dynamic_linking,
3318 "dynamic linking is not supported on this OS/architecture"
3319 );
3320 }
3321 if self.only_cdylib
3322 || self.crt_static_allows_dylibs
3323 || !self.late_link_args_dynamic.is_empty()
3324 {
3325 check!(
3326 self.dynamic_linking,
3327 "dynamic linking must be allowed when `only_cdylib` or `crt_static_allows_dylibs` or `late_link_args_dynamic` are set"
3328 );
3329 }
3330 if self.dynamic_linking && !self.is_like_wasm {
3332 check_eq!(
3333 self.relocation_model,
3334 RelocModel::Pic,
3335 "targets that support dynamic linking must use the `pic` relocation model"
3336 );
3337 }
3338 if self.position_independent_executables {
3339 check_eq!(
3340 self.relocation_model,
3341 RelocModel::Pic,
3342 "targets that support position-independent executables must use the `pic` relocation model"
3343 );
3344 }
3345 if self.relocation_model == RelocModel::Pic && (self.os != "uefi") {
3347 check!(
3348 self.dynamic_linking || self.position_independent_executables,
3349 "when the relocation model is `pic`, the target must support dynamic linking or use position-independent executables. \
3350 Set the relocation model to `static` to avoid this requirement"
3351 );
3352 }
3353 if self.static_position_independent_executables {
3354 check!(
3355 self.position_independent_executables,
3356 "if `static_position_independent_executables` is set, then `position_independent_executables` must be set"
3357 );
3358 }
3359 if self.position_independent_executables {
3360 check!(
3361 self.executables,
3362 "if `position_independent_executables` is set then `executables` must be set"
3363 );
3364 }
3365 }
3366
3367 if self.crt_static_default || self.crt_static_allows_dylibs {
3369 check!(
3370 self.crt_static_respected,
3371 "static CRT can be enabled but `crt_static_respected` is not set"
3372 );
3373 }
3374
3375 match &*self.arch {
3378 "riscv32" => {
3379 check_matches!(
3380 &*self.llvm_abiname,
3381 "ilp32" | "ilp32f" | "ilp32d" | "ilp32e",
3382 "invalid RISC-V ABI name: {}",
3383 self.llvm_abiname,
3384 );
3385 }
3386 "riscv64" => {
3387 check_matches!(
3389 &*self.llvm_abiname,
3390 "lp64" | "lp64f" | "lp64d" | "lp64e",
3391 "invalid RISC-V ABI name: {}",
3392 self.llvm_abiname,
3393 );
3394 }
3395 "arm" => {
3396 check!(
3397 self.llvm_floatabi.is_some(),
3398 "ARM targets must set `llvm-floatabi` to `hard` or `soft`",
3399 )
3400 }
3401 _ => {}
3402 }
3403
3404 if let Some(rust_abi) = self.rustc_abi {
3406 match rust_abi {
3407 RustcAbi::X86Sse2 => check_matches!(
3408 &*self.arch,
3409 "x86",
3410 "`x86-sse2` ABI is only valid for x86-32 targets"
3411 ),
3412 RustcAbi::X86Softfloat => check_matches!(
3413 &*self.arch,
3414 "x86" | "x86_64",
3415 "`x86-softfloat` ABI is only valid for x86 targets"
3416 ),
3417 }
3418 }
3419
3420 if !self.features.is_empty() {
3422 let mut features_enabled = FxHashSet::default();
3423 let mut features_disabled = FxHashSet::default();
3424 for feat in self.features.split(',') {
3425 if let Some(feat) = feat.strip_prefix("+") {
3426 features_enabled.insert(feat);
3427 if features_disabled.contains(feat) {
3428 return Err(format!(
3429 "target feature `{feat}` is both enabled and disabled"
3430 ));
3431 }
3432 } else if let Some(feat) = feat.strip_prefix("-") {
3433 features_disabled.insert(feat);
3434 if features_enabled.contains(feat) {
3435 return Err(format!(
3436 "target feature `{feat}` is both enabled and disabled"
3437 ));
3438 }
3439 } else {
3440 return Err(format!(
3441 "target feature `{feat}` is invalid, must start with `+` or `-`"
3442 ));
3443 }
3444 }
3445 let abi_feature_constraints = self.abi_required_features();
3447 for feat in abi_feature_constraints.required {
3448 if features_disabled.contains(feat) {
3451 return Err(format!(
3452 "target feature `{feat}` is required by the ABI but gets disabled in target spec"
3453 ));
3454 }
3455 }
3456 for feat in abi_feature_constraints.incompatible {
3457 if features_enabled.contains(feat) {
3460 return Err(format!(
3461 "target feature `{feat}` is incompatible with the ABI but gets enabled in target spec"
3462 ));
3463 }
3464 }
3465 }
3466
3467 Ok(())
3468 }
3469
3470 #[cfg(test)]
3472 fn test_target(mut self) {
3473 let recycled_target =
3474 Target::from_json(&serde_json::to_string(&self.to_json()).unwrap()).map(|(j, _)| j);
3475 self.update_to_cli();
3476 self.check_consistency(TargetKind::Builtin).unwrap();
3477 assert_eq!(recycled_target, Ok(self));
3478 }
3479
3480 fn can_use_os_unknown(&self) -> bool {
3483 self.llvm_target == "wasm32-unknown-unknown"
3484 || self.llvm_target == "wasm64-unknown-unknown"
3485 || (self.env == "sgx" && self.vendor == "fortanix")
3486 }
3487
3488 pub fn expect_builtin(target_tuple: &TargetTuple) -> Target {
3490 match *target_tuple {
3491 TargetTuple::TargetTuple(ref target_tuple) => {
3492 load_builtin(target_tuple).expect("built-in target")
3493 }
3494 TargetTuple::TargetJson { .. } => {
3495 panic!("built-in targets doesn't support target-paths")
3496 }
3497 }
3498 }
3499
3500 pub fn builtins() -> impl Iterator<Item = Target> {
3502 load_all_builtins()
3503 }
3504
3505 pub fn search(
3515 target_tuple: &TargetTuple,
3516 sysroot: &Path,
3517 ) -> Result<(Target, TargetWarnings), String> {
3518 use std::{env, fs};
3519
3520 fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
3521 let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
3522 Target::from_json(&contents)
3523 }
3524
3525 match *target_tuple {
3526 TargetTuple::TargetTuple(ref target_tuple) => {
3527 if let Some(t) = load_builtin(target_tuple) {
3529 return Ok((t, TargetWarnings::empty()));
3530 }
3531
3532 let path = {
3534 let mut target = target_tuple.to_string();
3535 target.push_str(".json");
3536 PathBuf::from(target)
3537 };
3538
3539 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
3540
3541 for dir in env::split_paths(&target_path) {
3542 let p = dir.join(&path);
3543 if p.is_file() {
3544 return load_file(&p);
3545 }
3546 }
3547
3548 let rustlib_path = crate::relative_target_rustlib_path(sysroot, target_tuple);
3551 let p = PathBuf::from_iter([
3552 Path::new(sysroot),
3553 Path::new(&rustlib_path),
3554 Path::new("target.json"),
3555 ]);
3556 if p.is_file() {
3557 return load_file(&p);
3558 }
3559
3560 if target_tuple == "i586-pc-windows-msvc" {
3564 Err("the `i586-pc-windows-msvc` target has been removed. Use the `i686-pc-windows-msvc` target instead.\n\
3565 Windows 10 (the minimum required OS version) requires a CPU baseline of at least i686 so you can safely switch".into())
3566 } else {
3567 Err(format!("could not find specification for target {target_tuple:?}"))
3568 }
3569 }
3570 TargetTuple::TargetJson { ref contents, .. } => Target::from_json(contents),
3571 }
3572 }
3573
3574 pub fn small_data_threshold_support(&self) -> SmallDataThresholdSupport {
3577 match &self.options.small_data_threshold_support {
3578 SmallDataThresholdSupport::DefaultForArch => match self.arch.as_ref() {
3582 "mips" | "mips64" | "mips32r6" => {
3583 SmallDataThresholdSupport::LlvmArg("mips-ssection-threshold".into())
3584 }
3585 "hexagon" => {
3586 SmallDataThresholdSupport::LlvmArg("hexagon-small-data-threshold".into())
3587 }
3588 "m68k" => SmallDataThresholdSupport::LlvmArg("m68k-ssection-threshold".into()),
3589 "riscv32" | "riscv64" => {
3590 SmallDataThresholdSupport::LlvmModuleFlag("SmallDataLimit".into())
3591 }
3592 _ => SmallDataThresholdSupport::None,
3593 },
3594 s => s.clone(),
3595 }
3596 }
3597
3598 pub fn object_architecture(
3599 &self,
3600 unstable_target_features: &FxIndexSet<Symbol>,
3601 ) -> Option<(object::Architecture, Option<object::SubArchitecture>)> {
3602 use object::Architecture;
3603 Some(match self.arch.as_ref() {
3604 "arm" => (Architecture::Arm, None),
3605 "aarch64" => (
3606 if self.pointer_width == 32 {
3607 Architecture::Aarch64_Ilp32
3608 } else {
3609 Architecture::Aarch64
3610 },
3611 None,
3612 ),
3613 "x86" => (Architecture::I386, None),
3614 "s390x" => (Architecture::S390x, None),
3615 "m68k" => (Architecture::M68k, None),
3616 "mips" | "mips32r6" => (Architecture::Mips, None),
3617 "mips64" | "mips64r6" => (
3618 if self.options.llvm_abiname.as_ref() == "n32" {
3624 Architecture::Mips64_N32
3625 } else {
3626 Architecture::Mips64
3627 },
3628 None,
3629 ),
3630 "x86_64" => (
3631 if self.pointer_width == 32 {
3632 Architecture::X86_64_X32
3633 } else {
3634 Architecture::X86_64
3635 },
3636 None,
3637 ),
3638 "powerpc" => (Architecture::PowerPc, None),
3639 "powerpc64" => (Architecture::PowerPc64, None),
3640 "riscv32" => (Architecture::Riscv32, None),
3641 "riscv64" => (Architecture::Riscv64, None),
3642 "sparc" => {
3643 if unstable_target_features.contains(&sym::v8plus) {
3644 (Architecture::Sparc32Plus, None)
3646 } else {
3647 (Architecture::Sparc, None)
3649 }
3650 }
3651 "sparc64" => (Architecture::Sparc64, None),
3652 "avr" => (Architecture::Avr, None),
3653 "msp430" => (Architecture::Msp430, None),
3654 "hexagon" => (Architecture::Hexagon, None),
3655 "bpf" => (Architecture::Bpf, None),
3656 "loongarch32" => (Architecture::LoongArch32, None),
3657 "loongarch64" => (Architecture::LoongArch64, None),
3658 "csky" => (Architecture::Csky, None),
3659 "arm64ec" => (Architecture::Aarch64, Some(object::SubArchitecture::Arm64EC)),
3660 _ => return None,
3662 })
3663 }
3664
3665 pub fn max_reliable_alignment(&self) -> Align {
3674 if self.is_like_windows && self.arch == "x86" {
3678 Align::from_bytes(4).unwrap()
3679 } else {
3680 Align::MAX
3681 }
3682 }
3683}
3684
3685#[derive(Clone, Debug)]
3687pub enum TargetTuple {
3688 TargetTuple(String),
3689 TargetJson {
3690 path_for_rustdoc: PathBuf,
3693 tuple: String,
3694 contents: String,
3695 },
3696}
3697
3698impl PartialEq for TargetTuple {
3700 fn eq(&self, other: &Self) -> bool {
3701 match (self, other) {
3702 (Self::TargetTuple(l0), Self::TargetTuple(r0)) => l0 == r0,
3703 (
3704 Self::TargetJson { path_for_rustdoc: _, tuple: l_tuple, contents: l_contents },
3705 Self::TargetJson { path_for_rustdoc: _, tuple: r_tuple, contents: r_contents },
3706 ) => l_tuple == r_tuple && l_contents == r_contents,
3707 _ => false,
3708 }
3709 }
3710}
3711
3712impl Hash for TargetTuple {
3714 fn hash<H: Hasher>(&self, state: &mut H) -> () {
3715 match self {
3716 TargetTuple::TargetTuple(tuple) => {
3717 0u8.hash(state);
3718 tuple.hash(state)
3719 }
3720 TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents } => {
3721 1u8.hash(state);
3722 tuple.hash(state);
3723 contents.hash(state)
3724 }
3725 }
3726 }
3727}
3728
3729impl<S: Encoder> Encodable<S> for TargetTuple {
3731 fn encode(&self, s: &mut S) {
3732 match self {
3733 TargetTuple::TargetTuple(tuple) => {
3734 s.emit_u8(0);
3735 s.emit_str(tuple);
3736 }
3737 TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents } => {
3738 s.emit_u8(1);
3739 s.emit_str(tuple);
3740 s.emit_str(contents);
3741 }
3742 }
3743 }
3744}
3745
3746impl<D: Decoder> Decodable<D> for TargetTuple {
3747 fn decode(d: &mut D) -> Self {
3748 match d.read_u8() {
3749 0 => TargetTuple::TargetTuple(d.read_str().to_owned()),
3750 1 => TargetTuple::TargetJson {
3751 path_for_rustdoc: PathBuf::new(),
3752 tuple: d.read_str().to_owned(),
3753 contents: d.read_str().to_owned(),
3754 },
3755 _ => {
3756 panic!("invalid enum variant tag while decoding `TargetTuple`, expected 0..2");
3757 }
3758 }
3759 }
3760}
3761
3762impl TargetTuple {
3763 pub fn from_tuple(tuple: &str) -> Self {
3765 TargetTuple::TargetTuple(tuple.into())
3766 }
3767
3768 pub fn from_path(path: &Path) -> Result<Self, io::Error> {
3770 let canonicalized_path = try_canonicalize(path)?;
3771 let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| {
3772 io::Error::new(
3773 io::ErrorKind::InvalidInput,
3774 format!("target path {canonicalized_path:?} is not a valid file: {err}"),
3775 )
3776 })?;
3777 let tuple = canonicalized_path
3778 .file_stem()
3779 .expect("target path must not be empty")
3780 .to_str()
3781 .expect("target path must be valid unicode")
3782 .to_owned();
3783 Ok(TargetTuple::TargetJson { path_for_rustdoc: canonicalized_path, tuple, contents })
3784 }
3785
3786 pub fn tuple(&self) -> &str {
3790 match *self {
3791 TargetTuple::TargetTuple(ref tuple) | TargetTuple::TargetJson { ref tuple, .. } => {
3792 tuple
3793 }
3794 }
3795 }
3796
3797 pub fn debug_tuple(&self) -> String {
3802 use std::hash::DefaultHasher;
3803
3804 match self {
3805 TargetTuple::TargetTuple(tuple) => tuple.to_owned(),
3806 TargetTuple::TargetJson { path_for_rustdoc: _, tuple, contents: content } => {
3807 let mut hasher = DefaultHasher::new();
3808 content.hash(&mut hasher);
3809 let hash = hasher.finish();
3810 format!("{tuple}-{hash}")
3811 }
3812 }
3813 }
3814}
3815
3816impl fmt::Display for TargetTuple {
3817 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3818 write!(f, "{}", self.debug_tuple())
3819 }
3820}
3821
3822into_diag_arg_using_display!(&TargetTuple);