]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_target/src/spec/mod.rs
Auto merge of #100395 - Dylan-DPC:rollup-ajrwo1s, r=Dylan-DPC
[rust.git] / compiler / rustc_target / src / spec / mod.rs
1 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
2 //!
3 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
4 //! allows new target triples to be defined in configuration files. Most users
5 //! will not need to care about these, but this is invaluable when porting Rust
6 //! to a new platform, and allows for an unprecedented level of control over how
7 //! the compiler works.
8 //!
9 //! # Using custom targets
10 //!
11 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
12 //! compared against the list of built-in targets. This is to ease distributing
13 //! rustc (no need for configuration files) and also to hold these built-in
14 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
15 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
16 //! will be loaded as the target configuration. If the file does not exist,
17 //! rustc will search each directory in the environment variable
18 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
19 //! be loaded. If no file is found in any of those directories, a fatal error
20 //! will be given.
21 //!
22 //! Projects defining their own targets should use
23 //! `--target=path/to/my-awesome-platform.json` instead of adding to
24 //! `RUST_TARGET_PATH`.
25 //!
26 //! # Defining a new target
27 //!
28 //! Targets are defined using [JSON](https://json.org/). The `Target` struct in
29 //! this module defines the format the JSON file should take, though each
30 //! underscore in the field names should be replaced with a hyphen (`-`) in the
31 //! JSON file. Some fields are required in every target specification, such as
32 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
33 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
34 //! the target's settings, though `target-feature` and `link-args` will *add*
35 //! to the list specified by the target, rather than replace.
36
37 use crate::abi::Endian;
38 use crate::json::{Json, ToJson};
39 use crate::spec::abi::{lookup as lookup_abi, Abi};
40 use crate::spec::crt_objects::{CrtObjects, LinkSelfContainedDefault};
41 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
42 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
43 use rustc_span::symbol::{sym, Symbol};
44 use serde_json::Value;
45 use std::borrow::Cow;
46 use std::collections::BTreeMap;
47 use std::convert::TryFrom;
48 use std::hash::{Hash, Hasher};
49 use std::iter::FromIterator;
50 use std::ops::{Deref, DerefMut};
51 use std::path::{Path, PathBuf};
52 use std::str::FromStr;
53 use std::{fmt, io};
54
55 use rustc_macros::HashStable_Generic;
56
57 pub mod abi;
58 pub mod crt_objects;
59
60 mod android_base;
61 mod apple_base;
62 mod apple_sdk_base;
63 mod avr_gnu_base;
64 mod bpf_base;
65 mod dragonfly_base;
66 mod freebsd_base;
67 mod fuchsia_base;
68 mod haiku_base;
69 mod hermit_base;
70 mod illumos_base;
71 mod l4re_base;
72 mod linux_base;
73 mod linux_gnu_base;
74 mod linux_kernel_base;
75 mod linux_musl_base;
76 mod linux_uclibc_base;
77 mod msvc_base;
78 mod netbsd_base;
79 mod openbsd_base;
80 mod redox_base;
81 mod solaris_base;
82 mod solid_base;
83 mod thumb_base;
84 mod uefi_msvc_base;
85 mod vxworks_base;
86 mod wasm_base;
87 mod windows_gnu_base;
88 mod windows_gnullvm_base;
89 mod windows_msvc_base;
90 mod windows_uwp_gnu_base;
91 mod windows_uwp_msvc_base;
92
93 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
94 pub enum LinkerFlavor {
95     Em,
96     Gcc,
97     L4Bender,
98     Ld,
99     Msvc,
100     Lld(LldFlavor),
101     PtxLinker,
102     BpfLinker,
103 }
104
105 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
106 pub enum LldFlavor {
107     Wasm,
108     Ld64,
109     Ld,
110     Link,
111 }
112
113 impl LldFlavor {
114     pub fn as_str(&self) -> &'static str {
115         match self {
116             LldFlavor::Wasm => "wasm",
117             LldFlavor::Ld64 => "darwin",
118             LldFlavor::Ld => "gnu",
119             LldFlavor::Link => "link",
120         }
121     }
122
123     fn from_str(s: &str) -> Option<Self> {
124         Some(match s {
125             "darwin" => LldFlavor::Ld64,
126             "gnu" => LldFlavor::Ld,
127             "link" => LldFlavor::Link,
128             "wasm" => LldFlavor::Wasm,
129             _ => return None,
130         })
131     }
132 }
133
134 impl ToJson for LldFlavor {
135     fn to_json(&self) -> Json {
136         self.as_str().to_json()
137     }
138 }
139
140 impl ToJson for LinkerFlavor {
141     fn to_json(&self) -> Json {
142         self.desc().to_json()
143     }
144 }
145 macro_rules! flavor_mappings {
146     ($((($($flavor:tt)*), $string:expr),)*) => (
147         impl LinkerFlavor {
148             pub const fn one_of() -> &'static str {
149                 concat!("one of: ", $($string, " ",)*)
150             }
151
152             pub fn from_str(s: &str) -> Option<Self> {
153                 Some(match s {
154                     $($string => $($flavor)*,)*
155                     _ => return None,
156                 })
157             }
158
159             pub fn desc(&self) -> &str {
160                 match *self {
161                     $($($flavor)* => $string,)*
162                 }
163             }
164         }
165     )
166 }
167
168 flavor_mappings! {
169     ((LinkerFlavor::Em), "em"),
170     ((LinkerFlavor::Gcc), "gcc"),
171     ((LinkerFlavor::L4Bender), "l4-bender"),
172     ((LinkerFlavor::Ld), "ld"),
173     ((LinkerFlavor::Msvc), "msvc"),
174     ((LinkerFlavor::PtxLinker), "ptx-linker"),
175     ((LinkerFlavor::BpfLinker), "bpf-linker"),
176     ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
177     ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
178     ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
179     ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
180 }
181
182 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
183 pub enum PanicStrategy {
184     Unwind,
185     Abort,
186 }
187
188 impl PanicStrategy {
189     pub fn desc(&self) -> &str {
190         match *self {
191             PanicStrategy::Unwind => "unwind",
192             PanicStrategy::Abort => "abort",
193         }
194     }
195
196     pub const fn desc_symbol(&self) -> Symbol {
197         match *self {
198             PanicStrategy::Unwind => sym::unwind,
199             PanicStrategy::Abort => sym::abort,
200         }
201     }
202
203     pub const fn all() -> [Symbol; 2] {
204         [Self::Abort.desc_symbol(), Self::Unwind.desc_symbol()]
205     }
206 }
207
208 impl ToJson for PanicStrategy {
209     fn to_json(&self) -> Json {
210         match *self {
211             PanicStrategy::Abort => "abort".to_json(),
212             PanicStrategy::Unwind => "unwind".to_json(),
213         }
214     }
215 }
216
217 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
218 pub enum RelroLevel {
219     Full,
220     Partial,
221     Off,
222     None,
223 }
224
225 impl RelroLevel {
226     pub fn desc(&self) -> &str {
227         match *self {
228             RelroLevel::Full => "full",
229             RelroLevel::Partial => "partial",
230             RelroLevel::Off => "off",
231             RelroLevel::None => "none",
232         }
233     }
234 }
235
236 impl FromStr for RelroLevel {
237     type Err = ();
238
239     fn from_str(s: &str) -> Result<RelroLevel, ()> {
240         match s {
241             "full" => Ok(RelroLevel::Full),
242             "partial" => Ok(RelroLevel::Partial),
243             "off" => Ok(RelroLevel::Off),
244             "none" => Ok(RelroLevel::None),
245             _ => Err(()),
246         }
247     }
248 }
249
250 impl ToJson for RelroLevel {
251     fn to_json(&self) -> Json {
252         match *self {
253             RelroLevel::Full => "full".to_json(),
254             RelroLevel::Partial => "partial".to_json(),
255             RelroLevel::Off => "off".to_json(),
256             RelroLevel::None => "None".to_json(),
257         }
258     }
259 }
260
261 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
262 pub enum MergeFunctions {
263     Disabled,
264     Trampolines,
265     Aliases,
266 }
267
268 impl MergeFunctions {
269     pub fn desc(&self) -> &str {
270         match *self {
271             MergeFunctions::Disabled => "disabled",
272             MergeFunctions::Trampolines => "trampolines",
273             MergeFunctions::Aliases => "aliases",
274         }
275     }
276 }
277
278 impl FromStr for MergeFunctions {
279     type Err = ();
280
281     fn from_str(s: &str) -> Result<MergeFunctions, ()> {
282         match s {
283             "disabled" => Ok(MergeFunctions::Disabled),
284             "trampolines" => Ok(MergeFunctions::Trampolines),
285             "aliases" => Ok(MergeFunctions::Aliases),
286             _ => Err(()),
287         }
288     }
289 }
290
291 impl ToJson for MergeFunctions {
292     fn to_json(&self) -> Json {
293         match *self {
294             MergeFunctions::Disabled => "disabled".to_json(),
295             MergeFunctions::Trampolines => "trampolines".to_json(),
296             MergeFunctions::Aliases => "aliases".to_json(),
297         }
298     }
299 }
300
301 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
302 pub enum RelocModel {
303     Static,
304     Pic,
305     Pie,
306     DynamicNoPic,
307     Ropi,
308     Rwpi,
309     RopiRwpi,
310 }
311
312 impl FromStr for RelocModel {
313     type Err = ();
314
315     fn from_str(s: &str) -> Result<RelocModel, ()> {
316         Ok(match s {
317             "static" => RelocModel::Static,
318             "pic" => RelocModel::Pic,
319             "pie" => RelocModel::Pie,
320             "dynamic-no-pic" => RelocModel::DynamicNoPic,
321             "ropi" => RelocModel::Ropi,
322             "rwpi" => RelocModel::Rwpi,
323             "ropi-rwpi" => RelocModel::RopiRwpi,
324             _ => return Err(()),
325         })
326     }
327 }
328
329 impl ToJson for RelocModel {
330     fn to_json(&self) -> Json {
331         match *self {
332             RelocModel::Static => "static",
333             RelocModel::Pic => "pic",
334             RelocModel::Pie => "pie",
335             RelocModel::DynamicNoPic => "dynamic-no-pic",
336             RelocModel::Ropi => "ropi",
337             RelocModel::Rwpi => "rwpi",
338             RelocModel::RopiRwpi => "ropi-rwpi",
339         }
340         .to_json()
341     }
342 }
343
344 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
345 pub enum CodeModel {
346     Tiny,
347     Small,
348     Kernel,
349     Medium,
350     Large,
351 }
352
353 impl FromStr for CodeModel {
354     type Err = ();
355
356     fn from_str(s: &str) -> Result<CodeModel, ()> {
357         Ok(match s {
358             "tiny" => CodeModel::Tiny,
359             "small" => CodeModel::Small,
360             "kernel" => CodeModel::Kernel,
361             "medium" => CodeModel::Medium,
362             "large" => CodeModel::Large,
363             _ => return Err(()),
364         })
365     }
366 }
367
368 impl ToJson for CodeModel {
369     fn to_json(&self) -> Json {
370         match *self {
371             CodeModel::Tiny => "tiny",
372             CodeModel::Small => "small",
373             CodeModel::Kernel => "kernel",
374             CodeModel::Medium => "medium",
375             CodeModel::Large => "large",
376         }
377         .to_json()
378     }
379 }
380
381 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
382 pub enum TlsModel {
383     GeneralDynamic,
384     LocalDynamic,
385     InitialExec,
386     LocalExec,
387 }
388
389 impl FromStr for TlsModel {
390     type Err = ();
391
392     fn from_str(s: &str) -> Result<TlsModel, ()> {
393         Ok(match s {
394             // Note the difference "general" vs "global" difference. The model name is "general",
395             // but the user-facing option name is "global" for consistency with other compilers.
396             "global-dynamic" => TlsModel::GeneralDynamic,
397             "local-dynamic" => TlsModel::LocalDynamic,
398             "initial-exec" => TlsModel::InitialExec,
399             "local-exec" => TlsModel::LocalExec,
400             _ => return Err(()),
401         })
402     }
403 }
404
405 impl ToJson for TlsModel {
406     fn to_json(&self) -> Json {
407         match *self {
408             TlsModel::GeneralDynamic => "global-dynamic",
409             TlsModel::LocalDynamic => "local-dynamic",
410             TlsModel::InitialExec => "initial-exec",
411             TlsModel::LocalExec => "local-exec",
412         }
413         .to_json()
414     }
415 }
416
417 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
418 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
419 pub enum LinkOutputKind {
420     /// Dynamically linked non position-independent executable.
421     DynamicNoPicExe,
422     /// Dynamically linked position-independent executable.
423     DynamicPicExe,
424     /// Statically linked non position-independent executable.
425     StaticNoPicExe,
426     /// Statically linked position-independent executable.
427     StaticPicExe,
428     /// Regular dynamic library ("dynamically linked").
429     DynamicDylib,
430     /// Dynamic library with bundled libc ("statically linked").
431     StaticDylib,
432     /// WASI module with a lifetime past the _initialize entry point
433     WasiReactorExe,
434 }
435
436 impl LinkOutputKind {
437     fn as_str(&self) -> &'static str {
438         match self {
439             LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
440             LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
441             LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
442             LinkOutputKind::StaticPicExe => "static-pic-exe",
443             LinkOutputKind::DynamicDylib => "dynamic-dylib",
444             LinkOutputKind::StaticDylib => "static-dylib",
445             LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
446         }
447     }
448
449     pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
450         Some(match s {
451             "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
452             "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
453             "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
454             "static-pic-exe" => LinkOutputKind::StaticPicExe,
455             "dynamic-dylib" => LinkOutputKind::DynamicDylib,
456             "static-dylib" => LinkOutputKind::StaticDylib,
457             "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
458             _ => return None,
459         })
460     }
461 }
462
463 impl fmt::Display for LinkOutputKind {
464     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465         f.write_str(self.as_str())
466     }
467 }
468
469 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<StaticCow<str>>>;
470
471 /// Which kind of debuginfo does the target use?
472 ///
473 /// Useful in determining whether a target supports Split DWARF (a target with
474 /// `DebuginfoKind::Dwarf` and supporting `SplitDebuginfo::Unpacked` for example).
475 #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
476 pub enum DebuginfoKind {
477     /// DWARF debuginfo (such as that used on `x86_64_unknown_linux_gnu`).
478     #[default]
479     Dwarf,
480     /// DWARF debuginfo in dSYM files (such as on Apple platforms).
481     DwarfDsym,
482     /// Program database files (such as on Windows).
483     Pdb,
484 }
485
486 impl DebuginfoKind {
487     fn as_str(&self) -> &'static str {
488         match self {
489             DebuginfoKind::Dwarf => "dwarf",
490             DebuginfoKind::DwarfDsym => "dwarf-dsym",
491             DebuginfoKind::Pdb => "pdb",
492         }
493     }
494 }
495
496 impl FromStr for DebuginfoKind {
497     type Err = ();
498
499     fn from_str(s: &str) -> Result<Self, ()> {
500         Ok(match s {
501             "dwarf" => DebuginfoKind::Dwarf,
502             "dwarf-dsym" => DebuginfoKind::DwarfDsym,
503             "pdb" => DebuginfoKind::Pdb,
504             _ => return Err(()),
505         })
506     }
507 }
508
509 impl ToJson for DebuginfoKind {
510     fn to_json(&self) -> Json {
511         self.as_str().to_json()
512     }
513 }
514
515 impl fmt::Display for DebuginfoKind {
516     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517         f.write_str(self.as_str())
518     }
519 }
520
521 #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
522 pub enum SplitDebuginfo {
523     /// Split debug-information is disabled, meaning that on supported platforms
524     /// you can find all debug information in the executable itself. This is
525     /// only supported for ELF effectively.
526     ///
527     /// * Windows - not supported
528     /// * macOS - don't run `dsymutil`
529     /// * ELF - `.debug_*` sections
530     #[default]
531     Off,
532
533     /// Split debug-information can be found in a "packed" location separate
534     /// from the final artifact. This is supported on all platforms.
535     ///
536     /// * Windows - `*.pdb`
537     /// * macOS - `*.dSYM` (run `dsymutil`)
538     /// * ELF - `*.dwp` (run `thorin`)
539     Packed,
540
541     /// Split debug-information can be found in individual object files on the
542     /// filesystem. The main executable may point to the object files.
543     ///
544     /// * Windows - not supported
545     /// * macOS - supported, scattered object files
546     /// * ELF - supported, scattered `*.dwo` or `*.o` files (see `SplitDwarfKind`)
547     Unpacked,
548 }
549
550 impl SplitDebuginfo {
551     fn as_str(&self) -> &'static str {
552         match self {
553             SplitDebuginfo::Off => "off",
554             SplitDebuginfo::Packed => "packed",
555             SplitDebuginfo::Unpacked => "unpacked",
556         }
557     }
558 }
559
560 impl FromStr for SplitDebuginfo {
561     type Err = ();
562
563     fn from_str(s: &str) -> Result<Self, ()> {
564         Ok(match s {
565             "off" => SplitDebuginfo::Off,
566             "unpacked" => SplitDebuginfo::Unpacked,
567             "packed" => SplitDebuginfo::Packed,
568             _ => return Err(()),
569         })
570     }
571 }
572
573 impl ToJson for SplitDebuginfo {
574     fn to_json(&self) -> Json {
575         self.as_str().to_json()
576     }
577 }
578
579 impl fmt::Display for SplitDebuginfo {
580     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
581         f.write_str(self.as_str())
582     }
583 }
584
585 #[derive(Clone, Debug, PartialEq, Eq)]
586 pub enum StackProbeType {
587     /// Don't emit any stack probes.
588     None,
589     /// It is harmless to use this option even on targets that do not have backend support for
590     /// stack probes as the failure mode is the same as if no stack-probe option was specified in
591     /// the first place.
592     Inline,
593     /// Call `__rust_probestack` whenever stack needs to be probed.
594     Call,
595     /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
596     /// and call `__rust_probestack` otherwise.
597     InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
598 }
599
600 impl StackProbeType {
601     fn from_json(json: &Json) -> Result<Self, String> {
602         let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
603         let kind = object
604             .get("kind")
605             .and_then(|o| o.as_str())
606             .ok_or_else(|| "expected `kind` to be a string")?;
607         match kind {
608             "none" => Ok(StackProbeType::None),
609             "inline" => Ok(StackProbeType::Inline),
610             "call" => Ok(StackProbeType::Call),
611             "inline-or-call" => {
612                 let min_version = object
613                     .get("min-llvm-version-for-inline")
614                     .and_then(|o| o.as_array())
615                     .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
616                 let mut iter = min_version.into_iter().map(|v| {
617                     let int = v.as_u64().ok_or_else(
618                         || "expected `min-llvm-version-for-inline` values to be integers",
619                     )?;
620                     u32::try_from(int)
621                         .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
622                 });
623                 let min_llvm_version_for_inline = (
624                     iter.next().unwrap_or(Ok(11))?,
625                     iter.next().unwrap_or(Ok(0))?,
626                     iter.next().unwrap_or(Ok(0))?,
627                 );
628                 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
629             }
630             _ => Err(String::from(
631                 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
632             )),
633         }
634     }
635 }
636
637 impl ToJson for StackProbeType {
638     fn to_json(&self) -> Json {
639         Json::Object(match self {
640             StackProbeType::None => {
641                 [(String::from("kind"), "none".to_json())].into_iter().collect()
642             }
643             StackProbeType::Inline => {
644                 [(String::from("kind"), "inline".to_json())].into_iter().collect()
645             }
646             StackProbeType::Call => {
647                 [(String::from("kind"), "call".to_json())].into_iter().collect()
648             }
649             StackProbeType::InlineOrCall { min_llvm_version_for_inline: (maj, min, patch) } => [
650                 (String::from("kind"), "inline-or-call".to_json()),
651                 (
652                     String::from("min-llvm-version-for-inline"),
653                     Json::Array(vec![maj.to_json(), min.to_json(), patch.to_json()]),
654                 ),
655             ]
656             .into_iter()
657             .collect(),
658         })
659     }
660 }
661
662 bitflags::bitflags! {
663     #[derive(Default, Encodable, Decodable)]
664     pub struct SanitizerSet: u8 {
665         const ADDRESS = 1 << 0;
666         const LEAK    = 1 << 1;
667         const MEMORY  = 1 << 2;
668         const THREAD  = 1 << 3;
669         const HWADDRESS = 1 << 4;
670         const CFI     = 1 << 5;
671         const MEMTAG  = 1 << 6;
672         const SHADOWCALLSTACK = 1 << 7;
673     }
674 }
675
676 impl SanitizerSet {
677     /// Return sanitizer's name
678     ///
679     /// Returns none if the flags is a set of sanitizers numbering not exactly one.
680     pub fn as_str(self) -> Option<&'static str> {
681         Some(match self {
682             SanitizerSet::ADDRESS => "address",
683             SanitizerSet::CFI => "cfi",
684             SanitizerSet::LEAK => "leak",
685             SanitizerSet::MEMORY => "memory",
686             SanitizerSet::MEMTAG => "memtag",
687             SanitizerSet::SHADOWCALLSTACK => "shadow-call-stack",
688             SanitizerSet::THREAD => "thread",
689             SanitizerSet::HWADDRESS => "hwaddress",
690             _ => return None,
691         })
692     }
693 }
694
695 /// Formats a sanitizer set as a comma separated list of sanitizers' names.
696 impl fmt::Display for SanitizerSet {
697     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698         let mut first = true;
699         for s in *self {
700             let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s));
701             if !first {
702                 f.write_str(", ")?;
703             }
704             f.write_str(name)?;
705             first = false;
706         }
707         Ok(())
708     }
709 }
710
711 impl IntoIterator for SanitizerSet {
712     type Item = SanitizerSet;
713     type IntoIter = std::vec::IntoIter<SanitizerSet>;
714
715     fn into_iter(self) -> Self::IntoIter {
716         [
717             SanitizerSet::ADDRESS,
718             SanitizerSet::CFI,
719             SanitizerSet::LEAK,
720             SanitizerSet::MEMORY,
721             SanitizerSet::MEMTAG,
722             SanitizerSet::SHADOWCALLSTACK,
723             SanitizerSet::THREAD,
724             SanitizerSet::HWADDRESS,
725         ]
726         .iter()
727         .copied()
728         .filter(|&s| self.contains(s))
729         .collect::<Vec<_>>()
730         .into_iter()
731     }
732 }
733
734 impl<CTX> HashStable<CTX> for SanitizerSet {
735     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
736         self.bits().hash_stable(ctx, hasher);
737     }
738 }
739
740 impl ToJson for SanitizerSet {
741     fn to_json(&self) -> Json {
742         self.into_iter()
743             .map(|v| Some(v.as_str()?.to_json()))
744             .collect::<Option<Vec<_>>>()
745             .unwrap_or_default()
746             .to_json()
747     }
748 }
749
750 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
751 pub enum FramePointer {
752     /// Forces the machine code generator to always preserve the frame pointers.
753     Always,
754     /// Forces the machine code generator to preserve the frame pointers except for the leaf
755     /// functions (i.e. those that don't call other functions).
756     NonLeaf,
757     /// Allows the machine code generator to omit the frame pointers.
758     ///
759     /// This option does not guarantee that the frame pointers will be omitted.
760     MayOmit,
761 }
762
763 impl FromStr for FramePointer {
764     type Err = ();
765     fn from_str(s: &str) -> Result<Self, ()> {
766         Ok(match s {
767             "always" => Self::Always,
768             "non-leaf" => Self::NonLeaf,
769             "may-omit" => Self::MayOmit,
770             _ => return Err(()),
771         })
772     }
773 }
774
775 impl ToJson for FramePointer {
776     fn to_json(&self) -> Json {
777         match *self {
778             Self::Always => "always",
779             Self::NonLeaf => "non-leaf",
780             Self::MayOmit => "may-omit",
781         }
782         .to_json()
783     }
784 }
785
786 /// Controls use of stack canaries.
787 #[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)]
788 pub enum StackProtector {
789     /// Disable stack canary generation.
790     None,
791
792     /// On LLVM, mark all generated LLVM functions with the `ssp` attribute (see
793     /// llvm/docs/LangRef.rst). This triggers stack canary generation in
794     /// functions which contain an array of a byte-sized type with more than
795     /// eight elements.
796     Basic,
797
798     /// On LLVM, mark all generated LLVM functions with the `sspstrong`
799     /// attribute (see llvm/docs/LangRef.rst). This triggers stack canary
800     /// generation in functions which either contain an array, or which take
801     /// the address of a local variable.
802     Strong,
803
804     /// Generate stack canaries in all functions.
805     All,
806 }
807
808 impl StackProtector {
809     fn as_str(&self) -> &'static str {
810         match self {
811             StackProtector::None => "none",
812             StackProtector::Basic => "basic",
813             StackProtector::Strong => "strong",
814             StackProtector::All => "all",
815         }
816     }
817 }
818
819 impl FromStr for StackProtector {
820     type Err = ();
821
822     fn from_str(s: &str) -> Result<StackProtector, ()> {
823         Ok(match s {
824             "none" => StackProtector::None,
825             "basic" => StackProtector::Basic,
826             "strong" => StackProtector::Strong,
827             "all" => StackProtector::All,
828             _ => return Err(()),
829         })
830     }
831 }
832
833 impl fmt::Display for StackProtector {
834     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
835         f.write_str(self.as_str())
836     }
837 }
838
839 macro_rules! supported_targets {
840     ( $(($triple:literal, $module:ident ),)+ ) => {
841         $(mod $module;)+
842
843         /// List of supported targets
844         pub const TARGETS: &[&str] = &[$($triple),+];
845
846         fn load_builtin(target: &str) -> Option<Target> {
847             let mut t = match target {
848                 $( $triple => $module::target(), )+
849                 _ => return None,
850             };
851             t.is_builtin = true;
852             debug!("got builtin target: {:?}", t);
853             Some(t)
854         }
855
856         #[cfg(test)]
857         mod tests {
858             mod tests_impl;
859
860             // Cannot put this into a separate file without duplication, make an exception.
861             $(
862                 #[test] // `#[test]`
863                 fn $module() {
864                     tests_impl::test_target(super::$module::target(), $triple);
865                 }
866             )+
867         }
868     };
869 }
870
871 supported_targets! {
872     ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
873     ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
874     ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
875     ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
876     ("m68k-unknown-linux-gnu", m68k_unknown_linux_gnu),
877     ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
878     ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
879     ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
880     ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
881     ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
882     ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
883     ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
884     ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
885     ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
886     ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
887     ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
888     ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
889     ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
890     ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
891     ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
892     ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
893     ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
894     ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
895     ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
896     ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
897     ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
898     ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
899     ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
900     ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
901     ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
902     ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
903     ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
904     ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
905     ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
906     ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
907     ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
908     ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
909     ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
910     ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
911     ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
912     ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
913     ("i686-unknown-linux-musl", i686_unknown_linux_musl),
914     ("i586-unknown-linux-musl", i586_unknown_linux_musl),
915     ("mips-unknown-linux-musl", mips_unknown_linux_musl),
916     ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
917     ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
918     ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
919     ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
920
921     ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
922     ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
923
924     ("i686-linux-android", i686_linux_android),
925     ("x86_64-linux-android", x86_64_linux_android),
926     ("arm-linux-androideabi", arm_linux_androideabi),
927     ("armv7-linux-androideabi", armv7_linux_androideabi),
928     ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
929     ("aarch64-linux-android", aarch64_linux_android),
930
931     ("x86_64-unknown-none-linuxkernel", x86_64_unknown_none_linuxkernel),
932
933     ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
934     ("armv6-unknown-freebsd", armv6_unknown_freebsd),
935     ("armv7-unknown-freebsd", armv7_unknown_freebsd),
936     ("i686-unknown-freebsd", i686_unknown_freebsd),
937     ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
938     ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
939     ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
940     ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
941     ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
942
943     ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
944
945     ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
946     ("i686-unknown-openbsd", i686_unknown_openbsd),
947     ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
948     ("powerpc64-unknown-openbsd", powerpc64_unknown_openbsd),
949     ("riscv64gc-unknown-openbsd", riscv64gc_unknown_openbsd),
950     ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
951     ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
952
953     ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
954     ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
955     ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
956     ("i686-unknown-netbsd", i686_unknown_netbsd),
957     ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
958     ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
959     ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
960
961     ("i686-unknown-haiku", i686_unknown_haiku),
962     ("x86_64-unknown-haiku", x86_64_unknown_haiku),
963
964     ("aarch64-apple-darwin", aarch64_apple_darwin),
965     ("x86_64-apple-darwin", x86_64_apple_darwin),
966     ("i686-apple-darwin", i686_apple_darwin),
967
968     ("aarch64-fuchsia", aarch64_fuchsia),
969     ("x86_64-fuchsia", x86_64_fuchsia),
970
971     ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
972
973     ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
974
975     ("aarch64-unknown-redox", aarch64_unknown_redox),
976     ("x86_64-unknown-redox", x86_64_unknown_redox),
977
978     ("i386-apple-ios", i386_apple_ios),
979     ("x86_64-apple-ios", x86_64_apple_ios),
980     ("aarch64-apple-ios", aarch64_apple_ios),
981     ("armv7-apple-ios", armv7_apple_ios),
982     ("armv7s-apple-ios", armv7s_apple_ios),
983     ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
984     ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
985     ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
986     ("aarch64-apple-tvos", aarch64_apple_tvos),
987     ("x86_64-apple-tvos", x86_64_apple_tvos),
988
989     ("armv7k-apple-watchos", armv7k_apple_watchos),
990     ("arm64_32-apple-watchos", arm64_32_apple_watchos),
991     ("x86_64-apple-watchos-sim", x86_64_apple_watchos_sim),
992     ("aarch64-apple-watchos-sim", aarch64_apple_watchos_sim),
993
994     ("armebv7r-none-eabi", armebv7r_none_eabi),
995     ("armebv7r-none-eabihf", armebv7r_none_eabihf),
996     ("armv7r-none-eabi", armv7r_none_eabi),
997     ("armv7r-none-eabihf", armv7r_none_eabihf),
998
999     ("x86_64-pc-solaris", x86_64_pc_solaris),
1000     ("x86_64-sun-solaris", x86_64_sun_solaris),
1001     ("sparcv9-sun-solaris", sparcv9_sun_solaris),
1002
1003     ("x86_64-unknown-illumos", x86_64_unknown_illumos),
1004
1005     ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
1006     ("i686-pc-windows-gnu", i686_pc_windows_gnu),
1007     ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
1008     ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
1009
1010     ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
1011     ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
1012
1013     ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
1014     ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
1015     ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
1016     ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
1017     ("i686-pc-windows-msvc", i686_pc_windows_msvc),
1018     ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
1019     ("i586-pc-windows-msvc", i586_pc_windows_msvc),
1020     ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
1021     ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
1022
1023     ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
1024     ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
1025     ("wasm32-unknown-unknown", wasm32_unknown_unknown),
1026     ("wasm32-wasi", wasm32_wasi),
1027     ("wasm64-unknown-unknown", wasm64_unknown_unknown),
1028
1029     ("thumbv6m-none-eabi", thumbv6m_none_eabi),
1030     ("thumbv7m-none-eabi", thumbv7m_none_eabi),
1031     ("thumbv7em-none-eabi", thumbv7em_none_eabi),
1032     ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
1033     ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
1034     ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
1035     ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
1036
1037     ("armv7a-none-eabi", armv7a_none_eabi),
1038     ("armv7a-none-eabihf", armv7a_none_eabihf),
1039
1040     ("msp430-none-elf", msp430_none_elf),
1041
1042     ("aarch64-unknown-hermit", aarch64_unknown_hermit),
1043     ("x86_64-unknown-hermit", x86_64_unknown_hermit),
1044
1045     ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
1046     ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
1047     ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
1048     ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
1049     ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
1050     ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
1051     ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
1052     ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
1053     ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
1054     ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
1055     ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
1056     ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
1057
1058     ("aarch64-unknown-none", aarch64_unknown_none),
1059     ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
1060
1061     ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
1062
1063     ("x86_64-unknown-uefi", x86_64_unknown_uefi),
1064     ("i686-unknown-uefi", i686_unknown_uefi),
1065     ("aarch64-unknown-uefi", aarch64_unknown_uefi),
1066
1067     ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1068
1069     ("i686-wrs-vxworks", i686_wrs_vxworks),
1070     ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1071     ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1072     ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1073     ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1074     ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1075     ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1076
1077     ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1078     ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1079     ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1080
1081     ("mipsel-sony-psp", mipsel_sony_psp),
1082     ("mipsel-unknown-none", mipsel_unknown_none),
1083     ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1084     ("armv4t-none-eabi", armv4t_none_eabi),
1085
1086     ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1087     ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1088     ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1089
1090     ("bpfeb-unknown-none", bpfeb_unknown_none),
1091     ("bpfel-unknown-none", bpfel_unknown_none),
1092
1093     ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1094
1095     ("aarch64-nintendo-switch-freestanding", aarch64_nintendo_switch_freestanding),
1096
1097     ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1098     ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1099
1100     ("x86_64-unknown-none", x86_64_unknown_none),
1101
1102     ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1103 }
1104
1105 /// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
1106 macro_rules! cvs {
1107     () => {
1108         ::std::borrow::Cow::Borrowed(&[])
1109     };
1110     ($($x:expr),+ $(,)?) => {
1111         ::std::borrow::Cow::Borrowed(&[
1112             $(
1113                 ::std::borrow::Cow::Borrowed($x),
1114             )*
1115         ])
1116     };
1117 }
1118
1119 pub(crate) use cvs;
1120
1121 /// Warnings encountered when parsing the target `json`.
1122 ///
1123 /// Includes fields that weren't recognized and fields that don't have the expected type.
1124 #[derive(Debug, PartialEq)]
1125 pub struct TargetWarnings {
1126     unused_fields: Vec<String>,
1127     incorrect_type: Vec<String>,
1128 }
1129
1130 impl TargetWarnings {
1131     pub fn empty() -> Self {
1132         Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1133     }
1134
1135     pub fn warning_messages(&self) -> Vec<String> {
1136         let mut warnings = vec![];
1137         if !self.unused_fields.is_empty() {
1138             warnings.push(format!(
1139                 "target json file contains unused fields: {}",
1140                 self.unused_fields.join(", ")
1141             ));
1142         }
1143         if !self.incorrect_type.is_empty() {
1144             warnings.push(format!(
1145                 "target json file contains fields whose value doesn't have the correct json type: {}",
1146                 self.incorrect_type.join(", ")
1147             ));
1148         }
1149         warnings
1150     }
1151 }
1152
1153 /// Everything `rustc` knows about how to compile for a specific target.
1154 ///
1155 /// Every field here must be specified, and has no default value.
1156 #[derive(PartialEq, Clone, Debug)]
1157 pub struct Target {
1158     /// Target triple to pass to LLVM.
1159     pub llvm_target: StaticCow<str>,
1160     /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1161     pub pointer_width: u32,
1162     /// Architecture to use for ABI considerations. Valid options include: "x86",
1163     /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1164     pub arch: StaticCow<str>,
1165     /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1166     pub data_layout: StaticCow<str>,
1167     /// Optional settings with defaults.
1168     pub options: TargetOptions,
1169 }
1170
1171 pub trait HasTargetSpec {
1172     fn target_spec(&self) -> &Target;
1173 }
1174
1175 impl HasTargetSpec for Target {
1176     #[inline]
1177     fn target_spec(&self) -> &Target {
1178         self
1179     }
1180 }
1181
1182 type StaticCow<T> = Cow<'static, T>;
1183
1184 /// Optional aspects of a target specification.
1185 ///
1186 /// This has an implementation of `Default`, see each field for what the default is. In general,
1187 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1188 ///
1189 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1190 /// construction, all its fields logically belong to `Target` and available from `Target`
1191 /// through `Deref` impls.
1192 #[derive(PartialEq, Clone, Debug)]
1193 pub struct TargetOptions {
1194     /// Whether the target is built-in or loaded from a custom target specification.
1195     pub is_builtin: bool,
1196
1197     /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1198     pub endian: Endian,
1199     /// Width of c_int type. Defaults to "32".
1200     pub c_int_width: StaticCow<str>,
1201     /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1202     /// "none" implies a bare metal target without `std` library.
1203     /// A couple of targets having `std` also use "unknown" as an `os` value,
1204     /// but they are exceptions.
1205     pub os: StaticCow<str>,
1206     /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1207     pub env: StaticCow<str>,
1208     /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1209     /// or `"eabihf"`. Defaults to "".
1210     pub abi: StaticCow<str>,
1211     /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1212     pub vendor: StaticCow<str>,
1213     /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1214     /// on the command line. Defaults to `LinkerFlavor::Gcc`.
1215     pub linker_flavor: LinkerFlavor,
1216
1217     /// Linker to invoke
1218     pub linker: Option<StaticCow<str>>,
1219
1220     /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
1221     /// without clarifying its flavor in any way.
1222     pub lld_flavor: LldFlavor,
1223
1224     /// Linker arguments that are passed *before* any user-defined libraries.
1225     pub pre_link_args: LinkArgs,
1226     /// Objects to link before and after all other object code.
1227     pub pre_link_objects: CrtObjects,
1228     pub post_link_objects: CrtObjects,
1229     /// Same as `(pre|post)_link_objects`, but when self-contained linking mode is enabled.
1230     pub pre_link_objects_self_contained: CrtObjects,
1231     pub post_link_objects_self_contained: CrtObjects,
1232     pub link_self_contained: LinkSelfContainedDefault,
1233
1234     /// Linker arguments that are unconditionally passed after any
1235     /// user-defined but before post-link objects. Standard platform
1236     /// libraries that should be always be linked to, usually go here.
1237     pub late_link_args: LinkArgs,
1238     /// Linker arguments used in addition to `late_link_args` if at least one
1239     /// Rust dependency is dynamically linked.
1240     pub late_link_args_dynamic: LinkArgs,
1241     /// Linker arguments used in addition to `late_link_args` if all Rust
1242     /// dependencies are statically linked.
1243     pub late_link_args_static: LinkArgs,
1244     /// Linker arguments that are unconditionally passed *after* any
1245     /// user-defined libraries.
1246     pub post_link_args: LinkArgs,
1247     /// Optional link script applied to `dylib` and `executable` crate types.
1248     /// This is a string containing the script, not a path. Can only be applied
1249     /// to linkers where `linker_is_gnu` is true.
1250     pub link_script: Option<StaticCow<str>>,
1251
1252     /// Environment variables to be set for the linker invocation.
1253     pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
1254     /// Environment variables to be removed for the linker invocation.
1255     pub link_env_remove: StaticCow<[StaticCow<str>]>,
1256
1257     /// Extra arguments to pass to the external assembler (when used)
1258     pub asm_args: StaticCow<[StaticCow<str>]>,
1259
1260     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1261     /// to "generic".
1262     pub cpu: StaticCow<str>,
1263     /// Default target features to pass to LLVM. These features will *always* be
1264     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1265     /// -mattr=$features`.
1266     pub features: StaticCow<str>,
1267     /// Whether dynamic linking is available on this target. Defaults to false.
1268     pub dynamic_linking: bool,
1269     /// If dynamic linking is available, whether only cdylibs are supported.
1270     pub only_cdylib: bool,
1271     /// Whether executables are available on this target. Defaults to true.
1272     pub executables: bool,
1273     /// Relocation model to use in object file. Corresponds to `llc
1274     /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1275     pub relocation_model: RelocModel,
1276     /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1277     /// Defaults to `None` which means "inherited from the base LLVM target".
1278     pub code_model: Option<CodeModel>,
1279     /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1280     /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1281     pub tls_model: TlsModel,
1282     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1283     pub disable_redzone: bool,
1284     /// Frame pointer mode for this target. Defaults to `MayOmit`.
1285     pub frame_pointer: FramePointer,
1286     /// Emit each function in its own section. Defaults to true.
1287     pub function_sections: bool,
1288     /// String to prepend to the name of every dynamic library. Defaults to "lib".
1289     pub dll_prefix: StaticCow<str>,
1290     /// String to append to the name of every dynamic library. Defaults to ".so".
1291     pub dll_suffix: StaticCow<str>,
1292     /// String to append to the name of every executable.
1293     pub exe_suffix: StaticCow<str>,
1294     /// String to prepend to the name of every static library. Defaults to "lib".
1295     pub staticlib_prefix: StaticCow<str>,
1296     /// String to append to the name of every static library. Defaults to ".a".
1297     pub staticlib_suffix: StaticCow<str>,
1298     /// Values of the `target_family` cfg set for this target.
1299     ///
1300     /// Common options are: "unix", "windows". Defaults to no families.
1301     ///
1302     /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1303     pub families: StaticCow<[StaticCow<str>]>,
1304     /// Whether the target toolchain's ABI supports returning small structs as an integer.
1305     pub abi_return_struct_as_int: bool,
1306     /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1307     /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1308     pub is_like_osx: bool,
1309     /// Whether the target toolchain is like Solaris's.
1310     /// Only useful for compiling against Illumos/Solaris,
1311     /// as they have a different set of linker flags. Defaults to false.
1312     pub is_like_solaris: bool,
1313     /// Whether the target is like Windows.
1314     /// This is a combination of several more specific properties represented as a single flag:
1315     ///   - The target uses a Windows ABI,
1316     ///   - uses PE/COFF as a format for object code,
1317     ///   - uses Windows-style dllexport/dllimport for shared libraries,
1318     ///   - uses import libraries and .def files for symbol exports,
1319     ///   - executables support setting a subsystem.
1320     pub is_like_windows: bool,
1321     /// Whether the target is like MSVC.
1322     /// This is a combination of several more specific properties represented as a single flag:
1323     ///   - The target has all the properties from `is_like_windows`
1324     ///     (for in-tree targets "is_like_msvc â‡’ is_like_windows" is ensured by a unit test),
1325     ///   - has some MSVC-specific Windows ABI properties,
1326     ///   - uses a link.exe-like linker,
1327     ///   - uses CodeView/PDB for debuginfo and natvis for its visualization,
1328     ///   - uses SEH-based unwinding,
1329     ///   - supports control flow guard mechanism.
1330     pub is_like_msvc: bool,
1331     /// Whether a target toolchain is like WASM.
1332     pub is_like_wasm: bool,
1333     /// Default supported version of DWARF on this platform.
1334     /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1335     pub default_dwarf_version: u32,
1336     /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1337     pub linker_is_gnu: bool,
1338     /// The MinGW toolchain has a known issue that prevents it from correctly
1339     /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1340     /// symbol needs its own COMDAT section, weak linkage implies a large
1341     /// number sections that easily exceeds the given limit for larger
1342     /// codebases. Consequently we want a way to disallow weak linkage on some
1343     /// platforms.
1344     pub allows_weak_linkage: bool,
1345     /// Whether the linker support rpaths or not. Defaults to false.
1346     pub has_rpath: bool,
1347     /// Whether to disable linking to the default libraries, typically corresponds
1348     /// to `-nodefaultlibs`. Defaults to true.
1349     pub no_default_libraries: bool,
1350     /// Dynamically linked executables can be compiled as position independent
1351     /// if the default relocation model of position independent code is not
1352     /// changed. This is a requirement to take advantage of ASLR, as otherwise
1353     /// the functions in the executable are not randomized and can be used
1354     /// during an exploit of a vulnerability in any code.
1355     pub position_independent_executables: bool,
1356     /// Executables that are both statically linked and position-independent are supported.
1357     pub static_position_independent_executables: bool,
1358     /// Determines if the target always requires using the PLT for indirect
1359     /// library calls or not. This controls the default value of the `-Z plt` flag.
1360     pub needs_plt: bool,
1361     /// Either partial, full, or off. Full RELRO makes the dynamic linker
1362     /// resolve all symbols at startup and marks the GOT read-only before
1363     /// starting the program, preventing overwriting the GOT.
1364     pub relro_level: RelroLevel,
1365     /// Format that archives should be emitted in. This affects whether we use
1366     /// LLVM to assemble an archive or fall back to the system linker, and
1367     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1368     /// the system linker to be used.
1369     pub archive_format: StaticCow<str>,
1370     /// Is asm!() allowed? Defaults to true.
1371     pub allow_asm: bool,
1372     /// Whether the runtime startup code requires the `main` function be passed
1373     /// `argc` and `argv` values.
1374     pub main_needs_argc_argv: bool,
1375
1376     /// Flag indicating whether #[thread_local] is available for this target.
1377     pub has_thread_local: bool,
1378     // This is mainly for easy compatibility with emscripten.
1379     // If we give emcc .o files that are actually .bc files it
1380     // will 'just work'.
1381     pub obj_is_bitcode: bool,
1382     /// Whether the target requires that emitted object code includes bitcode.
1383     pub forces_embed_bitcode: bool,
1384     /// Content of the LLVM cmdline section associated with embedded bitcode.
1385     pub bitcode_llvm_cmdline: StaticCow<str>,
1386
1387     /// Don't use this field; instead use the `.min_atomic_width()` method.
1388     pub min_atomic_width: Option<u64>,
1389
1390     /// Don't use this field; instead use the `.max_atomic_width()` method.
1391     pub max_atomic_width: Option<u64>,
1392
1393     /// Whether the target supports atomic CAS operations natively
1394     pub atomic_cas: bool,
1395
1396     /// Panic strategy: "unwind" or "abort"
1397     pub panic_strategy: PanicStrategy,
1398
1399     /// Whether or not linking dylibs to a static CRT is allowed.
1400     pub crt_static_allows_dylibs: bool,
1401     /// Whether or not the CRT is statically linked by default.
1402     pub crt_static_default: bool,
1403     /// Whether or not crt-static is respected by the compiler (or is a no-op).
1404     pub crt_static_respected: bool,
1405
1406     /// The implementation of stack probes to use.
1407     pub stack_probes: StackProbeType,
1408
1409     /// The minimum alignment for global symbols.
1410     pub min_global_align: Option<u64>,
1411
1412     /// Default number of codegen units to use in debug mode
1413     pub default_codegen_units: Option<u64>,
1414
1415     /// Whether to generate trap instructions in places where optimization would
1416     /// otherwise produce control flow that falls through into unrelated memory.
1417     pub trap_unreachable: bool,
1418
1419     /// This target requires everything to be compiled with LTO to emit a final
1420     /// executable, aka there is no native linker for this target.
1421     pub requires_lto: bool,
1422
1423     /// This target has no support for threads.
1424     pub singlethread: bool,
1425
1426     /// Whether library functions call lowering/optimization is disabled in LLVM
1427     /// for this target unconditionally.
1428     pub no_builtins: bool,
1429
1430     /// The default visibility for symbols in this target should be "hidden"
1431     /// rather than "default"
1432     pub default_hidden_visibility: bool,
1433
1434     /// Whether a .debug_gdb_scripts section will be added to the output object file
1435     pub emit_debug_gdb_scripts: bool,
1436
1437     /// Whether or not to unconditionally `uwtable` attributes on functions,
1438     /// typically because the platform needs to unwind for things like stack
1439     /// unwinders.
1440     pub requires_uwtable: bool,
1441
1442     /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1443     /// is not specified and `uwtable` is not required on this target.
1444     pub default_uwtable: bool,
1445
1446     /// Whether or not SIMD types are passed by reference in the Rust ABI,
1447     /// typically required if a target can be compiled with a mixed set of
1448     /// target features. This is `true` by default, and `false` for targets like
1449     /// wasm32 where the whole program either has simd or not.
1450     pub simd_types_indirect: bool,
1451
1452     /// Pass a list of symbol which should be exported in the dylib to the linker.
1453     pub limit_rdylib_exports: bool,
1454
1455     /// If set, have the linker export exactly these symbols, instead of using
1456     /// the usual logic to figure this out from the crate itself.
1457     pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
1458
1459     /// Determines how or whether the MergeFunctions LLVM pass should run for
1460     /// this target. Either "disabled", "trampolines", or "aliases".
1461     /// The MergeFunctions pass is generally useful, but some targets may need
1462     /// to opt out. The default is "aliases".
1463     ///
1464     /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1465     pub merge_functions: MergeFunctions,
1466
1467     /// Use platform dependent mcount function
1468     pub mcount: StaticCow<str>,
1469
1470     /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1471     pub llvm_abiname: StaticCow<str>,
1472
1473     /// Whether or not RelaxElfRelocation flag will be passed to the linker
1474     pub relax_elf_relocations: bool,
1475
1476     /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1477     pub llvm_args: StaticCow<[StaticCow<str>]>,
1478
1479     /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1480     /// to false (uses .init_array).
1481     pub use_ctors_section: bool,
1482
1483     /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1484     /// used to locate unwinding information is passed
1485     /// (only has effect if the linker is `ld`-like).
1486     pub eh_frame_header: bool,
1487
1488     /// Is true if the target is an ARM architecture using thumb v1 which allows for
1489     /// thumb and arm interworking.
1490     pub has_thumb_interworking: bool,
1491
1492     /// Which kind of debuginfo is used by this target?
1493     pub debuginfo_kind: DebuginfoKind,
1494     /// How to handle split debug information, if at all. Specifying `None` has
1495     /// target-specific meaning.
1496     pub split_debuginfo: SplitDebuginfo,
1497     /// Which kinds of split debuginfo are supported by the target?
1498     pub supported_split_debuginfo: StaticCow<[SplitDebuginfo]>,
1499
1500     /// The sanitizers supported by this target
1501     ///
1502     /// Note that the support here is at a codegen level. If the machine code with sanitizer
1503     /// enabled can generated on this target, but the necessary supporting libraries are not
1504     /// distributed with the target, the sanitizer should still appear in this list for the target.
1505     pub supported_sanitizers: SanitizerSet,
1506
1507     /// If present it's a default value to use for adjusting the C ABI.
1508     pub default_adjusted_cabi: Option<Abi>,
1509
1510     /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1511     pub c_enum_min_bits: u64,
1512
1513     /// Whether or not the DWARF `.debug_aranges` section should be generated.
1514     pub generate_arange_section: bool,
1515
1516     /// Whether the target supports stack canary checks. `true` by default,
1517     /// since this is most common among tier 1 and tier 2 targets.
1518     pub supports_stack_protector: bool,
1519 }
1520
1521 /// Add arguments for the given flavor and also for its "twin" flavors
1522 /// that have a compatible command line interface.
1523 fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'static str]) {
1524     let mut insert = |flavor| {
1525         link_args.entry(flavor).or_default().extend(args.iter().copied().map(Cow::Borrowed))
1526     };
1527     insert(flavor);
1528     match flavor {
1529         LinkerFlavor::Ld => insert(LinkerFlavor::Lld(LldFlavor::Ld)),
1530         LinkerFlavor::Msvc => insert(LinkerFlavor::Lld(LldFlavor::Link)),
1531         LinkerFlavor::Lld(LldFlavor::Ld64) | LinkerFlavor::Lld(LldFlavor::Wasm) => {}
1532         LinkerFlavor::Lld(lld_flavor) => {
1533             panic!("add_link_args: use non-LLD flavor for {:?}", lld_flavor)
1534         }
1535         LinkerFlavor::Gcc
1536         | LinkerFlavor::Em
1537         | LinkerFlavor::L4Bender
1538         | LinkerFlavor::BpfLinker
1539         | LinkerFlavor::PtxLinker => {}
1540     }
1541 }
1542
1543 impl TargetOptions {
1544     fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
1545         let mut link_args = LinkArgs::new();
1546         add_link_args(&mut link_args, flavor, args);
1547         link_args
1548     }
1549
1550     fn add_pre_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1551         add_link_args(&mut self.pre_link_args, flavor, args);
1552     }
1553
1554     fn add_post_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1555         add_link_args(&mut self.post_link_args, flavor, args);
1556     }
1557 }
1558
1559 impl Default for TargetOptions {
1560     /// Creates a set of "sane defaults" for any target. This is still
1561     /// incomplete, and if used for compilation, will certainly not work.
1562     fn default() -> TargetOptions {
1563         TargetOptions {
1564             is_builtin: false,
1565             endian: Endian::Little,
1566             c_int_width: "32".into(),
1567             os: "none".into(),
1568             env: "".into(),
1569             abi: "".into(),
1570             vendor: "unknown".into(),
1571             linker_flavor: LinkerFlavor::Gcc,
1572             linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
1573             lld_flavor: LldFlavor::Ld,
1574             pre_link_args: LinkArgs::new(),
1575             post_link_args: LinkArgs::new(),
1576             link_script: None,
1577             asm_args: cvs![],
1578             cpu: "generic".into(),
1579             features: "".into(),
1580             dynamic_linking: false,
1581             only_cdylib: false,
1582             executables: true,
1583             relocation_model: RelocModel::Pic,
1584             code_model: None,
1585             tls_model: TlsModel::GeneralDynamic,
1586             disable_redzone: false,
1587             frame_pointer: FramePointer::MayOmit,
1588             function_sections: true,
1589             dll_prefix: "lib".into(),
1590             dll_suffix: ".so".into(),
1591             exe_suffix: "".into(),
1592             staticlib_prefix: "lib".into(),
1593             staticlib_suffix: ".a".into(),
1594             families: cvs![],
1595             abi_return_struct_as_int: false,
1596             is_like_osx: false,
1597             is_like_solaris: false,
1598             is_like_windows: false,
1599             is_like_msvc: false,
1600             is_like_wasm: false,
1601             default_dwarf_version: 4,
1602             linker_is_gnu: true,
1603             allows_weak_linkage: true,
1604             has_rpath: false,
1605             no_default_libraries: true,
1606             position_independent_executables: false,
1607             static_position_independent_executables: false,
1608             needs_plt: false,
1609             relro_level: RelroLevel::None,
1610             pre_link_objects: Default::default(),
1611             post_link_objects: Default::default(),
1612             pre_link_objects_self_contained: Default::default(),
1613             post_link_objects_self_contained: Default::default(),
1614             link_self_contained: LinkSelfContainedDefault::False,
1615             late_link_args: LinkArgs::new(),
1616             late_link_args_dynamic: LinkArgs::new(),
1617             late_link_args_static: LinkArgs::new(),
1618             link_env: cvs![],
1619             link_env_remove: cvs![],
1620             archive_format: "gnu".into(),
1621             main_needs_argc_argv: true,
1622             allow_asm: true,
1623             has_thread_local: false,
1624             obj_is_bitcode: false,
1625             forces_embed_bitcode: false,
1626             bitcode_llvm_cmdline: "".into(),
1627             min_atomic_width: None,
1628             max_atomic_width: None,
1629             atomic_cas: true,
1630             panic_strategy: PanicStrategy::Unwind,
1631             crt_static_allows_dylibs: false,
1632             crt_static_default: false,
1633             crt_static_respected: false,
1634             stack_probes: StackProbeType::None,
1635             min_global_align: None,
1636             default_codegen_units: None,
1637             trap_unreachable: true,
1638             requires_lto: false,
1639             singlethread: false,
1640             no_builtins: false,
1641             default_hidden_visibility: false,
1642             emit_debug_gdb_scripts: true,
1643             requires_uwtable: false,
1644             default_uwtable: false,
1645             simd_types_indirect: true,
1646             limit_rdylib_exports: true,
1647             override_export_symbols: None,
1648             merge_functions: MergeFunctions::Aliases,
1649             mcount: "mcount".into(),
1650             llvm_abiname: "".into(),
1651             relax_elf_relocations: false,
1652             llvm_args: cvs![],
1653             use_ctors_section: false,
1654             eh_frame_header: true,
1655             has_thumb_interworking: false,
1656             debuginfo_kind: Default::default(),
1657             split_debuginfo: Default::default(),
1658             // `Off` is supported by default, but targets can remove this manually, e.g. Windows.
1659             supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
1660             supported_sanitizers: SanitizerSet::empty(),
1661             default_adjusted_cabi: None,
1662             c_enum_min_bits: 32,
1663             generate_arange_section: true,
1664             supports_stack_protector: true,
1665         }
1666     }
1667 }
1668
1669 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1670 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1671 /// this `Deref` implementation is no longer necessary.
1672 impl Deref for Target {
1673     type Target = TargetOptions;
1674
1675     #[inline]
1676     fn deref(&self) -> &Self::Target {
1677         &self.options
1678     }
1679 }
1680 impl DerefMut for Target {
1681     #[inline]
1682     fn deref_mut(&mut self) -> &mut Self::Target {
1683         &mut self.options
1684     }
1685 }
1686
1687 impl Target {
1688     /// Given a function ABI, turn it into the correct ABI for this target.
1689     pub fn adjust_abi(&self, abi: Abi) -> Abi {
1690         match abi {
1691             Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1692             Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1693                 Abi::Stdcall { unwind }
1694             }
1695             Abi::System { unwind } => Abi::C { unwind },
1696             Abi::EfiApi if self.arch == "x86_64" => Abi::Win64 { unwind: false },
1697             Abi::EfiApi => Abi::C { unwind: false },
1698
1699             // See commentary in `is_abi_supported`.
1700             Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1701             Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1702             Abi::Fastcall { .. } if self.arch == "x86" => abi,
1703             Abi::Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1704             Abi::Fastcall { unwind } | Abi::Vectorcall { unwind } => Abi::C { unwind },
1705
1706             abi => abi,
1707         }
1708     }
1709
1710     /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1711     pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1712         use Abi::*;
1713         Some(match abi {
1714             Rust
1715             | C { .. }
1716             | System { .. }
1717             | RustIntrinsic
1718             | RustCall
1719             | PlatformIntrinsic
1720             | Unadjusted
1721             | Cdecl { .. }
1722             | EfiApi
1723             | RustCold => true,
1724             X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1725             Aapcs { .. } => "arm" == self.arch,
1726             CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1727             Win64 { .. } | SysV64 { .. } => self.arch == "x86_64",
1728             PtxKernel => self.arch == "nvptx64",
1729             Msp430Interrupt => self.arch == "msp430",
1730             AmdGpuKernel => self.arch == "amdgcn",
1731             AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1732             Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1733             Thiscall { .. } => self.arch == "x86",
1734             // On windows these fall-back to platform native calling convention (C) when the
1735             // architecture is not supported.
1736             //
1737             // This is I believe a historical accident that has occurred as part of Microsoft
1738             // striving to allow most of the code to "just" compile when support for 64-bit x86
1739             // was added and then later again, when support for ARM architectures was added.
1740             //
1741             // This is well documented across MSDN. Support for this in Rust has been added in
1742             // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1743             // Rust, but there isn't much leeway remaining here to change it back at the time this
1744             // comment has been written.
1745             //
1746             // Following are the relevant excerpts from the MSDN documentation.
1747             //
1748             // > The __vectorcall calling convention is only supported in native code on x86 and
1749             // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1750             // > ...
1751             // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1752             //
1753             // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1754             //
1755             // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1756             //
1757             // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1758             //
1759             // > In most cases, keywords or compiler switches that specify an unsupported
1760             // > convention on a particular platform are ignored, and the platform default
1761             // > convention is used.
1762             //
1763             // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1764             Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } if self.is_like_windows => true,
1765             // Outside of Windows we want to only support these calling conventions for the
1766             // architectures for which these calling conventions are actually well defined.
1767             Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true,
1768             Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1769             // Return a `None` for other cases so that we know to emit a future compat lint.
1770             Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None,
1771         })
1772     }
1773
1774     /// Minimum integer size in bits that this target can perform atomic
1775     /// operations on.
1776     pub fn min_atomic_width(&self) -> u64 {
1777         self.min_atomic_width.unwrap_or(8)
1778     }
1779
1780     /// Maximum integer size in bits that this target can perform atomic
1781     /// operations on.
1782     pub fn max_atomic_width(&self) -> u64 {
1783         self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1784     }
1785
1786     /// Loads a target descriptor from a JSON object.
1787     pub fn from_json(obj: Json) -> Result<(Target, TargetWarnings), String> {
1788         // While ugly, this code must remain this way to retain
1789         // compatibility with existing JSON fields and the internal
1790         // expected naming of the Target and TargetOptions structs.
1791         // To ensure compatibility is retained, the built-in targets
1792         // are round-tripped through this code to catch cases where
1793         // the JSON parser is not updated to match the structs.
1794
1795         let mut obj = match obj {
1796             Value::Object(obj) => obj,
1797             _ => return Err("Expected JSON object for target")?,
1798         };
1799
1800         let mut get_req_field = |name: &str| {
1801             obj.remove(name)
1802                 .and_then(|j| j.as_str().map(str::to_string))
1803                 .ok_or_else(|| format!("Field {} in target specification is required", name))
1804         };
1805
1806         let mut base = Target {
1807             llvm_target: get_req_field("llvm-target")?.into(),
1808             pointer_width: get_req_field("target-pointer-width")?
1809                 .parse::<u32>()
1810                 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1811             data_layout: get_req_field("data-layout")?.into(),
1812             arch: get_req_field("arch")?.into(),
1813             options: Default::default(),
1814         };
1815
1816         let mut incorrect_type = vec![];
1817
1818         macro_rules! key {
1819             ($key_name:ident) => ( {
1820                 let name = (stringify!($key_name)).replace("_", "-");
1821                 if let Some(s) = obj.remove(&name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
1822                     base.$key_name = s;
1823                 }
1824             } );
1825             ($key_name:ident = $json_name:expr) => ( {
1826                 let name = $json_name;
1827                 if let Some(s) = obj.remove(name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
1828                     base.$key_name = s;
1829                 }
1830             } );
1831             ($key_name:ident, bool) => ( {
1832                 let name = (stringify!($key_name)).replace("_", "-");
1833                 if let Some(s) = obj.remove(&name).and_then(|b| b.as_bool()) {
1834                     base.$key_name = s;
1835                 }
1836             } );
1837             ($key_name:ident, u64) => ( {
1838                 let name = (stringify!($key_name)).replace("_", "-");
1839                 if let Some(s) = obj.remove(&name).and_then(|j| Json::as_u64(&j)) {
1840                     base.$key_name = s;
1841                 }
1842             } );
1843             ($key_name:ident, u32) => ( {
1844                 let name = (stringify!($key_name)).replace("_", "-");
1845                 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
1846                     if s < 1 || s > 5 {
1847                         return Err("Not a valid DWARF version number".into());
1848                     }
1849                     base.$key_name = s as u32;
1850                 }
1851             } );
1852             ($key_name:ident, Option<u64>) => ( {
1853                 let name = (stringify!($key_name)).replace("_", "-");
1854                 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
1855                     base.$key_name = Some(s);
1856                 }
1857             } );
1858             ($key_name:ident, MergeFunctions) => ( {
1859                 let name = (stringify!($key_name)).replace("_", "-");
1860                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1861                     match s.parse::<MergeFunctions>() {
1862                         Ok(mergefunc) => base.$key_name = mergefunc,
1863                         _ => return Some(Err(format!("'{}' is not a valid value for \
1864                                                       merge-functions. Use 'disabled', \
1865                                                       'trampolines', or 'aliases'.",
1866                                                       s))),
1867                     }
1868                     Some(Ok(()))
1869                 })).unwrap_or(Ok(()))
1870             } );
1871             ($key_name:ident, RelocModel) => ( {
1872                 let name = (stringify!($key_name)).replace("_", "-");
1873                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1874                     match s.parse::<RelocModel>() {
1875                         Ok(relocation_model) => base.$key_name = relocation_model,
1876                         _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1877                                                       Run `rustc --print relocation-models` to \
1878                                                       see the list of supported values.", s))),
1879                     }
1880                     Some(Ok(()))
1881                 })).unwrap_or(Ok(()))
1882             } );
1883             ($key_name:ident, CodeModel) => ( {
1884                 let name = (stringify!($key_name)).replace("_", "-");
1885                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1886                     match s.parse::<CodeModel>() {
1887                         Ok(code_model) => base.$key_name = Some(code_model),
1888                         _ => return Some(Err(format!("'{}' is not a valid code model. \
1889                                                       Run `rustc --print code-models` to \
1890                                                       see the list of supported values.", s))),
1891                     }
1892                     Some(Ok(()))
1893                 })).unwrap_or(Ok(()))
1894             } );
1895             ($key_name:ident, TlsModel) => ( {
1896                 let name = (stringify!($key_name)).replace("_", "-");
1897                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1898                     match s.parse::<TlsModel>() {
1899                         Ok(tls_model) => base.$key_name = tls_model,
1900                         _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1901                                                       Run `rustc --print tls-models` to \
1902                                                       see the list of supported values.", s))),
1903                     }
1904                     Some(Ok(()))
1905                 })).unwrap_or(Ok(()))
1906             } );
1907             ($key_name:ident, PanicStrategy) => ( {
1908                 let name = (stringify!($key_name)).replace("_", "-");
1909                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1910                     match s {
1911                         "unwind" => base.$key_name = PanicStrategy::Unwind,
1912                         "abort" => base.$key_name = PanicStrategy::Abort,
1913                         _ => return Some(Err(format!("'{}' is not a valid value for \
1914                                                       panic-strategy. Use 'unwind' or 'abort'.",
1915                                                      s))),
1916                 }
1917                 Some(Ok(()))
1918             })).unwrap_or(Ok(()))
1919             } );
1920             ($key_name:ident, RelroLevel) => ( {
1921                 let name = (stringify!($key_name)).replace("_", "-");
1922                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1923                     match s.parse::<RelroLevel>() {
1924                         Ok(level) => base.$key_name = level,
1925                         _ => return Some(Err(format!("'{}' is not a valid value for \
1926                                                       relro-level. Use 'full', 'partial, or 'off'.",
1927                                                       s))),
1928                     }
1929                     Some(Ok(()))
1930                 })).unwrap_or(Ok(()))
1931             } );
1932             ($key_name:ident, DebuginfoKind) => ( {
1933                 let name = (stringify!($key_name)).replace("_", "-");
1934                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1935                     match s.parse::<DebuginfoKind>() {
1936                         Ok(level) => base.$key_name = level,
1937                         _ => return Some(Err(
1938                             format!("'{s}' is not a valid value for debuginfo-kind. Use 'dwarf', \
1939                                   'dwarf-dsym' or 'pdb'.")
1940                         )),
1941                     }
1942                     Some(Ok(()))
1943                 })).unwrap_or(Ok(()))
1944             } );
1945             ($key_name:ident, SplitDebuginfo) => ( {
1946                 let name = (stringify!($key_name)).replace("_", "-");
1947                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1948                     match s.parse::<SplitDebuginfo>() {
1949                         Ok(level) => base.$key_name = level,
1950                         _ => return Some(Err(format!("'{}' is not a valid value for \
1951                                                       split-debuginfo. Use 'off' or 'dsymutil'.",
1952                                                       s))),
1953                     }
1954                     Some(Ok(()))
1955                 })).unwrap_or(Ok(()))
1956             } );
1957             ($key_name:ident, list) => ( {
1958                 let name = (stringify!($key_name)).replace("_", "-");
1959                 if let Some(j) = obj.remove(&name) {
1960                     if let Some(v) = j.as_array() {
1961                         base.$key_name = v.iter()
1962                             .map(|a| a.as_str().unwrap().to_string().into())
1963                             .collect();
1964                     } else {
1965                         incorrect_type.push(name)
1966                     }
1967                 }
1968             } );
1969             ($key_name:ident, opt_list) => ( {
1970                 let name = (stringify!($key_name)).replace("_", "-");
1971                 if let Some(j) = obj.remove(&name) {
1972                     if let Some(v) = j.as_array() {
1973                         base.$key_name = Some(v.iter()
1974                             .map(|a| a.as_str().unwrap().to_string().into())
1975                             .collect());
1976                     } else {
1977                         incorrect_type.push(name)
1978                     }
1979                 }
1980             } );
1981             ($key_name:ident, falliable_list) => ( {
1982                 let name = (stringify!($key_name)).replace("_", "-");
1983                 obj.remove(&name).and_then(|j| {
1984                     if let Some(v) = j.as_array() {
1985                         match v.iter().map(|a| FromStr::from_str(a.as_str().unwrap())).collect() {
1986                             Ok(l) => { base.$key_name = l },
1987                             // FIXME: `falliable_list` can't re-use the `key!` macro for list
1988                             // elements and the error messages from that macro, so it has a bad
1989                             // generic message instead
1990                             Err(_) => return Some(Err(
1991                                 format!("`{:?}` is not a valid value for `{}`", j, name)
1992                             )),
1993                         }
1994                     } else {
1995                         incorrect_type.push(name)
1996                     }
1997                     Some(Ok(()))
1998                 }).unwrap_or(Ok(()))
1999             } );
2000             ($key_name:ident, optional) => ( {
2001                 let name = (stringify!($key_name)).replace("_", "-");
2002                 if let Some(o) = obj.remove(&name) {
2003                     base.$key_name = o
2004                         .as_str()
2005                         .map(|s| s.to_string().into());
2006                 }
2007             } );
2008             ($key_name:ident, LldFlavor) => ( {
2009                 let name = (stringify!($key_name)).replace("_", "-");
2010                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2011                     if let Some(flavor) = LldFlavor::from_str(&s) {
2012                         base.$key_name = flavor;
2013                     } else {
2014                         return Some(Err(format!(
2015                             "'{}' is not a valid value for lld-flavor. \
2016                              Use 'darwin', 'gnu', 'link' or 'wasm.",
2017                             s)))
2018                     }
2019                     Some(Ok(()))
2020                 })).unwrap_or(Ok(()))
2021             } );
2022             ($key_name:ident, LinkerFlavor) => ( {
2023                 let name = (stringify!($key_name)).replace("_", "-");
2024                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2025                     match LinkerFlavor::from_str(s) {
2026                         Some(linker_flavor) => base.$key_name = linker_flavor,
2027                         _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
2028                                                       Use {}", s, LinkerFlavor::one_of()))),
2029                     }
2030                     Some(Ok(()))
2031                 })).unwrap_or(Ok(()))
2032             } );
2033             ($key_name:ident, StackProbeType) => ( {
2034                 let name = (stringify!($key_name)).replace("_", "-");
2035                 obj.remove(&name).and_then(|o| match StackProbeType::from_json(&o) {
2036                     Ok(v) => {
2037                         base.$key_name = v;
2038                         Some(Ok(()))
2039                     },
2040                     Err(s) => Some(Err(
2041                         format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
2042                     )),
2043                 }).unwrap_or(Ok(()))
2044             } );
2045             ($key_name:ident, SanitizerSet) => ( {
2046                 let name = (stringify!($key_name)).replace("_", "-");
2047                 if let Some(o) = obj.remove(&name) {
2048                     if let Some(a) = o.as_array() {
2049                         for s in a {
2050                             base.$key_name |= match s.as_str() {
2051                                 Some("address") => SanitizerSet::ADDRESS,
2052                                 Some("cfi") => SanitizerSet::CFI,
2053                                 Some("leak") => SanitizerSet::LEAK,
2054                                 Some("memory") => SanitizerSet::MEMORY,
2055                                 Some("memtag") => SanitizerSet::MEMTAG,
2056                                 Some("shadow-call-stack") => SanitizerSet::SHADOWCALLSTACK,
2057                                 Some("thread") => SanitizerSet::THREAD,
2058                                 Some("hwaddress") => SanitizerSet::HWADDRESS,
2059                                 Some(s) => return Err(format!("unknown sanitizer {}", s)),
2060                                 _ => return Err(format!("not a string: {:?}", s)),
2061                             };
2062                         }
2063                     } else {
2064                         incorrect_type.push(name)
2065                     }
2066                 }
2067                 Ok::<(), String>(())
2068             } );
2069
2070             ($key_name:ident = $json_name:expr, link_self_contained) => ( {
2071                 let name = $json_name;
2072                 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2073                     match s.parse::<LinkSelfContainedDefault>() {
2074                         Ok(lsc_default) => base.$key_name = lsc_default,
2075                         _ => return Some(Err(format!("'{}' is not a valid `-Clink-self-contained` default. \
2076                                                       Use 'false', 'true', 'musl' or 'mingw'", s))),
2077                     }
2078                     Some(Ok(()))
2079                 })).unwrap_or(Ok(()))
2080             } );
2081             ($key_name:ident = $json_name:expr, link_objects) => ( {
2082                 let name = $json_name;
2083                 if let Some(val) = obj.remove(name) {
2084                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2085                         JSON object with fields per CRT object kind.", name))?;
2086                     let mut args = CrtObjects::new();
2087                     for (k, v) in obj {
2088                         let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
2089                             format!("{}: '{}' is not a valid value for CRT object kind. \
2090                                      Use '(dynamic,static)-(nopic,pic)-exe' or \
2091                                      '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
2092                         })?;
2093
2094                         let v = v.as_array().ok_or_else(||
2095                             format!("{}.{}: expected a JSON array", name, k)
2096                         )?.iter().enumerate()
2097                             .map(|(i,s)| {
2098                                 let s = s.as_str().ok_or_else(||
2099                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2100                                 Ok(s.to_string().into())
2101                             })
2102                             .collect::<Result<Vec<_>, String>>()?;
2103
2104                         args.insert(kind, v);
2105                     }
2106                     base.$key_name = args;
2107                 }
2108             } );
2109             ($key_name:ident, link_args) => ( {
2110                 let name = (stringify!($key_name)).replace("_", "-");
2111                 if let Some(val) = obj.remove(&name) {
2112                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2113                         JSON object with fields per linker-flavor.", name))?;
2114                     let mut args = LinkArgs::new();
2115                     for (k, v) in obj {
2116                         let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
2117                             format!("{}: '{}' is not a valid value for linker-flavor. \
2118                                      Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
2119                         })?;
2120
2121                         let v = v.as_array().ok_or_else(||
2122                             format!("{}.{}: expected a JSON array", name, k)
2123                         )?.iter().enumerate()
2124                             .map(|(i,s)| {
2125                                 let s = s.as_str().ok_or_else(||
2126                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2127                                 Ok(s.to_string().into())
2128                             })
2129                             .collect::<Result<Vec<_>, String>>()?;
2130
2131                         args.insert(flavor, v);
2132                     }
2133                     base.$key_name = args;
2134                 }
2135             } );
2136             ($key_name:ident, env) => ( {
2137                 let name = (stringify!($key_name)).replace("_", "-");
2138                 if let Some(o) = obj.remove(&name) {
2139                     if let Some(a) = o.as_array() {
2140                         for o in a {
2141                             if let Some(s) = o.as_str() {
2142                                 let p = s.split('=').collect::<Vec<_>>();
2143                                 if p.len() == 2 {
2144                                     let k = p[0].to_string();
2145                                     let v = p[1].to_string();
2146                                     base.$key_name.to_mut().push((k.into(), v.into()));
2147                                 }
2148                             }
2149                         }
2150                     } else {
2151                         incorrect_type.push(name)
2152                     }
2153                 }
2154             } );
2155             ($key_name:ident, Option<Abi>) => ( {
2156                 let name = (stringify!($key_name)).replace("_", "-");
2157                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2158                     match lookup_abi(s) {
2159                         Some(abi) => base.$key_name = Some(abi),
2160                         _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
2161                     }
2162                     Some(Ok(()))
2163                 })).unwrap_or(Ok(()))
2164             } );
2165             ($key_name:ident, TargetFamilies) => ( {
2166                 if let Some(value) = obj.remove("target-family") {
2167                     if let Some(v) = value.as_array() {
2168                         base.$key_name = v.iter()
2169                             .map(|a| a.as_str().unwrap().to_string().into())
2170                             .collect();
2171                     } else if let Some(v) = value.as_str() {
2172                         base.$key_name = vec![v.to_string().into()].into();
2173                     }
2174                 }
2175             } );
2176         }
2177
2178         if let Some(j) = obj.remove("target-endian") {
2179             if let Some(s) = j.as_str() {
2180                 base.endian = s.parse()?;
2181             } else {
2182                 incorrect_type.push("target-endian".into())
2183             }
2184         }
2185
2186         if let Some(fp) = obj.remove("frame-pointer") {
2187             if let Some(s) = fp.as_str() {
2188                 base.frame_pointer = s
2189                     .parse()
2190                     .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2191             } else {
2192                 incorrect_type.push("frame-pointer".into())
2193             }
2194         }
2195
2196         key!(is_builtin, bool);
2197         key!(c_int_width = "target-c-int-width");
2198         key!(os);
2199         key!(env);
2200         key!(abi);
2201         key!(vendor);
2202         key!(linker_flavor, LinkerFlavor)?;
2203         key!(linker, optional);
2204         key!(lld_flavor, LldFlavor)?;
2205         key!(pre_link_objects = "pre-link-objects", link_objects);
2206         key!(post_link_objects = "post-link-objects", link_objects);
2207         key!(pre_link_objects_self_contained = "pre-link-objects-fallback", link_objects);
2208         key!(post_link_objects_self_contained = "post-link-objects-fallback", link_objects);
2209         key!(link_self_contained = "crt-objects-fallback", link_self_contained)?;
2210         key!(pre_link_args, link_args);
2211         key!(late_link_args, link_args);
2212         key!(late_link_args_dynamic, link_args);
2213         key!(late_link_args_static, link_args);
2214         key!(post_link_args, link_args);
2215         key!(link_script, optional);
2216         key!(link_env, env);
2217         key!(link_env_remove, list);
2218         key!(asm_args, list);
2219         key!(cpu);
2220         key!(features);
2221         key!(dynamic_linking, bool);
2222         key!(only_cdylib, bool);
2223         key!(executables, bool);
2224         key!(relocation_model, RelocModel)?;
2225         key!(code_model, CodeModel)?;
2226         key!(tls_model, TlsModel)?;
2227         key!(disable_redzone, bool);
2228         key!(function_sections, bool);
2229         key!(dll_prefix);
2230         key!(dll_suffix);
2231         key!(exe_suffix);
2232         key!(staticlib_prefix);
2233         key!(staticlib_suffix);
2234         key!(families, TargetFamilies);
2235         key!(abi_return_struct_as_int, bool);
2236         key!(is_like_osx, bool);
2237         key!(is_like_solaris, bool);
2238         key!(is_like_windows, bool);
2239         key!(is_like_msvc, bool);
2240         key!(is_like_wasm, bool);
2241         key!(default_dwarf_version, u32);
2242         key!(linker_is_gnu, bool);
2243         key!(allows_weak_linkage, bool);
2244         key!(has_rpath, bool);
2245         key!(no_default_libraries, bool);
2246         key!(position_independent_executables, bool);
2247         key!(static_position_independent_executables, bool);
2248         key!(needs_plt, bool);
2249         key!(relro_level, RelroLevel)?;
2250         key!(archive_format);
2251         key!(allow_asm, bool);
2252         key!(main_needs_argc_argv, bool);
2253         key!(has_thread_local, bool);
2254         key!(obj_is_bitcode, bool);
2255         key!(forces_embed_bitcode, bool);
2256         key!(bitcode_llvm_cmdline);
2257         key!(max_atomic_width, Option<u64>);
2258         key!(min_atomic_width, Option<u64>);
2259         key!(atomic_cas, bool);
2260         key!(panic_strategy, PanicStrategy)?;
2261         key!(crt_static_allows_dylibs, bool);
2262         key!(crt_static_default, bool);
2263         key!(crt_static_respected, bool);
2264         key!(stack_probes, StackProbeType)?;
2265         key!(min_global_align, Option<u64>);
2266         key!(default_codegen_units, Option<u64>);
2267         key!(trap_unreachable, bool);
2268         key!(requires_lto, bool);
2269         key!(singlethread, bool);
2270         key!(no_builtins, bool);
2271         key!(default_hidden_visibility, bool);
2272         key!(emit_debug_gdb_scripts, bool);
2273         key!(requires_uwtable, bool);
2274         key!(default_uwtable, bool);
2275         key!(simd_types_indirect, bool);
2276         key!(limit_rdylib_exports, bool);
2277         key!(override_export_symbols, opt_list);
2278         key!(merge_functions, MergeFunctions)?;
2279         key!(mcount = "target-mcount");
2280         key!(llvm_abiname);
2281         key!(relax_elf_relocations, bool);
2282         key!(llvm_args, list);
2283         key!(use_ctors_section, bool);
2284         key!(eh_frame_header, bool);
2285         key!(has_thumb_interworking, bool);
2286         key!(debuginfo_kind, DebuginfoKind)?;
2287         key!(split_debuginfo, SplitDebuginfo)?;
2288         key!(supported_split_debuginfo, falliable_list)?;
2289         key!(supported_sanitizers, SanitizerSet)?;
2290         key!(default_adjusted_cabi, Option<Abi>)?;
2291         key!(c_enum_min_bits, u64);
2292         key!(generate_arange_section, bool);
2293         key!(supports_stack_protector, bool);
2294
2295         if base.is_builtin {
2296             // This can cause unfortunate ICEs later down the line.
2297             return Err("may not set is_builtin for targets not built-in".into());
2298         }
2299         // Each field should have been read using `Json::remove` so any keys remaining are unused.
2300         let remaining_keys = obj.keys();
2301         Ok((
2302             base,
2303             TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2304         ))
2305     }
2306
2307     /// Load a built-in target
2308     pub fn expect_builtin(target_triple: &TargetTriple) -> Target {
2309         match *target_triple {
2310             TargetTriple::TargetTriple(ref target_triple) => {
2311                 load_builtin(target_triple).expect("built-in target")
2312             }
2313             TargetTriple::TargetJson { .. } => {
2314                 panic!("built-in targets doesn't support target-paths")
2315             }
2316         }
2317     }
2318
2319     /// Search for a JSON file specifying the given target triple.
2320     ///
2321     /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2322     /// sysroot under the target-triple's `rustlib` directory.  Note that it could also just be a
2323     /// bare filename already, so also check for that. If one of the hardcoded targets we know
2324     /// about, just return it directly.
2325     ///
2326     /// The error string could come from any of the APIs called, including filesystem access and
2327     /// JSON decoding.
2328     pub fn search(
2329         target_triple: &TargetTriple,
2330         sysroot: &Path,
2331     ) -> Result<(Target, TargetWarnings), String> {
2332         use std::env;
2333         use std::fs;
2334
2335         fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2336             let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
2337             let obj = serde_json::from_str(&contents).map_err(|e| e.to_string())?;
2338             Target::from_json(obj)
2339         }
2340
2341         match *target_triple {
2342             TargetTriple::TargetTriple(ref target_triple) => {
2343                 // check if triple is in list of built-in targets
2344                 if let Some(t) = load_builtin(target_triple) {
2345                     return Ok((t, TargetWarnings::empty()));
2346                 }
2347
2348                 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2349                 let path = {
2350                     let mut target = target_triple.to_string();
2351                     target.push_str(".json");
2352                     PathBuf::from(target)
2353                 };
2354
2355                 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2356
2357                 for dir in env::split_paths(&target_path) {
2358                     let p = dir.join(&path);
2359                     if p.is_file() {
2360                         return load_file(&p);
2361                     }
2362                 }
2363
2364                 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2365                 // as a fallback.
2366                 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2367                 let p = PathBuf::from_iter([
2368                     Path::new(sysroot),
2369                     Path::new(&rustlib_path),
2370                     Path::new("target.json"),
2371                 ]);
2372                 if p.is_file() {
2373                     return load_file(&p);
2374                 }
2375
2376                 Err(format!("Could not find specification for target {:?}", target_triple))
2377             }
2378             TargetTriple::TargetJson { ref contents, .. } => {
2379                 let obj = serde_json::from_str(contents).map_err(|e| e.to_string())?;
2380                 Target::from_json(obj)
2381             }
2382         }
2383     }
2384 }
2385
2386 impl ToJson for Target {
2387     fn to_json(&self) -> Json {
2388         let mut d = serde_json::Map::new();
2389         let default: TargetOptions = Default::default();
2390
2391         macro_rules! target_val {
2392             ($attr:ident) => {{
2393                 let name = (stringify!($attr)).replace("_", "-");
2394                 d.insert(name, self.$attr.to_json());
2395             }};
2396         }
2397
2398         macro_rules! target_option_val {
2399             ($attr:ident) => {{
2400                 let name = (stringify!($attr)).replace("_", "-");
2401                 if default.$attr != self.$attr {
2402                     d.insert(name, self.$attr.to_json());
2403                 }
2404             }};
2405             ($attr:ident, $key_name:expr) => {{
2406                 let name = $key_name;
2407                 if default.$attr != self.$attr {
2408                     d.insert(name.into(), self.$attr.to_json());
2409                 }
2410             }};
2411             (link_args - $attr:ident) => {{
2412                 let name = (stringify!($attr)).replace("_", "-");
2413                 if default.$attr != self.$attr {
2414                     let obj = self
2415                         .$attr
2416                         .iter()
2417                         .map(|(k, v)| (k.desc().to_string(), v.clone()))
2418                         .collect::<BTreeMap<_, _>>();
2419                     d.insert(name, obj.to_json());
2420                 }
2421             }};
2422             (env - $attr:ident) => {{
2423                 let name = (stringify!($attr)).replace("_", "-");
2424                 if default.$attr != self.$attr {
2425                     let obj = self
2426                         .$attr
2427                         .iter()
2428                         .map(|&(ref k, ref v)| format!("{k}={v}"))
2429                         .collect::<Vec<_>>();
2430                     d.insert(name, obj.to_json());
2431                 }
2432             }};
2433         }
2434
2435         target_val!(llvm_target);
2436         d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2437         target_val!(arch);
2438         target_val!(data_layout);
2439
2440         target_option_val!(is_builtin);
2441         target_option_val!(endian, "target-endian");
2442         target_option_val!(c_int_width, "target-c-int-width");
2443         target_option_val!(os);
2444         target_option_val!(env);
2445         target_option_val!(abi);
2446         target_option_val!(vendor);
2447         target_option_val!(linker_flavor);
2448         target_option_val!(linker);
2449         target_option_val!(lld_flavor);
2450         target_option_val!(pre_link_objects);
2451         target_option_val!(post_link_objects);
2452         target_option_val!(pre_link_objects_self_contained, "pre-link-objects-fallback");
2453         target_option_val!(post_link_objects_self_contained, "post-link-objects-fallback");
2454         target_option_val!(link_self_contained, "crt-objects-fallback");
2455         target_option_val!(link_args - pre_link_args);
2456         target_option_val!(link_args - late_link_args);
2457         target_option_val!(link_args - late_link_args_dynamic);
2458         target_option_val!(link_args - late_link_args_static);
2459         target_option_val!(link_args - post_link_args);
2460         target_option_val!(link_script);
2461         target_option_val!(env - link_env);
2462         target_option_val!(link_env_remove);
2463         target_option_val!(asm_args);
2464         target_option_val!(cpu);
2465         target_option_val!(features);
2466         target_option_val!(dynamic_linking);
2467         target_option_val!(only_cdylib);
2468         target_option_val!(executables);
2469         target_option_val!(relocation_model);
2470         target_option_val!(code_model);
2471         target_option_val!(tls_model);
2472         target_option_val!(disable_redzone);
2473         target_option_val!(frame_pointer);
2474         target_option_val!(function_sections);
2475         target_option_val!(dll_prefix);
2476         target_option_val!(dll_suffix);
2477         target_option_val!(exe_suffix);
2478         target_option_val!(staticlib_prefix);
2479         target_option_val!(staticlib_suffix);
2480         target_option_val!(families, "target-family");
2481         target_option_val!(abi_return_struct_as_int);
2482         target_option_val!(is_like_osx);
2483         target_option_val!(is_like_solaris);
2484         target_option_val!(is_like_windows);
2485         target_option_val!(is_like_msvc);
2486         target_option_val!(is_like_wasm);
2487         target_option_val!(default_dwarf_version);
2488         target_option_val!(linker_is_gnu);
2489         target_option_val!(allows_weak_linkage);
2490         target_option_val!(has_rpath);
2491         target_option_val!(no_default_libraries);
2492         target_option_val!(position_independent_executables);
2493         target_option_val!(static_position_independent_executables);
2494         target_option_val!(needs_plt);
2495         target_option_val!(relro_level);
2496         target_option_val!(archive_format);
2497         target_option_val!(allow_asm);
2498         target_option_val!(main_needs_argc_argv);
2499         target_option_val!(has_thread_local);
2500         target_option_val!(obj_is_bitcode);
2501         target_option_val!(forces_embed_bitcode);
2502         target_option_val!(bitcode_llvm_cmdline);
2503         target_option_val!(min_atomic_width);
2504         target_option_val!(max_atomic_width);
2505         target_option_val!(atomic_cas);
2506         target_option_val!(panic_strategy);
2507         target_option_val!(crt_static_allows_dylibs);
2508         target_option_val!(crt_static_default);
2509         target_option_val!(crt_static_respected);
2510         target_option_val!(stack_probes);
2511         target_option_val!(min_global_align);
2512         target_option_val!(default_codegen_units);
2513         target_option_val!(trap_unreachable);
2514         target_option_val!(requires_lto);
2515         target_option_val!(singlethread);
2516         target_option_val!(no_builtins);
2517         target_option_val!(default_hidden_visibility);
2518         target_option_val!(emit_debug_gdb_scripts);
2519         target_option_val!(requires_uwtable);
2520         target_option_val!(default_uwtable);
2521         target_option_val!(simd_types_indirect);
2522         target_option_val!(limit_rdylib_exports);
2523         target_option_val!(override_export_symbols);
2524         target_option_val!(merge_functions);
2525         target_option_val!(mcount, "target-mcount");
2526         target_option_val!(llvm_abiname);
2527         target_option_val!(relax_elf_relocations);
2528         target_option_val!(llvm_args);
2529         target_option_val!(use_ctors_section);
2530         target_option_val!(eh_frame_header);
2531         target_option_val!(has_thumb_interworking);
2532         target_option_val!(debuginfo_kind);
2533         target_option_val!(split_debuginfo);
2534         target_option_val!(supported_split_debuginfo);
2535         target_option_val!(supported_sanitizers);
2536         target_option_val!(c_enum_min_bits);
2537         target_option_val!(generate_arange_section);
2538         target_option_val!(supports_stack_protector);
2539
2540         if let Some(abi) = self.default_adjusted_cabi {
2541             d.insert("default-adjusted-cabi".into(), Abi::name(abi).to_json());
2542         }
2543
2544         Json::Object(d)
2545     }
2546 }
2547
2548 /// Either a target triple string or a path to a JSON file.
2549 #[derive(Clone, Debug)]
2550 pub enum TargetTriple {
2551     TargetTriple(String),
2552     TargetJson {
2553         /// Warning: This field may only be used by rustdoc. Using it anywhere else will lead to
2554         /// inconsistencies as it is discarded during serialization.
2555         path_for_rustdoc: PathBuf,
2556         triple: String,
2557         contents: String,
2558     },
2559 }
2560
2561 // Use a manual implementation to ignore the path field
2562 impl PartialEq for TargetTriple {
2563     fn eq(&self, other: &Self) -> bool {
2564         match (self, other) {
2565             (Self::TargetTriple(l0), Self::TargetTriple(r0)) => l0 == r0,
2566             (
2567                 Self::TargetJson { path_for_rustdoc: _, triple: l_triple, contents: l_contents },
2568                 Self::TargetJson { path_for_rustdoc: _, triple: r_triple, contents: r_contents },
2569             ) => l_triple == r_triple && l_contents == r_contents,
2570             _ => false,
2571         }
2572     }
2573 }
2574
2575 // Use a manual implementation to ignore the path field
2576 impl Hash for TargetTriple {
2577     fn hash<H: Hasher>(&self, state: &mut H) -> () {
2578         match self {
2579             TargetTriple::TargetTriple(triple) => {
2580                 0u8.hash(state);
2581                 triple.hash(state)
2582             }
2583             TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => {
2584                 1u8.hash(state);
2585                 triple.hash(state);
2586                 contents.hash(state)
2587             }
2588         }
2589     }
2590 }
2591
2592 // Use a manual implementation to prevent encoding the target json file path in the crate metadata
2593 impl<S: Encoder> Encodable<S> for TargetTriple {
2594     fn encode(&self, s: &mut S) {
2595         match self {
2596             TargetTriple::TargetTriple(triple) => s.emit_enum_variant(0, |s| s.emit_str(triple)),
2597             TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => s
2598                 .emit_enum_variant(1, |s| {
2599                     s.emit_str(triple);
2600                     s.emit_str(contents)
2601                 }),
2602         }
2603     }
2604 }
2605
2606 impl<D: Decoder> Decodable<D> for TargetTriple {
2607     fn decode(d: &mut D) -> Self {
2608         match d.read_usize() {
2609             0 => TargetTriple::TargetTriple(d.read_str().to_owned()),
2610             1 => TargetTriple::TargetJson {
2611                 path_for_rustdoc: PathBuf::new(),
2612                 triple: d.read_str().to_owned(),
2613                 contents: d.read_str().to_owned(),
2614             },
2615             _ => {
2616                 panic!("invalid enum variant tag while decoding `TargetTriple`, expected 0..2");
2617             }
2618         }
2619     }
2620 }
2621
2622 impl TargetTriple {
2623     /// Creates a target triple from the passed target triple string.
2624     pub fn from_triple(triple: &str) -> Self {
2625         TargetTriple::TargetTriple(triple.into())
2626     }
2627
2628     /// Creates a target triple from the passed target path.
2629     pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2630         let canonicalized_path = path.canonicalize()?;
2631         let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| {
2632             io::Error::new(
2633                 io::ErrorKind::InvalidInput,
2634                 format!("target path {:?} is not a valid file: {}", canonicalized_path, err),
2635             )
2636         })?;
2637         let triple = canonicalized_path
2638             .file_stem()
2639             .expect("target path must not be empty")
2640             .to_str()
2641             .expect("target path must be valid unicode")
2642             .to_owned();
2643         Ok(TargetTriple::TargetJson { path_for_rustdoc: canonicalized_path, triple, contents })
2644     }
2645
2646     /// Returns a string triple for this target.
2647     ///
2648     /// If this target is a path, the file name (without extension) is returned.
2649     pub fn triple(&self) -> &str {
2650         match *self {
2651             TargetTriple::TargetTriple(ref triple)
2652             | TargetTriple::TargetJson { ref triple, .. } => triple,
2653         }
2654     }
2655
2656     /// Returns an extended string triple for this target.
2657     ///
2658     /// If this target is a path, a hash of the path is appended to the triple returned
2659     /// by `triple()`.
2660     pub fn debug_triple(&self) -> String {
2661         use std::collections::hash_map::DefaultHasher;
2662
2663         match self {
2664             TargetTriple::TargetTriple(triple) => triple.to_owned(),
2665             TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents: content } => {
2666                 let mut hasher = DefaultHasher::new();
2667                 content.hash(&mut hasher);
2668                 let hash = hasher.finish();
2669                 format!("{}-{}", triple, hash)
2670             }
2671         }
2672     }
2673 }
2674
2675 impl fmt::Display for TargetTriple {
2676     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2677         write!(f, "{}", self.debug_triple())
2678     }
2679 }