]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_target/src/spec/mod.rs
Rollup merge of #100121 - Nilstrieb:mir-validator-param-env, r=oli-obk
[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     ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
936     ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
937     ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
938     ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
939     ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
940     ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
941     ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
942     ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
943     ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
944     ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
945     ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
946     ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
947     ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
948     ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
949     ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
950     ("i686-unknown-linux-musl", i686_unknown_linux_musl),
951     ("i586-unknown-linux-musl", i586_unknown_linux_musl),
952     ("mips-unknown-linux-musl", mips_unknown_linux_musl),
953     ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
954     ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
955     ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
956     ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
957
958     ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
959     ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
960
961     ("i686-linux-android", i686_linux_android),
962     ("x86_64-linux-android", x86_64_linux_android),
963     ("arm-linux-androideabi", arm_linux_androideabi),
964     ("armv7-linux-androideabi", armv7_linux_androideabi),
965     ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
966     ("aarch64-linux-android", aarch64_linux_android),
967
968     ("x86_64-unknown-none-linuxkernel", x86_64_unknown_none_linuxkernel),
969
970     ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
971     ("armv6-unknown-freebsd", armv6_unknown_freebsd),
972     ("armv7-unknown-freebsd", armv7_unknown_freebsd),
973     ("i686-unknown-freebsd", i686_unknown_freebsd),
974     ("powerpc-unknown-freebsd", powerpc_unknown_freebsd),
975     ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
976     ("powerpc64le-unknown-freebsd", powerpc64le_unknown_freebsd),
977     ("riscv64gc-unknown-freebsd", riscv64gc_unknown_freebsd),
978     ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
979
980     ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
981
982     ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
983     ("i686-unknown-openbsd", i686_unknown_openbsd),
984     ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
985     ("powerpc64-unknown-openbsd", powerpc64_unknown_openbsd),
986     ("riscv64gc-unknown-openbsd", riscv64gc_unknown_openbsd),
987     ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
988     ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
989
990     ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
991     ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
992     ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
993     ("i686-unknown-netbsd", i686_unknown_netbsd),
994     ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
995     ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
996     ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
997
998     ("i686-unknown-haiku", i686_unknown_haiku),
999     ("x86_64-unknown-haiku", x86_64_unknown_haiku),
1000
1001     ("aarch64-apple-darwin", aarch64_apple_darwin),
1002     ("x86_64-apple-darwin", x86_64_apple_darwin),
1003     ("i686-apple-darwin", i686_apple_darwin),
1004
1005     ("aarch64-fuchsia", aarch64_fuchsia),
1006     ("x86_64-fuchsia", x86_64_fuchsia),
1007
1008     ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
1009
1010     ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
1011
1012     ("aarch64-unknown-redox", aarch64_unknown_redox),
1013     ("x86_64-unknown-redox", x86_64_unknown_redox),
1014
1015     ("i386-apple-ios", i386_apple_ios),
1016     ("x86_64-apple-ios", x86_64_apple_ios),
1017     ("aarch64-apple-ios", aarch64_apple_ios),
1018     ("armv7-apple-ios", armv7_apple_ios),
1019     ("armv7s-apple-ios", armv7s_apple_ios),
1020     ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
1021     ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
1022     ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
1023     ("aarch64-apple-tvos", aarch64_apple_tvos),
1024     ("x86_64-apple-tvos", x86_64_apple_tvos),
1025
1026     ("armv7k-apple-watchos", armv7k_apple_watchos),
1027     ("arm64_32-apple-watchos", arm64_32_apple_watchos),
1028     ("x86_64-apple-watchos-sim", x86_64_apple_watchos_sim),
1029     ("aarch64-apple-watchos-sim", aarch64_apple_watchos_sim),
1030
1031     ("armebv7r-none-eabi", armebv7r_none_eabi),
1032     ("armebv7r-none-eabihf", armebv7r_none_eabihf),
1033     ("armv7r-none-eabi", armv7r_none_eabi),
1034     ("armv7r-none-eabihf", armv7r_none_eabihf),
1035
1036     ("x86_64-pc-solaris", x86_64_pc_solaris),
1037     ("x86_64-sun-solaris", x86_64_sun_solaris),
1038     ("sparcv9-sun-solaris", sparcv9_sun_solaris),
1039
1040     ("x86_64-unknown-illumos", x86_64_unknown_illumos),
1041
1042     ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
1043     ("i686-pc-windows-gnu", i686_pc_windows_gnu),
1044     ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
1045     ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
1046
1047     ("aarch64-pc-windows-gnullvm", aarch64_pc_windows_gnullvm),
1048     ("x86_64-pc-windows-gnullvm", x86_64_pc_windows_gnullvm),
1049
1050     ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
1051     ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
1052     ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
1053     ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
1054     ("i686-pc-windows-msvc", i686_pc_windows_msvc),
1055     ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
1056     ("i586-pc-windows-msvc", i586_pc_windows_msvc),
1057     ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
1058     ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
1059
1060     ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
1061     ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
1062     ("wasm32-unknown-unknown", wasm32_unknown_unknown),
1063     ("wasm32-wasi", wasm32_wasi),
1064     ("wasm64-unknown-unknown", wasm64_unknown_unknown),
1065
1066     ("thumbv6m-none-eabi", thumbv6m_none_eabi),
1067     ("thumbv7m-none-eabi", thumbv7m_none_eabi),
1068     ("thumbv7em-none-eabi", thumbv7em_none_eabi),
1069     ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
1070     ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
1071     ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
1072     ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
1073
1074     ("armv7a-none-eabi", armv7a_none_eabi),
1075     ("armv7a-none-eabihf", armv7a_none_eabihf),
1076
1077     ("msp430-none-elf", msp430_none_elf),
1078
1079     ("aarch64-unknown-hermit", aarch64_unknown_hermit),
1080     ("x86_64-unknown-hermit", x86_64_unknown_hermit),
1081
1082     ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
1083     ("riscv32im-unknown-none-elf", riscv32im_unknown_none_elf),
1084     ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
1085     ("riscv32imc-esp-espidf", riscv32imc_esp_espidf),
1086     ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
1087     ("riscv32imac-unknown-xous-elf", riscv32imac_unknown_xous_elf),
1088     ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
1089     ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
1090     ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
1091     ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
1092     ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
1093     ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
1094
1095     ("aarch64-unknown-none", aarch64_unknown_none),
1096     ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
1097
1098     ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
1099
1100     ("x86_64-unknown-uefi", x86_64_unknown_uefi),
1101     ("i686-unknown-uefi", i686_unknown_uefi),
1102     ("aarch64-unknown-uefi", aarch64_unknown_uefi),
1103
1104     ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
1105
1106     ("i686-wrs-vxworks", i686_wrs_vxworks),
1107     ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
1108     ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
1109     ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
1110     ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
1111     ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
1112     ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
1113
1114     ("aarch64-kmc-solid_asp3", aarch64_kmc_solid_asp3),
1115     ("armv7a-kmc-solid_asp3-eabi", armv7a_kmc_solid_asp3_eabi),
1116     ("armv7a-kmc-solid_asp3-eabihf", armv7a_kmc_solid_asp3_eabihf),
1117
1118     ("mipsel-sony-psp", mipsel_sony_psp),
1119     ("mipsel-unknown-none", mipsel_unknown_none),
1120     ("thumbv4t-none-eabi", thumbv4t_none_eabi),
1121     ("armv4t-none-eabi", armv4t_none_eabi),
1122
1123     ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
1124     ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
1125     ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
1126
1127     ("bpfeb-unknown-none", bpfeb_unknown_none),
1128     ("bpfel-unknown-none", bpfel_unknown_none),
1129
1130     ("armv6k-nintendo-3ds", armv6k_nintendo_3ds),
1131
1132     ("aarch64-nintendo-switch-freestanding", aarch64_nintendo_switch_freestanding),
1133
1134     ("armv7-unknown-linux-uclibceabi", armv7_unknown_linux_uclibceabi),
1135     ("armv7-unknown-linux-uclibceabihf", armv7_unknown_linux_uclibceabihf),
1136
1137     ("x86_64-unknown-none", x86_64_unknown_none),
1138
1139     ("mips64-openwrt-linux-musl", mips64_openwrt_linux_musl),
1140 }
1141
1142 /// Cow-Vec-Str: Cow<'static, [Cow<'static, str>]>
1143 macro_rules! cvs {
1144     () => {
1145         ::std::borrow::Cow::Borrowed(&[])
1146     };
1147     ($($x:expr),+ $(,)?) => {
1148         ::std::borrow::Cow::Borrowed(&[
1149             $(
1150                 ::std::borrow::Cow::Borrowed($x),
1151             )*
1152         ])
1153     };
1154 }
1155
1156 pub(crate) use cvs;
1157
1158 /// Warnings encountered when parsing the target `json`.
1159 ///
1160 /// Includes fields that weren't recognized and fields that don't have the expected type.
1161 #[derive(Debug, PartialEq)]
1162 pub struct TargetWarnings {
1163     unused_fields: Vec<String>,
1164     incorrect_type: Vec<String>,
1165 }
1166
1167 impl TargetWarnings {
1168     pub fn empty() -> Self {
1169         Self { unused_fields: Vec::new(), incorrect_type: Vec::new() }
1170     }
1171
1172     pub fn warning_messages(&self) -> Vec<String> {
1173         let mut warnings = vec![];
1174         if !self.unused_fields.is_empty() {
1175             warnings.push(format!(
1176                 "target json file contains unused fields: {}",
1177                 self.unused_fields.join(", ")
1178             ));
1179         }
1180         if !self.incorrect_type.is_empty() {
1181             warnings.push(format!(
1182                 "target json file contains fields whose value doesn't have the correct json type: {}",
1183                 self.incorrect_type.join(", ")
1184             ));
1185         }
1186         warnings
1187     }
1188 }
1189
1190 /// Everything `rustc` knows about how to compile for a specific target.
1191 ///
1192 /// Every field here must be specified, and has no default value.
1193 #[derive(PartialEq, Clone, Debug)]
1194 pub struct Target {
1195     /// Target triple to pass to LLVM.
1196     pub llvm_target: StaticCow<str>,
1197     /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
1198     pub pointer_width: u32,
1199     /// Architecture to use for ABI considerations. Valid options include: "x86",
1200     /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
1201     pub arch: StaticCow<str>,
1202     /// [Data layout](https://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
1203     pub data_layout: StaticCow<str>,
1204     /// Optional settings with defaults.
1205     pub options: TargetOptions,
1206 }
1207
1208 pub trait HasTargetSpec {
1209     fn target_spec(&self) -> &Target;
1210 }
1211
1212 impl HasTargetSpec for Target {
1213     #[inline]
1214     fn target_spec(&self) -> &Target {
1215         self
1216     }
1217 }
1218
1219 type StaticCow<T> = Cow<'static, T>;
1220
1221 /// Optional aspects of a target specification.
1222 ///
1223 /// This has an implementation of `Default`, see each field for what the default is. In general,
1224 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
1225 ///
1226 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
1227 /// construction, all its fields logically belong to `Target` and available from `Target`
1228 /// through `Deref` impls.
1229 #[derive(PartialEq, Clone, Debug)]
1230 pub struct TargetOptions {
1231     /// Whether the target is built-in or loaded from a custom target specification.
1232     pub is_builtin: bool,
1233
1234     /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
1235     pub endian: Endian,
1236     /// Width of c_int type. Defaults to "32".
1237     pub c_int_width: StaticCow<str>,
1238     /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
1239     /// "none" implies a bare metal target without `std` library.
1240     /// A couple of targets having `std` also use "unknown" as an `os` value,
1241     /// but they are exceptions.
1242     pub os: StaticCow<str>,
1243     /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
1244     pub env: StaticCow<str>,
1245     /// ABI name to distinguish multiple ABIs on the same OS and architecture. For instance, `"eabi"`
1246     /// or `"eabihf"`. Defaults to "".
1247     pub abi: StaticCow<str>,
1248     /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
1249     pub vendor: StaticCow<str>,
1250
1251     /// Linker to invoke
1252     pub linker: Option<StaticCow<str>>,
1253     /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
1254     /// on the command line. Defaults to `LinkerFlavor::Gcc`.
1255     pub linker_flavor: LinkerFlavor,
1256     linker_flavor_json: LinkerFlavorCli,
1257     /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
1258     /// without clarifying its flavor in any way.
1259     /// FIXME: Merge this into `LinkerFlavor`.
1260     pub lld_flavor: LldFlavor,
1261     /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1262     /// FIXME: Merge this into `LinkerFlavor`.
1263     pub linker_is_gnu: bool,
1264
1265     /// Objects to link before and after all other object code.
1266     pub pre_link_objects: CrtObjects,
1267     pub post_link_objects: CrtObjects,
1268     /// Same as `(pre|post)_link_objects`, but when self-contained linking mode is enabled.
1269     pub pre_link_objects_self_contained: CrtObjects,
1270     pub post_link_objects_self_contained: CrtObjects,
1271     pub link_self_contained: LinkSelfContainedDefault,
1272
1273     /// Linker arguments that are passed *before* any user-defined libraries.
1274     pub pre_link_args: LinkArgs,
1275     pre_link_args_json: LinkArgsCli,
1276     /// Linker arguments that are unconditionally passed after any
1277     /// user-defined but before post-link objects. Standard platform
1278     /// libraries that should be always be linked to, usually go here.
1279     pub late_link_args: LinkArgs,
1280     late_link_args_json: LinkArgsCli,
1281     /// Linker arguments used in addition to `late_link_args` if at least one
1282     /// Rust dependency is dynamically linked.
1283     pub late_link_args_dynamic: LinkArgs,
1284     late_link_args_dynamic_json: LinkArgsCli,
1285     /// Linker arguments used in addition to `late_link_args` if all Rust
1286     /// dependencies are statically linked.
1287     pub late_link_args_static: LinkArgs,
1288     late_link_args_static_json: LinkArgsCli,
1289     /// Linker arguments that are unconditionally passed *after* any
1290     /// user-defined libraries.
1291     pub post_link_args: LinkArgs,
1292     post_link_args_json: LinkArgsCli,
1293
1294     /// Optional link script applied to `dylib` and `executable` crate types.
1295     /// This is a string containing the script, not a path. Can only be applied
1296     /// to linkers where `linker_is_gnu` is true.
1297     pub link_script: Option<StaticCow<str>>,
1298     /// Environment variables to be set for the linker invocation.
1299     pub link_env: StaticCow<[(StaticCow<str>, StaticCow<str>)]>,
1300     /// Environment variables to be removed for the linker invocation.
1301     pub link_env_remove: StaticCow<[StaticCow<str>]>,
1302
1303     /// Extra arguments to pass to the external assembler (when used)
1304     pub asm_args: StaticCow<[StaticCow<str>]>,
1305
1306     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1307     /// to "generic".
1308     pub cpu: StaticCow<str>,
1309     /// Default target features to pass to LLVM. These features will *always* be
1310     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1311     /// -mattr=$features`.
1312     pub features: StaticCow<str>,
1313     /// Whether dynamic linking is available on this target. Defaults to false.
1314     pub dynamic_linking: bool,
1315     /// If dynamic linking is available, whether only cdylibs are supported.
1316     pub only_cdylib: bool,
1317     /// Whether executables are available on this target. Defaults to true.
1318     pub executables: bool,
1319     /// Relocation model to use in object file. Corresponds to `llc
1320     /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1321     pub relocation_model: RelocModel,
1322     /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1323     /// Defaults to `None` which means "inherited from the base LLVM target".
1324     pub code_model: Option<CodeModel>,
1325     /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1326     /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1327     pub tls_model: TlsModel,
1328     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1329     pub disable_redzone: bool,
1330     /// Frame pointer mode for this target. Defaults to `MayOmit`.
1331     pub frame_pointer: FramePointer,
1332     /// Emit each function in its own section. Defaults to true.
1333     pub function_sections: bool,
1334     /// String to prepend to the name of every dynamic library. Defaults to "lib".
1335     pub dll_prefix: StaticCow<str>,
1336     /// String to append to the name of every dynamic library. Defaults to ".so".
1337     pub dll_suffix: StaticCow<str>,
1338     /// String to append to the name of every executable.
1339     pub exe_suffix: StaticCow<str>,
1340     /// String to prepend to the name of every static library. Defaults to "lib".
1341     pub staticlib_prefix: StaticCow<str>,
1342     /// String to append to the name of every static library. Defaults to ".a".
1343     pub staticlib_suffix: StaticCow<str>,
1344     /// Values of the `target_family` cfg set for this target.
1345     ///
1346     /// Common options are: "unix", "windows". Defaults to no families.
1347     ///
1348     /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1349     pub families: StaticCow<[StaticCow<str>]>,
1350     /// Whether the target toolchain's ABI supports returning small structs as an integer.
1351     pub abi_return_struct_as_int: bool,
1352     /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1353     /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1354     pub is_like_osx: bool,
1355     /// Whether the target toolchain is like Solaris's.
1356     /// Only useful for compiling against Illumos/Solaris,
1357     /// as they have a different set of linker flags. Defaults to false.
1358     pub is_like_solaris: bool,
1359     /// Whether the target is like Windows.
1360     /// This is a combination of several more specific properties represented as a single flag:
1361     ///   - The target uses a Windows ABI,
1362     ///   - uses PE/COFF as a format for object code,
1363     ///   - uses Windows-style dllexport/dllimport for shared libraries,
1364     ///   - uses import libraries and .def files for symbol exports,
1365     ///   - executables support setting a subsystem.
1366     pub is_like_windows: bool,
1367     /// Whether the target is like MSVC.
1368     /// This is a combination of several more specific properties represented as a single flag:
1369     ///   - The target has all the properties from `is_like_windows`
1370     ///     (for in-tree targets "is_like_msvc â‡’ is_like_windows" is ensured by a unit test),
1371     ///   - has some MSVC-specific Windows ABI properties,
1372     ///   - uses a link.exe-like linker,
1373     ///   - uses CodeView/PDB for debuginfo and natvis for its visualization,
1374     ///   - uses SEH-based unwinding,
1375     ///   - supports control flow guard mechanism.
1376     pub is_like_msvc: bool,
1377     /// Whether a target toolchain is like WASM.
1378     pub is_like_wasm: bool,
1379     /// Default supported version of DWARF on this platform.
1380     /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1381     pub default_dwarf_version: u32,
1382     /// The MinGW toolchain has a known issue that prevents it from correctly
1383     /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1384     /// symbol needs its own COMDAT section, weak linkage implies a large
1385     /// number sections that easily exceeds the given limit for larger
1386     /// codebases. Consequently we want a way to disallow weak linkage on some
1387     /// platforms.
1388     pub allows_weak_linkage: bool,
1389     /// Whether the linker support rpaths or not. Defaults to false.
1390     pub has_rpath: bool,
1391     /// Whether to disable linking to the default libraries, typically corresponds
1392     /// to `-nodefaultlibs`. Defaults to true.
1393     pub no_default_libraries: bool,
1394     /// Dynamically linked executables can be compiled as position independent
1395     /// if the default relocation model of position independent code is not
1396     /// changed. This is a requirement to take advantage of ASLR, as otherwise
1397     /// the functions in the executable are not randomized and can be used
1398     /// during an exploit of a vulnerability in any code.
1399     pub position_independent_executables: bool,
1400     /// Executables that are both statically linked and position-independent are supported.
1401     pub static_position_independent_executables: bool,
1402     /// Determines if the target always requires using the PLT for indirect
1403     /// library calls or not. This controls the default value of the `-Z plt` flag.
1404     pub needs_plt: bool,
1405     /// Either partial, full, or off. Full RELRO makes the dynamic linker
1406     /// resolve all symbols at startup and marks the GOT read-only before
1407     /// starting the program, preventing overwriting the GOT.
1408     pub relro_level: RelroLevel,
1409     /// Format that archives should be emitted in. This affects whether we use
1410     /// LLVM to assemble an archive or fall back to the system linker, and
1411     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1412     /// the system linker to be used.
1413     pub archive_format: StaticCow<str>,
1414     /// Is asm!() allowed? Defaults to true.
1415     pub allow_asm: bool,
1416     /// Whether the runtime startup code requires the `main` function be passed
1417     /// `argc` and `argv` values.
1418     pub main_needs_argc_argv: bool,
1419
1420     /// Flag indicating whether #[thread_local] is available for this target.
1421     pub has_thread_local: bool,
1422     // This is mainly for easy compatibility with emscripten.
1423     // If we give emcc .o files that are actually .bc files it
1424     // will 'just work'.
1425     pub obj_is_bitcode: bool,
1426     /// Whether the target requires that emitted object code includes bitcode.
1427     pub forces_embed_bitcode: bool,
1428     /// Content of the LLVM cmdline section associated with embedded bitcode.
1429     pub bitcode_llvm_cmdline: StaticCow<str>,
1430
1431     /// Don't use this field; instead use the `.min_atomic_width()` method.
1432     pub min_atomic_width: Option<u64>,
1433
1434     /// Don't use this field; instead use the `.max_atomic_width()` method.
1435     pub max_atomic_width: Option<u64>,
1436
1437     /// Whether the target supports atomic CAS operations natively
1438     pub atomic_cas: bool,
1439
1440     /// Panic strategy: "unwind" or "abort"
1441     pub panic_strategy: PanicStrategy,
1442
1443     /// Whether or not linking dylibs to a static CRT is allowed.
1444     pub crt_static_allows_dylibs: bool,
1445     /// Whether or not the CRT is statically linked by default.
1446     pub crt_static_default: bool,
1447     /// Whether or not crt-static is respected by the compiler (or is a no-op).
1448     pub crt_static_respected: bool,
1449
1450     /// The implementation of stack probes to use.
1451     pub stack_probes: StackProbeType,
1452
1453     /// The minimum alignment for global symbols.
1454     pub min_global_align: Option<u64>,
1455
1456     /// Default number of codegen units to use in debug mode
1457     pub default_codegen_units: Option<u64>,
1458
1459     /// Whether to generate trap instructions in places where optimization would
1460     /// otherwise produce control flow that falls through into unrelated memory.
1461     pub trap_unreachable: bool,
1462
1463     /// This target requires everything to be compiled with LTO to emit a final
1464     /// executable, aka there is no native linker for this target.
1465     pub requires_lto: bool,
1466
1467     /// This target has no support for threads.
1468     pub singlethread: bool,
1469
1470     /// Whether library functions call lowering/optimization is disabled in LLVM
1471     /// for this target unconditionally.
1472     pub no_builtins: bool,
1473
1474     /// The default visibility for symbols in this target should be "hidden"
1475     /// rather than "default"
1476     pub default_hidden_visibility: bool,
1477
1478     /// Whether a .debug_gdb_scripts section will be added to the output object file
1479     pub emit_debug_gdb_scripts: bool,
1480
1481     /// Whether or not to unconditionally `uwtable` attributes on functions,
1482     /// typically because the platform needs to unwind for things like stack
1483     /// unwinders.
1484     pub requires_uwtable: bool,
1485
1486     /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1487     /// is not specified and `uwtable` is not required on this target.
1488     pub default_uwtable: bool,
1489
1490     /// Whether or not SIMD types are passed by reference in the Rust ABI,
1491     /// typically required if a target can be compiled with a mixed set of
1492     /// target features. This is `true` by default, and `false` for targets like
1493     /// wasm32 where the whole program either has simd or not.
1494     pub simd_types_indirect: bool,
1495
1496     /// Pass a list of symbol which should be exported in the dylib to the linker.
1497     pub limit_rdylib_exports: bool,
1498
1499     /// If set, have the linker export exactly these symbols, instead of using
1500     /// the usual logic to figure this out from the crate itself.
1501     pub override_export_symbols: Option<StaticCow<[StaticCow<str>]>>,
1502
1503     /// Determines how or whether the MergeFunctions LLVM pass should run for
1504     /// this target. Either "disabled", "trampolines", or "aliases".
1505     /// The MergeFunctions pass is generally useful, but some targets may need
1506     /// to opt out. The default is "aliases".
1507     ///
1508     /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1509     pub merge_functions: MergeFunctions,
1510
1511     /// Use platform dependent mcount function
1512     pub mcount: StaticCow<str>,
1513
1514     /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1515     pub llvm_abiname: StaticCow<str>,
1516
1517     /// Whether or not RelaxElfRelocation flag will be passed to the linker
1518     pub relax_elf_relocations: bool,
1519
1520     /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1521     pub llvm_args: StaticCow<[StaticCow<str>]>,
1522
1523     /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1524     /// to false (uses .init_array).
1525     pub use_ctors_section: bool,
1526
1527     /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1528     /// used to locate unwinding information is passed
1529     /// (only has effect if the linker is `ld`-like).
1530     pub eh_frame_header: bool,
1531
1532     /// Is true if the target is an ARM architecture using thumb v1 which allows for
1533     /// thumb and arm interworking.
1534     pub has_thumb_interworking: bool,
1535
1536     /// Which kind of debuginfo is used by this target?
1537     pub debuginfo_kind: DebuginfoKind,
1538     /// How to handle split debug information, if at all. Specifying `None` has
1539     /// target-specific meaning.
1540     pub split_debuginfo: SplitDebuginfo,
1541     /// Which kinds of split debuginfo are supported by the target?
1542     pub supported_split_debuginfo: StaticCow<[SplitDebuginfo]>,
1543
1544     /// The sanitizers supported by this target
1545     ///
1546     /// Note that the support here is at a codegen level. If the machine code with sanitizer
1547     /// enabled can generated on this target, but the necessary supporting libraries are not
1548     /// distributed with the target, the sanitizer should still appear in this list for the target.
1549     pub supported_sanitizers: SanitizerSet,
1550
1551     /// If present it's a default value to use for adjusting the C ABI.
1552     pub default_adjusted_cabi: Option<Abi>,
1553
1554     /// Minimum number of bits in #[repr(C)] enum. Defaults to 32.
1555     pub c_enum_min_bits: u64,
1556
1557     /// Whether or not the DWARF `.debug_aranges` section should be generated.
1558     pub generate_arange_section: bool,
1559
1560     /// Whether the target supports stack canary checks. `true` by default,
1561     /// since this is most common among tier 1 and tier 2 targets.
1562     pub supports_stack_protector: bool,
1563 }
1564
1565 /// Add arguments for the given flavor and also for its "twin" flavors
1566 /// that have a compatible command line interface.
1567 fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'static str]) {
1568     let mut insert = |flavor| {
1569         link_args.entry(flavor).or_default().extend(args.iter().copied().map(Cow::Borrowed))
1570     };
1571     insert(flavor);
1572     match flavor {
1573         LinkerFlavor::Ld => insert(LinkerFlavor::Lld(LldFlavor::Ld)),
1574         LinkerFlavor::Msvc => insert(LinkerFlavor::Lld(LldFlavor::Link)),
1575         LinkerFlavor::Lld(LldFlavor::Ld64) | LinkerFlavor::Lld(LldFlavor::Wasm) => {}
1576         LinkerFlavor::Lld(lld_flavor) => {
1577             panic!("add_link_args: use non-LLD flavor for {:?}", lld_flavor)
1578         }
1579         LinkerFlavor::Gcc | LinkerFlavor::EmCc | LinkerFlavor::Bpf | LinkerFlavor::Ptx => {}
1580     }
1581 }
1582
1583 impl TargetOptions {
1584     fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
1585         let mut link_args = LinkArgs::new();
1586         add_link_args(&mut link_args, flavor, args);
1587         link_args
1588     }
1589
1590     fn add_pre_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1591         add_link_args(&mut self.pre_link_args, flavor, args);
1592     }
1593
1594     fn add_post_link_args(&mut self, flavor: LinkerFlavor, args: &[&'static str]) {
1595         add_link_args(&mut self.post_link_args, flavor, args);
1596     }
1597
1598     fn update_from_cli(&mut self) {
1599         self.linker_flavor = LinkerFlavor::from_cli(self.linker_flavor_json);
1600         for (args, args_json) in [
1601             (&mut self.pre_link_args, &self.pre_link_args_json),
1602             (&mut self.late_link_args, &self.late_link_args_json),
1603             (&mut self.late_link_args_dynamic, &self.late_link_args_dynamic_json),
1604             (&mut self.late_link_args_static, &self.late_link_args_static_json),
1605             (&mut self.post_link_args, &self.post_link_args_json),
1606         ] {
1607             *args = args_json
1608                 .iter()
1609                 .map(|(flavor, args)| (LinkerFlavor::from_cli(*flavor), args.clone()))
1610                 .collect();
1611         }
1612     }
1613
1614     fn update_to_cli(&mut self) {
1615         self.linker_flavor_json = self.linker_flavor.to_cli();
1616         for (args, args_json) in [
1617             (&self.pre_link_args, &mut self.pre_link_args_json),
1618             (&self.late_link_args, &mut self.late_link_args_json),
1619             (&self.late_link_args_dynamic, &mut self.late_link_args_dynamic_json),
1620             (&self.late_link_args_static, &mut self.late_link_args_static_json),
1621             (&self.post_link_args, &mut self.post_link_args_json),
1622         ] {
1623             *args_json =
1624                 args.iter().map(|(flavor, args)| (flavor.to_cli(), args.clone())).collect();
1625         }
1626     }
1627 }
1628
1629 impl Default for TargetOptions {
1630     /// Creates a set of "sane defaults" for any target. This is still
1631     /// incomplete, and if used for compilation, will certainly not work.
1632     fn default() -> TargetOptions {
1633         TargetOptions {
1634             is_builtin: false,
1635             endian: Endian::Little,
1636             c_int_width: "32".into(),
1637             os: "none".into(),
1638             env: "".into(),
1639             abi: "".into(),
1640             vendor: "unknown".into(),
1641             linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.into()),
1642             linker_flavor: LinkerFlavor::Gcc,
1643             linker_flavor_json: LinkerFlavorCli::Gcc,
1644             lld_flavor: LldFlavor::Ld,
1645             linker_is_gnu: true,
1646             link_script: None,
1647             asm_args: cvs![],
1648             cpu: "generic".into(),
1649             features: "".into(),
1650             dynamic_linking: false,
1651             only_cdylib: false,
1652             executables: true,
1653             relocation_model: RelocModel::Pic,
1654             code_model: None,
1655             tls_model: TlsModel::GeneralDynamic,
1656             disable_redzone: false,
1657             frame_pointer: FramePointer::MayOmit,
1658             function_sections: true,
1659             dll_prefix: "lib".into(),
1660             dll_suffix: ".so".into(),
1661             exe_suffix: "".into(),
1662             staticlib_prefix: "lib".into(),
1663             staticlib_suffix: ".a".into(),
1664             families: cvs![],
1665             abi_return_struct_as_int: false,
1666             is_like_osx: false,
1667             is_like_solaris: false,
1668             is_like_windows: false,
1669             is_like_msvc: false,
1670             is_like_wasm: false,
1671             default_dwarf_version: 4,
1672             allows_weak_linkage: true,
1673             has_rpath: false,
1674             no_default_libraries: true,
1675             position_independent_executables: false,
1676             static_position_independent_executables: false,
1677             needs_plt: false,
1678             relro_level: RelroLevel::None,
1679             pre_link_objects: Default::default(),
1680             post_link_objects: Default::default(),
1681             pre_link_objects_self_contained: Default::default(),
1682             post_link_objects_self_contained: Default::default(),
1683             link_self_contained: LinkSelfContainedDefault::False,
1684             pre_link_args: LinkArgs::new(),
1685             pre_link_args_json: LinkArgsCli::new(),
1686             late_link_args: LinkArgs::new(),
1687             late_link_args_json: LinkArgsCli::new(),
1688             late_link_args_dynamic: LinkArgs::new(),
1689             late_link_args_dynamic_json: LinkArgsCli::new(),
1690             late_link_args_static: LinkArgs::new(),
1691             late_link_args_static_json: LinkArgsCli::new(),
1692             post_link_args: LinkArgs::new(),
1693             post_link_args_json: LinkArgsCli::new(),
1694             link_env: cvs![],
1695             link_env_remove: cvs![],
1696             archive_format: "gnu".into(),
1697             main_needs_argc_argv: true,
1698             allow_asm: true,
1699             has_thread_local: false,
1700             obj_is_bitcode: false,
1701             forces_embed_bitcode: false,
1702             bitcode_llvm_cmdline: "".into(),
1703             min_atomic_width: None,
1704             max_atomic_width: None,
1705             atomic_cas: true,
1706             panic_strategy: PanicStrategy::Unwind,
1707             crt_static_allows_dylibs: false,
1708             crt_static_default: false,
1709             crt_static_respected: false,
1710             stack_probes: StackProbeType::None,
1711             min_global_align: None,
1712             default_codegen_units: None,
1713             trap_unreachable: true,
1714             requires_lto: false,
1715             singlethread: false,
1716             no_builtins: false,
1717             default_hidden_visibility: false,
1718             emit_debug_gdb_scripts: true,
1719             requires_uwtable: false,
1720             default_uwtable: false,
1721             simd_types_indirect: true,
1722             limit_rdylib_exports: true,
1723             override_export_symbols: None,
1724             merge_functions: MergeFunctions::Aliases,
1725             mcount: "mcount".into(),
1726             llvm_abiname: "".into(),
1727             relax_elf_relocations: false,
1728             llvm_args: cvs![],
1729             use_ctors_section: false,
1730             eh_frame_header: true,
1731             has_thumb_interworking: false,
1732             debuginfo_kind: Default::default(),
1733             split_debuginfo: Default::default(),
1734             // `Off` is supported by default, but targets can remove this manually, e.g. Windows.
1735             supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]),
1736             supported_sanitizers: SanitizerSet::empty(),
1737             default_adjusted_cabi: None,
1738             c_enum_min_bits: 32,
1739             generate_arange_section: true,
1740             supports_stack_protector: true,
1741         }
1742     }
1743 }
1744
1745 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1746 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1747 /// this `Deref` implementation is no longer necessary.
1748 impl Deref for Target {
1749     type Target = TargetOptions;
1750
1751     #[inline]
1752     fn deref(&self) -> &Self::Target {
1753         &self.options
1754     }
1755 }
1756 impl DerefMut for Target {
1757     #[inline]
1758     fn deref_mut(&mut self) -> &mut Self::Target {
1759         &mut self.options
1760     }
1761 }
1762
1763 impl Target {
1764     /// Given a function ABI, turn it into the correct ABI for this target.
1765     pub fn adjust_abi(&self, abi: Abi) -> Abi {
1766         match abi {
1767             Abi::C { .. } => self.default_adjusted_cabi.unwrap_or(abi),
1768             Abi::System { unwind } if self.is_like_windows && self.arch == "x86" => {
1769                 Abi::Stdcall { unwind }
1770             }
1771             Abi::System { unwind } => Abi::C { unwind },
1772             Abi::EfiApi if self.arch == "x86_64" => Abi::Win64 { unwind: false },
1773             Abi::EfiApi => Abi::C { unwind: false },
1774
1775             // See commentary in `is_abi_supported`.
1776             Abi::Stdcall { .. } | Abi::Thiscall { .. } if self.arch == "x86" => abi,
1777             Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => Abi::C { unwind },
1778             Abi::Fastcall { .. } if self.arch == "x86" => abi,
1779             Abi::Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => abi,
1780             Abi::Fastcall { unwind } | Abi::Vectorcall { unwind } => Abi::C { unwind },
1781
1782             abi => abi,
1783         }
1784     }
1785
1786     /// Returns a None if the UNSUPPORTED_CALLING_CONVENTIONS lint should be emitted
1787     pub fn is_abi_supported(&self, abi: Abi) -> Option<bool> {
1788         use Abi::*;
1789         Some(match abi {
1790             Rust
1791             | C { .. }
1792             | System { .. }
1793             | RustIntrinsic
1794             | RustCall
1795             | PlatformIntrinsic
1796             | Unadjusted
1797             | Cdecl { .. }
1798             | EfiApi
1799             | RustCold => true,
1800             X86Interrupt => ["x86", "x86_64"].contains(&&self.arch[..]),
1801             Aapcs { .. } => "arm" == self.arch,
1802             CCmseNonSecureCall => ["arm", "aarch64"].contains(&&self.arch[..]),
1803             Win64 { .. } | SysV64 { .. } => self.arch == "x86_64",
1804             PtxKernel => self.arch == "nvptx64",
1805             Msp430Interrupt => self.arch == "msp430",
1806             AmdGpuKernel => self.arch == "amdgcn",
1807             AvrInterrupt | AvrNonBlockingInterrupt => self.arch == "avr",
1808             Wasm => ["wasm32", "wasm64"].contains(&&self.arch[..]),
1809             Thiscall { .. } => self.arch == "x86",
1810             // On windows these fall-back to platform native calling convention (C) when the
1811             // architecture is not supported.
1812             //
1813             // This is I believe a historical accident that has occurred as part of Microsoft
1814             // striving to allow most of the code to "just" compile when support for 64-bit x86
1815             // was added and then later again, when support for ARM architectures was added.
1816             //
1817             // This is well documented across MSDN. Support for this in Rust has been added in
1818             // #54576. This makes much more sense in context of Microsoft's C++ than it does in
1819             // Rust, but there isn't much leeway remaining here to change it back at the time this
1820             // comment has been written.
1821             //
1822             // Following are the relevant excerpts from the MSDN documentation.
1823             //
1824             // > The __vectorcall calling convention is only supported in native code on x86 and
1825             // x64 processors that include Streaming SIMD Extensions 2 (SSE2) and above.
1826             // > ...
1827             // > On ARM machines, __vectorcall is accepted and ignored by the compiler.
1828             //
1829             // -- https://docs.microsoft.com/en-us/cpp/cpp/vectorcall?view=msvc-160
1830             //
1831             // > On ARM and x64 processors, __stdcall is accepted and ignored by the compiler;
1832             //
1833             // -- https://docs.microsoft.com/en-us/cpp/cpp/stdcall?view=msvc-160
1834             //
1835             // > In most cases, keywords or compiler switches that specify an unsupported
1836             // > convention on a particular platform are ignored, and the platform default
1837             // > convention is used.
1838             //
1839             // -- https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1840             Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } if self.is_like_windows => true,
1841             // Outside of Windows we want to only support these calling conventions for the
1842             // architectures for which these calling conventions are actually well defined.
1843             Stdcall { .. } | Fastcall { .. } if self.arch == "x86" => true,
1844             Vectorcall { .. } if ["x86", "x86_64"].contains(&&self.arch[..]) => true,
1845             // Return a `None` for other cases so that we know to emit a future compat lint.
1846             Stdcall { .. } | Fastcall { .. } | Vectorcall { .. } => return None,
1847         })
1848     }
1849
1850     /// Minimum integer size in bits that this target can perform atomic
1851     /// operations on.
1852     pub fn min_atomic_width(&self) -> u64 {
1853         self.min_atomic_width.unwrap_or(8)
1854     }
1855
1856     /// Maximum integer size in bits that this target can perform atomic
1857     /// operations on.
1858     pub fn max_atomic_width(&self) -> u64 {
1859         self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1860     }
1861
1862     /// Loads a target descriptor from a JSON object.
1863     pub fn from_json(obj: Json) -> Result<(Target, TargetWarnings), String> {
1864         // While ugly, this code must remain this way to retain
1865         // compatibility with existing JSON fields and the internal
1866         // expected naming of the Target and TargetOptions structs.
1867         // To ensure compatibility is retained, the built-in targets
1868         // are round-tripped through this code to catch cases where
1869         // the JSON parser is not updated to match the structs.
1870
1871         let mut obj = match obj {
1872             Value::Object(obj) => obj,
1873             _ => return Err("Expected JSON object for target")?,
1874         };
1875
1876         let mut get_req_field = |name: &str| {
1877             obj.remove(name)
1878                 .and_then(|j| j.as_str().map(str::to_string))
1879                 .ok_or_else(|| format!("Field {} in target specification is required", name))
1880         };
1881
1882         let mut base = Target {
1883             llvm_target: get_req_field("llvm-target")?.into(),
1884             pointer_width: get_req_field("target-pointer-width")?
1885                 .parse::<u32>()
1886                 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1887             data_layout: get_req_field("data-layout")?.into(),
1888             arch: get_req_field("arch")?.into(),
1889             options: Default::default(),
1890         };
1891
1892         let mut incorrect_type = vec![];
1893
1894         macro_rules! key {
1895             ($key_name:ident) => ( {
1896                 let name = (stringify!($key_name)).replace("_", "-");
1897                 if let Some(s) = obj.remove(&name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
1898                     base.$key_name = s;
1899                 }
1900             } );
1901             ($key_name:ident = $json_name:expr) => ( {
1902                 let name = $json_name;
1903                 if let Some(s) = obj.remove(name).and_then(|s| s.as_str().map(str::to_string).map(Cow::from)) {
1904                     base.$key_name = s;
1905                 }
1906             } );
1907             ($key_name:ident, bool) => ( {
1908                 let name = (stringify!($key_name)).replace("_", "-");
1909                 if let Some(s) = obj.remove(&name).and_then(|b| b.as_bool()) {
1910                     base.$key_name = s;
1911                 }
1912             } );
1913             ($key_name:ident, u64) => ( {
1914                 let name = (stringify!($key_name)).replace("_", "-");
1915                 if let Some(s) = obj.remove(&name).and_then(|j| Json::as_u64(&j)) {
1916                     base.$key_name = s;
1917                 }
1918             } );
1919             ($key_name:ident, u32) => ( {
1920                 let name = (stringify!($key_name)).replace("_", "-");
1921                 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
1922                     if s < 1 || s > 5 {
1923                         return Err("Not a valid DWARF version number".into());
1924                     }
1925                     base.$key_name = s as u32;
1926                 }
1927             } );
1928             ($key_name:ident, Option<u64>) => ( {
1929                 let name = (stringify!($key_name)).replace("_", "-");
1930                 if let Some(s) = obj.remove(&name).and_then(|b| b.as_u64()) {
1931                     base.$key_name = Some(s);
1932                 }
1933             } );
1934             ($key_name:ident, MergeFunctions) => ( {
1935                 let name = (stringify!($key_name)).replace("_", "-");
1936                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1937                     match s.parse::<MergeFunctions>() {
1938                         Ok(mergefunc) => base.$key_name = mergefunc,
1939                         _ => return Some(Err(format!("'{}' is not a valid value for \
1940                                                       merge-functions. Use 'disabled', \
1941                                                       'trampolines', or 'aliases'.",
1942                                                       s))),
1943                     }
1944                     Some(Ok(()))
1945                 })).unwrap_or(Ok(()))
1946             } );
1947             ($key_name:ident, RelocModel) => ( {
1948                 let name = (stringify!($key_name)).replace("_", "-");
1949                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1950                     match s.parse::<RelocModel>() {
1951                         Ok(relocation_model) => base.$key_name = relocation_model,
1952                         _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1953                                                       Run `rustc --print relocation-models` to \
1954                                                       see the list of supported values.", s))),
1955                     }
1956                     Some(Ok(()))
1957                 })).unwrap_or(Ok(()))
1958             } );
1959             ($key_name:ident, CodeModel) => ( {
1960                 let name = (stringify!($key_name)).replace("_", "-");
1961                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1962                     match s.parse::<CodeModel>() {
1963                         Ok(code_model) => base.$key_name = Some(code_model),
1964                         _ => return Some(Err(format!("'{}' is not a valid code model. \
1965                                                       Run `rustc --print code-models` to \
1966                                                       see the list of supported values.", s))),
1967                     }
1968                     Some(Ok(()))
1969                 })).unwrap_or(Ok(()))
1970             } );
1971             ($key_name:ident, TlsModel) => ( {
1972                 let name = (stringify!($key_name)).replace("_", "-");
1973                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1974                     match s.parse::<TlsModel>() {
1975                         Ok(tls_model) => base.$key_name = tls_model,
1976                         _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1977                                                       Run `rustc --print tls-models` to \
1978                                                       see the list of supported values.", s))),
1979                     }
1980                     Some(Ok(()))
1981                 })).unwrap_or(Ok(()))
1982             } );
1983             ($key_name:ident, PanicStrategy) => ( {
1984                 let name = (stringify!($key_name)).replace("_", "-");
1985                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1986                     match s {
1987                         "unwind" => base.$key_name = PanicStrategy::Unwind,
1988                         "abort" => base.$key_name = PanicStrategy::Abort,
1989                         _ => return Some(Err(format!("'{}' is not a valid value for \
1990                                                       panic-strategy. Use 'unwind' or 'abort'.",
1991                                                      s))),
1992                 }
1993                 Some(Ok(()))
1994             })).unwrap_or(Ok(()))
1995             } );
1996             ($key_name:ident, RelroLevel) => ( {
1997                 let name = (stringify!($key_name)).replace("_", "-");
1998                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
1999                     match s.parse::<RelroLevel>() {
2000                         Ok(level) => base.$key_name = level,
2001                         _ => return Some(Err(format!("'{}' is not a valid value for \
2002                                                       relro-level. Use 'full', 'partial, or 'off'.",
2003                                                       s))),
2004                     }
2005                     Some(Ok(()))
2006                 })).unwrap_or(Ok(()))
2007             } );
2008             ($key_name:ident, DebuginfoKind) => ( {
2009                 let name = (stringify!($key_name)).replace("_", "-");
2010                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2011                     match s.parse::<DebuginfoKind>() {
2012                         Ok(level) => base.$key_name = level,
2013                         _ => return Some(Err(
2014                             format!("'{s}' is not a valid value for debuginfo-kind. Use 'dwarf', \
2015                                   'dwarf-dsym' or 'pdb'.")
2016                         )),
2017                     }
2018                     Some(Ok(()))
2019                 })).unwrap_or(Ok(()))
2020             } );
2021             ($key_name:ident, SplitDebuginfo) => ( {
2022                 let name = (stringify!($key_name)).replace("_", "-");
2023                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2024                     match s.parse::<SplitDebuginfo>() {
2025                         Ok(level) => base.$key_name = level,
2026                         _ => return Some(Err(format!("'{}' is not a valid value for \
2027                                                       split-debuginfo. Use 'off' or 'dsymutil'.",
2028                                                       s))),
2029                     }
2030                     Some(Ok(()))
2031                 })).unwrap_or(Ok(()))
2032             } );
2033             ($key_name:ident, list) => ( {
2034                 let name = (stringify!($key_name)).replace("_", "-");
2035                 if let Some(j) = obj.remove(&name) {
2036                     if let Some(v) = j.as_array() {
2037                         base.$key_name = v.iter()
2038                             .map(|a| a.as_str().unwrap().to_string().into())
2039                             .collect();
2040                     } else {
2041                         incorrect_type.push(name)
2042                     }
2043                 }
2044             } );
2045             ($key_name:ident, opt_list) => ( {
2046                 let name = (stringify!($key_name)).replace("_", "-");
2047                 if let Some(j) = obj.remove(&name) {
2048                     if let Some(v) = j.as_array() {
2049                         base.$key_name = Some(v.iter()
2050                             .map(|a| a.as_str().unwrap().to_string().into())
2051                             .collect());
2052                     } else {
2053                         incorrect_type.push(name)
2054                     }
2055                 }
2056             } );
2057             ($key_name:ident, falliable_list) => ( {
2058                 let name = (stringify!($key_name)).replace("_", "-");
2059                 obj.remove(&name).and_then(|j| {
2060                     if let Some(v) = j.as_array() {
2061                         match v.iter().map(|a| FromStr::from_str(a.as_str().unwrap())).collect() {
2062                             Ok(l) => { base.$key_name = l },
2063                             // FIXME: `falliable_list` can't re-use the `key!` macro for list
2064                             // elements and the error messages from that macro, so it has a bad
2065                             // generic message instead
2066                             Err(_) => return Some(Err(
2067                                 format!("`{:?}` is not a valid value for `{}`", j, name)
2068                             )),
2069                         }
2070                     } else {
2071                         incorrect_type.push(name)
2072                     }
2073                     Some(Ok(()))
2074                 }).unwrap_or(Ok(()))
2075             } );
2076             ($key_name:ident, optional) => ( {
2077                 let name = (stringify!($key_name)).replace("_", "-");
2078                 if let Some(o) = obj.remove(&name) {
2079                     base.$key_name = o
2080                         .as_str()
2081                         .map(|s| s.to_string().into());
2082                 }
2083             } );
2084             ($key_name:ident, LldFlavor) => ( {
2085                 let name = (stringify!($key_name)).replace("_", "-");
2086                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2087                     if let Some(flavor) = LldFlavor::from_str(&s) {
2088                         base.$key_name = flavor;
2089                     } else {
2090                         return Some(Err(format!(
2091                             "'{}' is not a valid value for lld-flavor. \
2092                              Use 'darwin', 'gnu', 'link' or 'wasm.",
2093                             s)))
2094                     }
2095                     Some(Ok(()))
2096                 })).unwrap_or(Ok(()))
2097             } );
2098             ($key_name:ident = $json_name:expr, LinkerFlavor) => ( {
2099                 let name = $json_name;
2100                 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2101                     match LinkerFlavorCli::from_str(s) {
2102                         Some(linker_flavor) => base.$key_name = linker_flavor,
2103                         _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
2104                                                       Use {}", s, LinkerFlavorCli::one_of()))),
2105                     }
2106                     Some(Ok(()))
2107                 })).unwrap_or(Ok(()))
2108             } );
2109             ($key_name:ident, StackProbeType) => ( {
2110                 let name = (stringify!($key_name)).replace("_", "-");
2111                 obj.remove(&name).and_then(|o| match StackProbeType::from_json(&o) {
2112                     Ok(v) => {
2113                         base.$key_name = v;
2114                         Some(Ok(()))
2115                     },
2116                     Err(s) => Some(Err(
2117                         format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
2118                     )),
2119                 }).unwrap_or(Ok(()))
2120             } );
2121             ($key_name:ident, SanitizerSet) => ( {
2122                 let name = (stringify!($key_name)).replace("_", "-");
2123                 if let Some(o) = obj.remove(&name) {
2124                     if let Some(a) = o.as_array() {
2125                         for s in a {
2126                             base.$key_name |= match s.as_str() {
2127                                 Some("address") => SanitizerSet::ADDRESS,
2128                                 Some("cfi") => SanitizerSet::CFI,
2129                                 Some("leak") => SanitizerSet::LEAK,
2130                                 Some("memory") => SanitizerSet::MEMORY,
2131                                 Some("memtag") => SanitizerSet::MEMTAG,
2132                                 Some("shadow-call-stack") => SanitizerSet::SHADOWCALLSTACK,
2133                                 Some("thread") => SanitizerSet::THREAD,
2134                                 Some("hwaddress") => SanitizerSet::HWADDRESS,
2135                                 Some(s) => return Err(format!("unknown sanitizer {}", s)),
2136                                 _ => return Err(format!("not a string: {:?}", s)),
2137                             };
2138                         }
2139                     } else {
2140                         incorrect_type.push(name)
2141                     }
2142                 }
2143                 Ok::<(), String>(())
2144             } );
2145
2146             ($key_name:ident = $json_name:expr, link_self_contained) => ( {
2147                 let name = $json_name;
2148                 obj.remove(name).and_then(|o| o.as_str().and_then(|s| {
2149                     match s.parse::<LinkSelfContainedDefault>() {
2150                         Ok(lsc_default) => base.$key_name = lsc_default,
2151                         _ => return Some(Err(format!("'{}' is not a valid `-Clink-self-contained` default. \
2152                                                       Use 'false', 'true', 'musl' or 'mingw'", s))),
2153                     }
2154                     Some(Ok(()))
2155                 })).unwrap_or(Ok(()))
2156             } );
2157             ($key_name:ident = $json_name:expr, link_objects) => ( {
2158                 let name = $json_name;
2159                 if let Some(val) = obj.remove(name) {
2160                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2161                         JSON object with fields per CRT object kind.", name))?;
2162                     let mut args = CrtObjects::new();
2163                     for (k, v) in obj {
2164                         let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
2165                             format!("{}: '{}' is not a valid value for CRT object kind. \
2166                                      Use '(dynamic,static)-(nopic,pic)-exe' or \
2167                                      '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
2168                         })?;
2169
2170                         let v = v.as_array().ok_or_else(||
2171                             format!("{}.{}: expected a JSON array", name, k)
2172                         )?.iter().enumerate()
2173                             .map(|(i,s)| {
2174                                 let s = s.as_str().ok_or_else(||
2175                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2176                                 Ok(s.to_string().into())
2177                             })
2178                             .collect::<Result<Vec<_>, String>>()?;
2179
2180                         args.insert(kind, v);
2181                     }
2182                     base.$key_name = args;
2183                 }
2184             } );
2185             ($key_name:ident = $json_name:expr, link_args) => ( {
2186                 let name = $json_name;
2187                 if let Some(val) = obj.remove(name) {
2188                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
2189                         JSON object with fields per linker-flavor.", name))?;
2190                     let mut args = LinkArgsCli::new();
2191                     for (k, v) in obj {
2192                         let flavor = LinkerFlavorCli::from_str(&k).ok_or_else(|| {
2193                             format!("{}: '{}' is not a valid value for linker-flavor. \
2194                                      Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
2195                         })?;
2196
2197                         let v = v.as_array().ok_or_else(||
2198                             format!("{}.{}: expected a JSON array", name, k)
2199                         )?.iter().enumerate()
2200                             .map(|(i,s)| {
2201                                 let s = s.as_str().ok_or_else(||
2202                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
2203                                 Ok(s.to_string().into())
2204                             })
2205                             .collect::<Result<Vec<_>, String>>()?;
2206
2207                         args.insert(flavor, v);
2208                     }
2209                     base.$key_name = args;
2210                 }
2211             } );
2212             ($key_name:ident, env) => ( {
2213                 let name = (stringify!($key_name)).replace("_", "-");
2214                 if let Some(o) = obj.remove(&name) {
2215                     if let Some(a) = o.as_array() {
2216                         for o in a {
2217                             if let Some(s) = o.as_str() {
2218                                 let p = s.split('=').collect::<Vec<_>>();
2219                                 if p.len() == 2 {
2220                                     let k = p[0].to_string();
2221                                     let v = p[1].to_string();
2222                                     base.$key_name.to_mut().push((k.into(), v.into()));
2223                                 }
2224                             }
2225                         }
2226                     } else {
2227                         incorrect_type.push(name)
2228                     }
2229                 }
2230             } );
2231             ($key_name:ident, Option<Abi>) => ( {
2232                 let name = (stringify!($key_name)).replace("_", "-");
2233                 obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2234                     match lookup_abi(s) {
2235                         Some(abi) => base.$key_name = Some(abi),
2236                         _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
2237                     }
2238                     Some(Ok(()))
2239                 })).unwrap_or(Ok(()))
2240             } );
2241             ($key_name:ident, TargetFamilies) => ( {
2242                 if let Some(value) = obj.remove("target-family") {
2243                     if let Some(v) = value.as_array() {
2244                         base.$key_name = v.iter()
2245                             .map(|a| a.as_str().unwrap().to_string().into())
2246                             .collect();
2247                     } else if let Some(v) = value.as_str() {
2248                         base.$key_name = vec![v.to_string().into()].into();
2249                     }
2250                 }
2251             } );
2252         }
2253
2254         if let Some(j) = obj.remove("target-endian") {
2255             if let Some(s) = j.as_str() {
2256                 base.endian = s.parse()?;
2257             } else {
2258                 incorrect_type.push("target-endian".into())
2259             }
2260         }
2261
2262         if let Some(fp) = obj.remove("frame-pointer") {
2263             if let Some(s) = fp.as_str() {
2264                 base.frame_pointer = s
2265                     .parse()
2266                     .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?;
2267             } else {
2268                 incorrect_type.push("frame-pointer".into())
2269             }
2270         }
2271
2272         key!(is_builtin, bool);
2273         key!(c_int_width = "target-c-int-width");
2274         key!(os);
2275         key!(env);
2276         key!(abi);
2277         key!(vendor);
2278         key!(linker, optional);
2279         key!(linker_flavor_json = "linker-flavor", LinkerFlavor)?;
2280         key!(lld_flavor, LldFlavor)?;
2281         key!(linker_is_gnu, bool);
2282         key!(pre_link_objects = "pre-link-objects", link_objects);
2283         key!(post_link_objects = "post-link-objects", link_objects);
2284         key!(pre_link_objects_self_contained = "pre-link-objects-fallback", link_objects);
2285         key!(post_link_objects_self_contained = "post-link-objects-fallback", link_objects);
2286         key!(link_self_contained = "crt-objects-fallback", link_self_contained)?;
2287         key!(pre_link_args_json = "pre-link-args", link_args);
2288         key!(late_link_args_json = "late-link-args", link_args);
2289         key!(late_link_args_dynamic_json = "late-link-args-dynamic", link_args);
2290         key!(late_link_args_static_json = "late-link-args-static", link_args);
2291         key!(post_link_args_json = "post-link-args", link_args);
2292         key!(link_script, optional);
2293         key!(link_env, env);
2294         key!(link_env_remove, list);
2295         key!(asm_args, list);
2296         key!(cpu);
2297         key!(features);
2298         key!(dynamic_linking, bool);
2299         key!(only_cdylib, bool);
2300         key!(executables, bool);
2301         key!(relocation_model, RelocModel)?;
2302         key!(code_model, CodeModel)?;
2303         key!(tls_model, TlsModel)?;
2304         key!(disable_redzone, bool);
2305         key!(function_sections, bool);
2306         key!(dll_prefix);
2307         key!(dll_suffix);
2308         key!(exe_suffix);
2309         key!(staticlib_prefix);
2310         key!(staticlib_suffix);
2311         key!(families, TargetFamilies);
2312         key!(abi_return_struct_as_int, bool);
2313         key!(is_like_osx, bool);
2314         key!(is_like_solaris, bool);
2315         key!(is_like_windows, bool);
2316         key!(is_like_msvc, bool);
2317         key!(is_like_wasm, bool);
2318         key!(default_dwarf_version, u32);
2319         key!(allows_weak_linkage, bool);
2320         key!(has_rpath, bool);
2321         key!(no_default_libraries, bool);
2322         key!(position_independent_executables, bool);
2323         key!(static_position_independent_executables, bool);
2324         key!(needs_plt, bool);
2325         key!(relro_level, RelroLevel)?;
2326         key!(archive_format);
2327         key!(allow_asm, bool);
2328         key!(main_needs_argc_argv, bool);
2329         key!(has_thread_local, bool);
2330         key!(obj_is_bitcode, bool);
2331         key!(forces_embed_bitcode, bool);
2332         key!(bitcode_llvm_cmdline);
2333         key!(max_atomic_width, Option<u64>);
2334         key!(min_atomic_width, Option<u64>);
2335         key!(atomic_cas, bool);
2336         key!(panic_strategy, PanicStrategy)?;
2337         key!(crt_static_allows_dylibs, bool);
2338         key!(crt_static_default, bool);
2339         key!(crt_static_respected, bool);
2340         key!(stack_probes, StackProbeType)?;
2341         key!(min_global_align, Option<u64>);
2342         key!(default_codegen_units, Option<u64>);
2343         key!(trap_unreachable, bool);
2344         key!(requires_lto, bool);
2345         key!(singlethread, bool);
2346         key!(no_builtins, bool);
2347         key!(default_hidden_visibility, bool);
2348         key!(emit_debug_gdb_scripts, bool);
2349         key!(requires_uwtable, bool);
2350         key!(default_uwtable, bool);
2351         key!(simd_types_indirect, bool);
2352         key!(limit_rdylib_exports, bool);
2353         key!(override_export_symbols, opt_list);
2354         key!(merge_functions, MergeFunctions)?;
2355         key!(mcount = "target-mcount");
2356         key!(llvm_abiname);
2357         key!(relax_elf_relocations, bool);
2358         key!(llvm_args, list);
2359         key!(use_ctors_section, bool);
2360         key!(eh_frame_header, bool);
2361         key!(has_thumb_interworking, bool);
2362         key!(debuginfo_kind, DebuginfoKind)?;
2363         key!(split_debuginfo, SplitDebuginfo)?;
2364         key!(supported_split_debuginfo, falliable_list)?;
2365         key!(supported_sanitizers, SanitizerSet)?;
2366         key!(default_adjusted_cabi, Option<Abi>)?;
2367         key!(c_enum_min_bits, u64);
2368         key!(generate_arange_section, bool);
2369         key!(supports_stack_protector, bool);
2370
2371         if base.is_builtin {
2372             // This can cause unfortunate ICEs later down the line.
2373             return Err("may not set is_builtin for targets not built-in".into());
2374         }
2375         base.update_from_cli();
2376
2377         // Each field should have been read using `Json::remove` so any keys remaining are unused.
2378         let remaining_keys = obj.keys();
2379         Ok((
2380             base,
2381             TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type },
2382         ))
2383     }
2384
2385     /// Load a built-in target
2386     pub fn expect_builtin(target_triple: &TargetTriple) -> Target {
2387         match *target_triple {
2388             TargetTriple::TargetTriple(ref target_triple) => {
2389                 load_builtin(target_triple).expect("built-in target")
2390             }
2391             TargetTriple::TargetJson { .. } => {
2392                 panic!("built-in targets doesn't support target-paths")
2393             }
2394         }
2395     }
2396
2397     /// Search for a JSON file specifying the given target triple.
2398     ///
2399     /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
2400     /// sysroot under the target-triple's `rustlib` directory.  Note that it could also just be a
2401     /// bare filename already, so also check for that. If one of the hardcoded targets we know
2402     /// about, just return it directly.
2403     ///
2404     /// The error string could come from any of the APIs called, including filesystem access and
2405     /// JSON decoding.
2406     pub fn search(
2407         target_triple: &TargetTriple,
2408         sysroot: &Path,
2409     ) -> Result<(Target, TargetWarnings), String> {
2410         use std::env;
2411         use std::fs;
2412
2413         fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
2414             let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
2415             let obj = serde_json::from_str(&contents).map_err(|e| e.to_string())?;
2416             Target::from_json(obj)
2417         }
2418
2419         match *target_triple {
2420             TargetTriple::TargetTriple(ref target_triple) => {
2421                 // check if triple is in list of built-in targets
2422                 if let Some(t) = load_builtin(target_triple) {
2423                     return Ok((t, TargetWarnings::empty()));
2424                 }
2425
2426                 // search for a file named `target_triple`.json in RUST_TARGET_PATH
2427                 let path = {
2428                     let mut target = target_triple.to_string();
2429                     target.push_str(".json");
2430                     PathBuf::from(target)
2431                 };
2432
2433                 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
2434
2435                 for dir in env::split_paths(&target_path) {
2436                     let p = dir.join(&path);
2437                     if p.is_file() {
2438                         return load_file(&p);
2439                     }
2440                 }
2441
2442                 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
2443                 // as a fallback.
2444                 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
2445                 let p = PathBuf::from_iter([
2446                     Path::new(sysroot),
2447                     Path::new(&rustlib_path),
2448                     Path::new("target.json"),
2449                 ]);
2450                 if p.is_file() {
2451                     return load_file(&p);
2452                 }
2453
2454                 Err(format!("Could not find specification for target {:?}", target_triple))
2455             }
2456             TargetTriple::TargetJson { ref contents, .. } => {
2457                 let obj = serde_json::from_str(contents).map_err(|e| e.to_string())?;
2458                 Target::from_json(obj)
2459             }
2460         }
2461     }
2462 }
2463
2464 impl ToJson for Target {
2465     fn to_json(&self) -> Json {
2466         let mut d = serde_json::Map::new();
2467         let default: TargetOptions = Default::default();
2468         let mut target = self.clone();
2469         target.update_to_cli();
2470
2471         macro_rules! target_val {
2472             ($attr:ident) => {{
2473                 let name = (stringify!($attr)).replace("_", "-");
2474                 d.insert(name, target.$attr.to_json());
2475             }};
2476         }
2477
2478         macro_rules! target_option_val {
2479             ($attr:ident) => {{
2480                 let name = (stringify!($attr)).replace("_", "-");
2481                 if default.$attr != target.$attr {
2482                     d.insert(name, target.$attr.to_json());
2483                 }
2484             }};
2485             ($attr:ident, $json_name:expr) => {{
2486                 let name = $json_name;
2487                 if default.$attr != target.$attr {
2488                     d.insert(name.into(), target.$attr.to_json());
2489                 }
2490             }};
2491             (link_args - $attr:ident, $json_name:expr) => {{
2492                 let name = $json_name;
2493                 if default.$attr != target.$attr {
2494                     let obj = target
2495                         .$attr
2496                         .iter()
2497                         .map(|(k, v)| (k.desc().to_string(), v.clone()))
2498                         .collect::<BTreeMap<_, _>>();
2499                     d.insert(name.to_string(), obj.to_json());
2500                 }
2501             }};
2502             (env - $attr:ident) => {{
2503                 let name = (stringify!($attr)).replace("_", "-");
2504                 if default.$attr != target.$attr {
2505                     let obj = target
2506                         .$attr
2507                         .iter()
2508                         .map(|&(ref k, ref v)| format!("{k}={v}"))
2509                         .collect::<Vec<_>>();
2510                     d.insert(name, obj.to_json());
2511                 }
2512             }};
2513         }
2514
2515         target_val!(llvm_target);
2516         d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2517         target_val!(arch);
2518         target_val!(data_layout);
2519
2520         target_option_val!(is_builtin);
2521         target_option_val!(endian, "target-endian");
2522         target_option_val!(c_int_width, "target-c-int-width");
2523         target_option_val!(os);
2524         target_option_val!(env);
2525         target_option_val!(abi);
2526         target_option_val!(vendor);
2527         target_option_val!(linker);
2528         target_option_val!(linker_flavor_json, "linker-flavor");
2529         target_option_val!(lld_flavor);
2530         target_option_val!(linker_is_gnu);
2531         target_option_val!(pre_link_objects);
2532         target_option_val!(post_link_objects);
2533         target_option_val!(pre_link_objects_self_contained, "pre-link-objects-fallback");
2534         target_option_val!(post_link_objects_self_contained, "post-link-objects-fallback");
2535         target_option_val!(link_self_contained, "crt-objects-fallback");
2536         target_option_val!(link_args - pre_link_args_json, "pre-link-args");
2537         target_option_val!(link_args - late_link_args_json, "late-link-args");
2538         target_option_val!(link_args - late_link_args_dynamic_json, "late-link-args-dynamic");
2539         target_option_val!(link_args - late_link_args_static_json, "late-link-args-static");
2540         target_option_val!(link_args - post_link_args_json, "post-link-args");
2541         target_option_val!(link_script);
2542         target_option_val!(env - link_env);
2543         target_option_val!(link_env_remove);
2544         target_option_val!(asm_args);
2545         target_option_val!(cpu);
2546         target_option_val!(features);
2547         target_option_val!(dynamic_linking);
2548         target_option_val!(only_cdylib);
2549         target_option_val!(executables);
2550         target_option_val!(relocation_model);
2551         target_option_val!(code_model);
2552         target_option_val!(tls_model);
2553         target_option_val!(disable_redzone);
2554         target_option_val!(frame_pointer);
2555         target_option_val!(function_sections);
2556         target_option_val!(dll_prefix);
2557         target_option_val!(dll_suffix);
2558         target_option_val!(exe_suffix);
2559         target_option_val!(staticlib_prefix);
2560         target_option_val!(staticlib_suffix);
2561         target_option_val!(families, "target-family");
2562         target_option_val!(abi_return_struct_as_int);
2563         target_option_val!(is_like_osx);
2564         target_option_val!(is_like_solaris);
2565         target_option_val!(is_like_windows);
2566         target_option_val!(is_like_msvc);
2567         target_option_val!(is_like_wasm);
2568         target_option_val!(default_dwarf_version);
2569         target_option_val!(allows_weak_linkage);
2570         target_option_val!(has_rpath);
2571         target_option_val!(no_default_libraries);
2572         target_option_val!(position_independent_executables);
2573         target_option_val!(static_position_independent_executables);
2574         target_option_val!(needs_plt);
2575         target_option_val!(relro_level);
2576         target_option_val!(archive_format);
2577         target_option_val!(allow_asm);
2578         target_option_val!(main_needs_argc_argv);
2579         target_option_val!(has_thread_local);
2580         target_option_val!(obj_is_bitcode);
2581         target_option_val!(forces_embed_bitcode);
2582         target_option_val!(bitcode_llvm_cmdline);
2583         target_option_val!(min_atomic_width);
2584         target_option_val!(max_atomic_width);
2585         target_option_val!(atomic_cas);
2586         target_option_val!(panic_strategy);
2587         target_option_val!(crt_static_allows_dylibs);
2588         target_option_val!(crt_static_default);
2589         target_option_val!(crt_static_respected);
2590         target_option_val!(stack_probes);
2591         target_option_val!(min_global_align);
2592         target_option_val!(default_codegen_units);
2593         target_option_val!(trap_unreachable);
2594         target_option_val!(requires_lto);
2595         target_option_val!(singlethread);
2596         target_option_val!(no_builtins);
2597         target_option_val!(default_hidden_visibility);
2598         target_option_val!(emit_debug_gdb_scripts);
2599         target_option_val!(requires_uwtable);
2600         target_option_val!(default_uwtable);
2601         target_option_val!(simd_types_indirect);
2602         target_option_val!(limit_rdylib_exports);
2603         target_option_val!(override_export_symbols);
2604         target_option_val!(merge_functions);
2605         target_option_val!(mcount, "target-mcount");
2606         target_option_val!(llvm_abiname);
2607         target_option_val!(relax_elf_relocations);
2608         target_option_val!(llvm_args);
2609         target_option_val!(use_ctors_section);
2610         target_option_val!(eh_frame_header);
2611         target_option_val!(has_thumb_interworking);
2612         target_option_val!(debuginfo_kind);
2613         target_option_val!(split_debuginfo);
2614         target_option_val!(supported_split_debuginfo);
2615         target_option_val!(supported_sanitizers);
2616         target_option_val!(c_enum_min_bits);
2617         target_option_val!(generate_arange_section);
2618         target_option_val!(supports_stack_protector);
2619
2620         if let Some(abi) = self.default_adjusted_cabi {
2621             d.insert("default-adjusted-cabi".into(), Abi::name(abi).to_json());
2622         }
2623
2624         Json::Object(d)
2625     }
2626 }
2627
2628 /// Either a target triple string or a path to a JSON file.
2629 #[derive(Clone, Debug)]
2630 pub enum TargetTriple {
2631     TargetTriple(String),
2632     TargetJson {
2633         /// Warning: This field may only be used by rustdoc. Using it anywhere else will lead to
2634         /// inconsistencies as it is discarded during serialization.
2635         path_for_rustdoc: PathBuf,
2636         triple: String,
2637         contents: String,
2638     },
2639 }
2640
2641 // Use a manual implementation to ignore the path field
2642 impl PartialEq for TargetTriple {
2643     fn eq(&self, other: &Self) -> bool {
2644         match (self, other) {
2645             (Self::TargetTriple(l0), Self::TargetTriple(r0)) => l0 == r0,
2646             (
2647                 Self::TargetJson { path_for_rustdoc: _, triple: l_triple, contents: l_contents },
2648                 Self::TargetJson { path_for_rustdoc: _, triple: r_triple, contents: r_contents },
2649             ) => l_triple == r_triple && l_contents == r_contents,
2650             _ => false,
2651         }
2652     }
2653 }
2654
2655 // Use a manual implementation to ignore the path field
2656 impl Hash for TargetTriple {
2657     fn hash<H: Hasher>(&self, state: &mut H) -> () {
2658         match self {
2659             TargetTriple::TargetTriple(triple) => {
2660                 0u8.hash(state);
2661                 triple.hash(state)
2662             }
2663             TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => {
2664                 1u8.hash(state);
2665                 triple.hash(state);
2666                 contents.hash(state)
2667             }
2668         }
2669     }
2670 }
2671
2672 // Use a manual implementation to prevent encoding the target json file path in the crate metadata
2673 impl<S: Encoder> Encodable<S> for TargetTriple {
2674     fn encode(&self, s: &mut S) {
2675         match self {
2676             TargetTriple::TargetTriple(triple) => s.emit_enum_variant(0, |s| s.emit_str(triple)),
2677             TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents } => s
2678                 .emit_enum_variant(1, |s| {
2679                     s.emit_str(triple);
2680                     s.emit_str(contents)
2681                 }),
2682         }
2683     }
2684 }
2685
2686 impl<D: Decoder> Decodable<D> for TargetTriple {
2687     fn decode(d: &mut D) -> Self {
2688         match d.read_usize() {
2689             0 => TargetTriple::TargetTriple(d.read_str().to_owned()),
2690             1 => TargetTriple::TargetJson {
2691                 path_for_rustdoc: PathBuf::new(),
2692                 triple: d.read_str().to_owned(),
2693                 contents: d.read_str().to_owned(),
2694             },
2695             _ => {
2696                 panic!("invalid enum variant tag while decoding `TargetTriple`, expected 0..2");
2697             }
2698         }
2699     }
2700 }
2701
2702 impl TargetTriple {
2703     /// Creates a target triple from the passed target triple string.
2704     pub fn from_triple(triple: &str) -> Self {
2705         TargetTriple::TargetTriple(triple.into())
2706     }
2707
2708     /// Creates a target triple from the passed target path.
2709     pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2710         let canonicalized_path = path.canonicalize()?;
2711         let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| {
2712             io::Error::new(
2713                 io::ErrorKind::InvalidInput,
2714                 format!("target path {:?} is not a valid file: {}", canonicalized_path, err),
2715             )
2716         })?;
2717         let triple = canonicalized_path
2718             .file_stem()
2719             .expect("target path must not be empty")
2720             .to_str()
2721             .expect("target path must be valid unicode")
2722             .to_owned();
2723         Ok(TargetTriple::TargetJson { path_for_rustdoc: canonicalized_path, triple, contents })
2724     }
2725
2726     /// Returns a string triple for this target.
2727     ///
2728     /// If this target is a path, the file name (without extension) is returned.
2729     pub fn triple(&self) -> &str {
2730         match *self {
2731             TargetTriple::TargetTriple(ref triple)
2732             | TargetTriple::TargetJson { ref triple, .. } => triple,
2733         }
2734     }
2735
2736     /// Returns an extended string triple for this target.
2737     ///
2738     /// If this target is a path, a hash of the path is appended to the triple returned
2739     /// by `triple()`.
2740     pub fn debug_triple(&self) -> String {
2741         use std::collections::hash_map::DefaultHasher;
2742
2743         match self {
2744             TargetTriple::TargetTriple(triple) => triple.to_owned(),
2745             TargetTriple::TargetJson { path_for_rustdoc: _, triple, contents: content } => {
2746                 let mut hasher = DefaultHasher::new();
2747                 content.hash(&mut hasher);
2748                 let hash = hasher.finish();
2749                 format!("{}-{}", triple, hash)
2750             }
2751         }
2752     }
2753 }
2754
2755 impl fmt::Display for TargetTriple {
2756     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2757         write!(f, "{}", self.debug_triple())
2758     }
2759 }