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