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