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