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