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