]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_target/src/spec/mod.rs
Auto merge of #79608 - alessandrod:bpf, r=nagisa
[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](http://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::spec::abi::{lookup as lookup_abi, Abi};
39 use crate::spec::crt_objects::{CrtObjects, CrtObjectsFallback};
40 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
41 use rustc_serialize::json::{Json, ToJson};
42 use rustc_span::symbol::{sym, Symbol};
43 use std::collections::BTreeMap;
44 use std::convert::TryFrom;
45 use std::ops::{Deref, DerefMut};
46 use std::path::{Path, PathBuf};
47 use std::str::FromStr;
48 use std::{fmt, io};
49
50 use rustc_macros::HashStable_Generic;
51
52 pub mod abi;
53 pub mod crt_objects;
54
55 mod android_base;
56 mod apple_base;
57 mod apple_sdk_base;
58 mod arm_base;
59 mod avr_gnu_base;
60 mod bpf_base;
61 mod dragonfly_base;
62 mod freebsd_base;
63 mod fuchsia_base;
64 mod haiku_base;
65 mod hermit_base;
66 mod hermit_kernel_base;
67 mod illumos_base;
68 mod l4re_base;
69 mod linux_base;
70 mod linux_gnu_base;
71 mod linux_kernel_base;
72 mod linux_musl_base;
73 mod linux_uclibc_base;
74 mod msvc_base;
75 mod netbsd_base;
76 mod openbsd_base;
77 mod redox_base;
78 mod riscv_base;
79 mod solaris_base;
80 mod thumb_base;
81 mod uefi_msvc_base;
82 mod vxworks_base;
83 mod wasm_base;
84 mod windows_gnu_base;
85 mod windows_msvc_base;
86 mod windows_uwp_gnu_base;
87 mod windows_uwp_msvc_base;
88
89 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
90 pub enum LinkerFlavor {
91     Em,
92     Gcc,
93     Ld,
94     Msvc,
95     Lld(LldFlavor),
96     PtxLinker,
97     BpfLinker,
98 }
99
100 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
101 pub enum LldFlavor {
102     Wasm,
103     Ld64,
104     Ld,
105     Link,
106 }
107
108 impl LldFlavor {
109     fn from_str(s: &str) -> Option<Self> {
110         Some(match s {
111             "darwin" => LldFlavor::Ld64,
112             "gnu" => LldFlavor::Ld,
113             "link" => LldFlavor::Link,
114             "wasm" => LldFlavor::Wasm,
115             _ => return None,
116         })
117     }
118 }
119
120 impl ToJson for LldFlavor {
121     fn to_json(&self) -> Json {
122         match *self {
123             LldFlavor::Ld64 => "darwin",
124             LldFlavor::Ld => "gnu",
125             LldFlavor::Link => "link",
126             LldFlavor::Wasm => "wasm",
127         }
128         .to_json()
129     }
130 }
131
132 impl ToJson for LinkerFlavor {
133     fn to_json(&self) -> Json {
134         self.desc().to_json()
135     }
136 }
137 macro_rules! flavor_mappings {
138     ($((($($flavor:tt)*), $string:expr),)*) => (
139         impl LinkerFlavor {
140             pub const fn one_of() -> &'static str {
141                 concat!("one of: ", $($string, " ",)*)
142             }
143
144             pub fn from_str(s: &str) -> Option<Self> {
145                 Some(match s {
146                     $($string => $($flavor)*,)*
147                     _ => return None,
148                 })
149             }
150
151             pub fn desc(&self) -> &str {
152                 match *self {
153                     $($($flavor)* => $string,)*
154                 }
155             }
156         }
157     )
158 }
159
160 flavor_mappings! {
161     ((LinkerFlavor::Em), "em"),
162     ((LinkerFlavor::Gcc), "gcc"),
163     ((LinkerFlavor::Ld), "ld"),
164     ((LinkerFlavor::Msvc), "msvc"),
165     ((LinkerFlavor::PtxLinker), "ptx-linker"),
166     ((LinkerFlavor::BpfLinker), "bpf-linker"),
167     ((LinkerFlavor::Lld(LldFlavor::Wasm)), "wasm-ld"),
168     ((LinkerFlavor::Lld(LldFlavor::Ld64)), "ld64.lld"),
169     ((LinkerFlavor::Lld(LldFlavor::Ld)), "ld.lld"),
170     ((LinkerFlavor::Lld(LldFlavor::Link)), "lld-link"),
171 }
172
173 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
174 pub enum PanicStrategy {
175     Unwind,
176     Abort,
177 }
178
179 impl PanicStrategy {
180     pub fn desc(&self) -> &str {
181         match *self {
182             PanicStrategy::Unwind => "unwind",
183             PanicStrategy::Abort => "abort",
184         }
185     }
186
187     pub fn desc_symbol(&self) -> Symbol {
188         match *self {
189             PanicStrategy::Unwind => sym::unwind,
190             PanicStrategy::Abort => sym::abort,
191         }
192     }
193 }
194
195 impl ToJson for PanicStrategy {
196     fn to_json(&self) -> Json {
197         match *self {
198             PanicStrategy::Abort => "abort".to_json(),
199             PanicStrategy::Unwind => "unwind".to_json(),
200         }
201     }
202 }
203
204 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
205 pub enum RelroLevel {
206     Full,
207     Partial,
208     Off,
209     None,
210 }
211
212 impl RelroLevel {
213     pub fn desc(&self) -> &str {
214         match *self {
215             RelroLevel::Full => "full",
216             RelroLevel::Partial => "partial",
217             RelroLevel::Off => "off",
218             RelroLevel::None => "none",
219         }
220     }
221 }
222
223 impl FromStr for RelroLevel {
224     type Err = ();
225
226     fn from_str(s: &str) -> Result<RelroLevel, ()> {
227         match s {
228             "full" => Ok(RelroLevel::Full),
229             "partial" => Ok(RelroLevel::Partial),
230             "off" => Ok(RelroLevel::Off),
231             "none" => Ok(RelroLevel::None),
232             _ => Err(()),
233         }
234     }
235 }
236
237 impl ToJson for RelroLevel {
238     fn to_json(&self) -> Json {
239         match *self {
240             RelroLevel::Full => "full".to_json(),
241             RelroLevel::Partial => "partial".to_json(),
242             RelroLevel::Off => "off".to_json(),
243             RelroLevel::None => "None".to_json(),
244         }
245     }
246 }
247
248 #[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable)]
249 pub enum MergeFunctions {
250     Disabled,
251     Trampolines,
252     Aliases,
253 }
254
255 impl MergeFunctions {
256     pub fn desc(&self) -> &str {
257         match *self {
258             MergeFunctions::Disabled => "disabled",
259             MergeFunctions::Trampolines => "trampolines",
260             MergeFunctions::Aliases => "aliases",
261         }
262     }
263 }
264
265 impl FromStr for MergeFunctions {
266     type Err = ();
267
268     fn from_str(s: &str) -> Result<MergeFunctions, ()> {
269         match s {
270             "disabled" => Ok(MergeFunctions::Disabled),
271             "trampolines" => Ok(MergeFunctions::Trampolines),
272             "aliases" => Ok(MergeFunctions::Aliases),
273             _ => Err(()),
274         }
275     }
276 }
277
278 impl ToJson for MergeFunctions {
279     fn to_json(&self) -> Json {
280         match *self {
281             MergeFunctions::Disabled => "disabled".to_json(),
282             MergeFunctions::Trampolines => "trampolines".to_json(),
283             MergeFunctions::Aliases => "aliases".to_json(),
284         }
285     }
286 }
287
288 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
289 pub enum RelocModel {
290     Static,
291     Pic,
292     DynamicNoPic,
293     Ropi,
294     Rwpi,
295     RopiRwpi,
296 }
297
298 impl FromStr for RelocModel {
299     type Err = ();
300
301     fn from_str(s: &str) -> Result<RelocModel, ()> {
302         Ok(match s {
303             "static" => RelocModel::Static,
304             "pic" => RelocModel::Pic,
305             "dynamic-no-pic" => RelocModel::DynamicNoPic,
306             "ropi" => RelocModel::Ropi,
307             "rwpi" => RelocModel::Rwpi,
308             "ropi-rwpi" => RelocModel::RopiRwpi,
309             _ => return Err(()),
310         })
311     }
312 }
313
314 impl ToJson for RelocModel {
315     fn to_json(&self) -> Json {
316         match *self {
317             RelocModel::Static => "static",
318             RelocModel::Pic => "pic",
319             RelocModel::DynamicNoPic => "dynamic-no-pic",
320             RelocModel::Ropi => "ropi",
321             RelocModel::Rwpi => "rwpi",
322             RelocModel::RopiRwpi => "ropi-rwpi",
323         }
324         .to_json()
325     }
326 }
327
328 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
329 pub enum CodeModel {
330     Tiny,
331     Small,
332     Kernel,
333     Medium,
334     Large,
335 }
336
337 impl FromStr for CodeModel {
338     type Err = ();
339
340     fn from_str(s: &str) -> Result<CodeModel, ()> {
341         Ok(match s {
342             "tiny" => CodeModel::Tiny,
343             "small" => CodeModel::Small,
344             "kernel" => CodeModel::Kernel,
345             "medium" => CodeModel::Medium,
346             "large" => CodeModel::Large,
347             _ => return Err(()),
348         })
349     }
350 }
351
352 impl ToJson for CodeModel {
353     fn to_json(&self) -> Json {
354         match *self {
355             CodeModel::Tiny => "tiny",
356             CodeModel::Small => "small",
357             CodeModel::Kernel => "kernel",
358             CodeModel::Medium => "medium",
359             CodeModel::Large => "large",
360         }
361         .to_json()
362     }
363 }
364
365 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
366 pub enum TlsModel {
367     GeneralDynamic,
368     LocalDynamic,
369     InitialExec,
370     LocalExec,
371 }
372
373 impl FromStr for TlsModel {
374     type Err = ();
375
376     fn from_str(s: &str) -> Result<TlsModel, ()> {
377         Ok(match s {
378             // Note the difference "general" vs "global" difference. The model name is "general",
379             // but the user-facing option name is "global" for consistency with other compilers.
380             "global-dynamic" => TlsModel::GeneralDynamic,
381             "local-dynamic" => TlsModel::LocalDynamic,
382             "initial-exec" => TlsModel::InitialExec,
383             "local-exec" => TlsModel::LocalExec,
384             _ => return Err(()),
385         })
386     }
387 }
388
389 impl ToJson for TlsModel {
390     fn to_json(&self) -> Json {
391         match *self {
392             TlsModel::GeneralDynamic => "global-dynamic",
393             TlsModel::LocalDynamic => "local-dynamic",
394             TlsModel::InitialExec => "initial-exec",
395             TlsModel::LocalExec => "local-exec",
396         }
397         .to_json()
398     }
399 }
400
401 /// Everything is flattened to a single enum to make the json encoding/decoding less annoying.
402 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
403 pub enum LinkOutputKind {
404     /// Dynamically linked non position-independent executable.
405     DynamicNoPicExe,
406     /// Dynamically linked position-independent executable.
407     DynamicPicExe,
408     /// Statically linked non position-independent executable.
409     StaticNoPicExe,
410     /// Statically linked position-independent executable.
411     StaticPicExe,
412     /// Regular dynamic library ("dynamically linked").
413     DynamicDylib,
414     /// Dynamic library with bundled libc ("statically linked").
415     StaticDylib,
416     /// WASI module with a lifetime past the _initialize entry point
417     WasiReactorExe,
418 }
419
420 impl LinkOutputKind {
421     fn as_str(&self) -> &'static str {
422         match self {
423             LinkOutputKind::DynamicNoPicExe => "dynamic-nopic-exe",
424             LinkOutputKind::DynamicPicExe => "dynamic-pic-exe",
425             LinkOutputKind::StaticNoPicExe => "static-nopic-exe",
426             LinkOutputKind::StaticPicExe => "static-pic-exe",
427             LinkOutputKind::DynamicDylib => "dynamic-dylib",
428             LinkOutputKind::StaticDylib => "static-dylib",
429             LinkOutputKind::WasiReactorExe => "wasi-reactor-exe",
430         }
431     }
432
433     pub(super) fn from_str(s: &str) -> Option<LinkOutputKind> {
434         Some(match s {
435             "dynamic-nopic-exe" => LinkOutputKind::DynamicNoPicExe,
436             "dynamic-pic-exe" => LinkOutputKind::DynamicPicExe,
437             "static-nopic-exe" => LinkOutputKind::StaticNoPicExe,
438             "static-pic-exe" => LinkOutputKind::StaticPicExe,
439             "dynamic-dylib" => LinkOutputKind::DynamicDylib,
440             "static-dylib" => LinkOutputKind::StaticDylib,
441             "wasi-reactor-exe" => LinkOutputKind::WasiReactorExe,
442             _ => return None,
443         })
444     }
445 }
446
447 impl fmt::Display for LinkOutputKind {
448     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449         f.write_str(self.as_str())
450     }
451 }
452
453 pub type LinkArgs = BTreeMap<LinkerFlavor, Vec<String>>;
454
455 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
456 pub enum SplitDebuginfo {
457     /// Split debug-information is disabled, meaning that on supported platforms
458     /// you can find all debug information in the executable itself. This is
459     /// only supported for ELF effectively.
460     ///
461     /// * Windows - not supported
462     /// * macOS - don't run `dsymutil`
463     /// * ELF - `.dwarf_*` sections
464     Off,
465
466     /// Split debug-information can be found in a "packed" location separate
467     /// from the final artifact. This is supported on all platforms.
468     ///
469     /// * Windows - `*.pdb`
470     /// * macOS - `*.dSYM` (run `dsymutil`)
471     /// * ELF - `*.dwp` (run `rust-llvm-dwp`)
472     Packed,
473
474     /// Split debug-information can be found in individual object files on the
475     /// filesystem. The main executable may point to the object files.
476     ///
477     /// * Windows - not supported
478     /// * macOS - supported, scattered object files
479     /// * ELF - supported, scattered `*.dwo` files
480     Unpacked,
481 }
482
483 impl SplitDebuginfo {
484     fn as_str(&self) -> &'static str {
485         match self {
486             SplitDebuginfo::Off => "off",
487             SplitDebuginfo::Packed => "packed",
488             SplitDebuginfo::Unpacked => "unpacked",
489         }
490     }
491 }
492
493 impl FromStr for SplitDebuginfo {
494     type Err = ();
495
496     fn from_str(s: &str) -> Result<SplitDebuginfo, ()> {
497         Ok(match s {
498             "off" => SplitDebuginfo::Off,
499             "unpacked" => SplitDebuginfo::Unpacked,
500             "packed" => SplitDebuginfo::Packed,
501             _ => return Err(()),
502         })
503     }
504 }
505
506 impl ToJson for SplitDebuginfo {
507     fn to_json(&self) -> Json {
508         self.as_str().to_json()
509     }
510 }
511
512 impl fmt::Display for SplitDebuginfo {
513     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514         f.write_str(self.as_str())
515     }
516 }
517
518 #[derive(Clone, Debug, PartialEq, Eq)]
519 pub enum StackProbeType {
520     /// Don't emit any stack probes.
521     None,
522     /// It is harmless to use this option even on targets that do not have backend support for
523     /// stack probes as the failure mode is the same as if no stack-probe option was specified in
524     /// the first place.
525     Inline,
526     /// Call `__rust_probestack` whenever stack needs to be probed.
527     Call,
528     /// Use inline option for LLVM versions later than specified in `min_llvm_version_for_inline`
529     /// and call `__rust_probestack` otherwise.
530     InlineOrCall { min_llvm_version_for_inline: (u32, u32, u32) },
531 }
532
533 impl StackProbeType {
534     fn from_json(json: &Json) -> Result<Self, String> {
535         let object = json.as_object().ok_or_else(|| "expected a JSON object")?;
536         let kind = object
537             .get("kind")
538             .and_then(|o| o.as_string())
539             .ok_or_else(|| "expected `kind` to be a string")?;
540         match kind {
541             "none" => Ok(StackProbeType::None),
542             "inline" => Ok(StackProbeType::Inline),
543             "call" => Ok(StackProbeType::Call),
544             "inline-or-call" => {
545                 let min_version = object
546                     .get("min-llvm-version-for-inline")
547                     .and_then(|o| o.as_array())
548                     .ok_or_else(|| "expected `min-llvm-version-for-inline` to be an array")?;
549                 let mut iter = min_version.into_iter().map(|v| {
550                     let int = v.as_u64().ok_or_else(
551                         || "expected `min-llvm-version-for-inline` values to be integers",
552                     )?;
553                     u32::try_from(int)
554                         .map_err(|_| "`min-llvm-version-for-inline` values don't convert to u32")
555                 });
556                 let min_llvm_version_for_inline = (
557                     iter.next().unwrap_or(Ok(11))?,
558                     iter.next().unwrap_or(Ok(0))?,
559                     iter.next().unwrap_or(Ok(0))?,
560                 );
561                 Ok(StackProbeType::InlineOrCall { min_llvm_version_for_inline })
562             }
563             _ => Err(String::from(
564                 "`kind` expected to be one of `none`, `inline`, `call` or `inline-or-call`",
565             )),
566         }
567     }
568 }
569
570 impl ToJson for StackProbeType {
571     fn to_json(&self) -> Json {
572         Json::Object(match self {
573             StackProbeType::None => {
574                 vec![(String::from("kind"), "none".to_json())].into_iter().collect()
575             }
576             StackProbeType::Inline => {
577                 vec![(String::from("kind"), "inline".to_json())].into_iter().collect()
578             }
579             StackProbeType::Call => {
580                 vec![(String::from("kind"), "call".to_json())].into_iter().collect()
581             }
582             StackProbeType::InlineOrCall { min_llvm_version_for_inline } => vec![
583                 (String::from("kind"), "inline-or-call".to_json()),
584                 (
585                     String::from("min-llvm-version-for-inline"),
586                     min_llvm_version_for_inline.to_json(),
587                 ),
588             ]
589             .into_iter()
590             .collect(),
591         })
592     }
593 }
594
595 bitflags::bitflags! {
596     #[derive(Default, Encodable, Decodable)]
597     pub struct SanitizerSet: u8 {
598         const ADDRESS = 1 << 0;
599         const LEAK    = 1 << 1;
600         const MEMORY  = 1 << 2;
601         const THREAD  = 1 << 3;
602         const HWADDRESS = 1 << 4;
603     }
604 }
605
606 impl SanitizerSet {
607     /// Return sanitizer's name
608     ///
609     /// Returns none if the flags is a set of sanitizers numbering not exactly one.
610     fn as_str(self) -> Option<&'static str> {
611         Some(match self {
612             SanitizerSet::ADDRESS => "address",
613             SanitizerSet::LEAK => "leak",
614             SanitizerSet::MEMORY => "memory",
615             SanitizerSet::THREAD => "thread",
616             SanitizerSet::HWADDRESS => "hwaddress",
617             _ => return None,
618         })
619     }
620 }
621
622 /// Formats a sanitizer set as a comma separated list of sanitizers' names.
623 impl fmt::Display for SanitizerSet {
624     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625         let mut first = true;
626         for s in *self {
627             let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s));
628             if !first {
629                 f.write_str(", ")?;
630             }
631             f.write_str(name)?;
632             first = false;
633         }
634         Ok(())
635     }
636 }
637
638 impl IntoIterator for SanitizerSet {
639     type Item = SanitizerSet;
640     type IntoIter = std::vec::IntoIter<SanitizerSet>;
641
642     fn into_iter(self) -> Self::IntoIter {
643         [
644             SanitizerSet::ADDRESS,
645             SanitizerSet::LEAK,
646             SanitizerSet::MEMORY,
647             SanitizerSet::THREAD,
648             SanitizerSet::HWADDRESS,
649         ]
650         .iter()
651         .copied()
652         .filter(|&s| self.contains(s))
653         .collect::<Vec<_>>()
654         .into_iter()
655     }
656 }
657
658 impl<CTX> HashStable<CTX> for SanitizerSet {
659     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
660         self.bits().hash_stable(ctx, hasher);
661     }
662 }
663
664 impl ToJson for SanitizerSet {
665     fn to_json(&self) -> Json {
666         self.into_iter()
667             .map(|v| Some(v.as_str()?.to_json()))
668             .collect::<Option<Vec<_>>>()
669             .unwrap_or(Vec::new())
670             .to_json()
671     }
672 }
673
674 macro_rules! supported_targets {
675     ( $(($( $triple:literal, )+ $module:ident ),)+ ) => {
676         $(mod $module;)+
677
678         /// List of supported targets
679         pub const TARGETS: &[&str] = &[$($($triple),+),+];
680
681         fn load_builtin(target: &str) -> Option<Target> {
682             let mut t = match target {
683                 $( $($triple)|+ => $module::target(), )+
684                 _ => return None,
685             };
686             t.is_builtin = true;
687             debug!("got builtin target: {:?}", t);
688             Some(t)
689         }
690
691         #[cfg(test)]
692         mod tests {
693             mod tests_impl;
694
695             // Cannot put this into a separate file without duplication, make an exception.
696             $(
697                 #[test] // `#[test]`
698                 fn $module() {
699                     tests_impl::test_target(super::$module::target());
700                 }
701             )+
702         }
703     };
704 }
705
706 supported_targets! {
707     ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
708     ("x86_64-unknown-linux-gnux32", x86_64_unknown_linux_gnux32),
709     ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
710     ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
711     ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
712     ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
713     ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
714     ("mipsisa32r6-unknown-linux-gnu", mipsisa32r6_unknown_linux_gnu),
715     ("mipsisa32r6el-unknown-linux-gnu", mipsisa32r6el_unknown_linux_gnu),
716     ("mipsisa64r6-unknown-linux-gnuabi64", mipsisa64r6_unknown_linux_gnuabi64),
717     ("mipsisa64r6el-unknown-linux-gnuabi64", mipsisa64r6el_unknown_linux_gnuabi64),
718     ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
719     ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
720     ("powerpc-unknown-linux-gnuspe", powerpc_unknown_linux_gnuspe),
721     ("powerpc-unknown-linux-musl", powerpc_unknown_linux_musl),
722     ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
723     ("powerpc64-unknown-linux-musl", powerpc64_unknown_linux_musl),
724     ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
725     ("powerpc64le-unknown-linux-musl", powerpc64le_unknown_linux_musl),
726     ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
727     ("s390x-unknown-linux-musl", s390x_unknown_linux_musl),
728     ("sparc-unknown-linux-gnu", sparc_unknown_linux_gnu),
729     ("sparc64-unknown-linux-gnu", sparc64_unknown_linux_gnu),
730     ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
731     ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
732     ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
733     ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
734     ("armv4t-unknown-linux-gnueabi", armv4t_unknown_linux_gnueabi),
735     ("armv5te-unknown-linux-gnueabi", armv5te_unknown_linux_gnueabi),
736     ("armv5te-unknown-linux-musleabi", armv5te_unknown_linux_musleabi),
737     ("armv5te-unknown-linux-uclibceabi", armv5te_unknown_linux_uclibceabi),
738     ("armv7-unknown-linux-gnueabi", armv7_unknown_linux_gnueabi),
739     ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
740     ("thumbv7neon-unknown-linux-gnueabihf", thumbv7neon_unknown_linux_gnueabihf),
741     ("thumbv7neon-unknown-linux-musleabihf", thumbv7neon_unknown_linux_musleabihf),
742     ("armv7-unknown-linux-musleabi", armv7_unknown_linux_musleabi),
743     ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
744     ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
745     ("aarch64-unknown-linux-musl", aarch64_unknown_linux_musl),
746     ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
747     ("i686-unknown-linux-musl", i686_unknown_linux_musl),
748     ("i586-unknown-linux-musl", i586_unknown_linux_musl),
749     ("mips-unknown-linux-musl", mips_unknown_linux_musl),
750     ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
751     ("mips64-unknown-linux-muslabi64", mips64_unknown_linux_muslabi64),
752     ("mips64el-unknown-linux-muslabi64", mips64el_unknown_linux_muslabi64),
753     ("hexagon-unknown-linux-musl", hexagon_unknown_linux_musl),
754
755     ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
756     ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
757
758     ("i686-linux-android", i686_linux_android),
759     ("x86_64-linux-android", x86_64_linux_android),
760     ("arm-linux-androideabi", arm_linux_androideabi),
761     ("armv7-linux-androideabi", armv7_linux_androideabi),
762     ("thumbv7neon-linux-androideabi", thumbv7neon_linux_androideabi),
763     ("aarch64-linux-android", aarch64_linux_android),
764
765     ("x86_64-unknown-none-linuxkernel", x86_64_unknown_none_linuxkernel),
766
767     ("aarch64-unknown-freebsd", aarch64_unknown_freebsd),
768     ("armv6-unknown-freebsd", armv6_unknown_freebsd),
769     ("armv7-unknown-freebsd", armv7_unknown_freebsd),
770     ("i686-unknown-freebsd", i686_unknown_freebsd),
771     ("powerpc64-unknown-freebsd", powerpc64_unknown_freebsd),
772     ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
773
774     ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
775
776     ("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
777     ("i686-unknown-openbsd", i686_unknown_openbsd),
778     ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
779     ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
780     ("powerpc-unknown-openbsd", powerpc_unknown_openbsd),
781
782     ("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
783     ("armv6-unknown-netbsd-eabihf", armv6_unknown_netbsd_eabihf),
784     ("armv7-unknown-netbsd-eabihf", armv7_unknown_netbsd_eabihf),
785     ("i686-unknown-netbsd", i686_unknown_netbsd),
786     ("powerpc-unknown-netbsd", powerpc_unknown_netbsd),
787     ("sparc64-unknown-netbsd", sparc64_unknown_netbsd),
788     ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
789
790     ("i686-unknown-haiku", i686_unknown_haiku),
791     ("x86_64-unknown-haiku", x86_64_unknown_haiku),
792
793     ("aarch64-apple-darwin", aarch64_apple_darwin),
794     ("x86_64-apple-darwin", x86_64_apple_darwin),
795     ("i686-apple-darwin", i686_apple_darwin),
796
797     ("aarch64-fuchsia", aarch64_fuchsia),
798     ("x86_64-fuchsia", x86_64_fuchsia),
799
800     ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328),
801
802     ("x86_64-unknown-l4re-uclibc", x86_64_unknown_l4re_uclibc),
803
804     ("aarch64-unknown-redox", aarch64_unknown_redox),
805     ("x86_64-unknown-redox", x86_64_unknown_redox),
806
807     ("i386-apple-ios", i386_apple_ios),
808     ("x86_64-apple-ios", x86_64_apple_ios),
809     ("aarch64-apple-ios", aarch64_apple_ios),
810     ("armv7-apple-ios", armv7_apple_ios),
811     ("armv7s-apple-ios", armv7s_apple_ios),
812     ("x86_64-apple-ios-macabi", x86_64_apple_ios_macabi),
813     ("aarch64-apple-ios-macabi", aarch64_apple_ios_macabi),
814     ("aarch64-apple-ios-sim", aarch64_apple_ios_sim),
815     ("aarch64-apple-tvos", aarch64_apple_tvos),
816     ("x86_64-apple-tvos", x86_64_apple_tvos),
817
818     ("armebv7r-none-eabi", armebv7r_none_eabi),
819     ("armebv7r-none-eabihf", armebv7r_none_eabihf),
820     ("armv7r-none-eabi", armv7r_none_eabi),
821     ("armv7r-none-eabihf", armv7r_none_eabihf),
822
823     ("x86_64-pc-solaris", x86_64_pc_solaris),
824     ("x86_64-sun-solaris", x86_64_sun_solaris),
825     ("sparcv9-sun-solaris", sparcv9_sun_solaris),
826
827     ("x86_64-unknown-illumos", x86_64_unknown_illumos),
828
829     ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
830     ("i686-pc-windows-gnu", i686_pc_windows_gnu),
831     ("i686-uwp-windows-gnu", i686_uwp_windows_gnu),
832     ("x86_64-uwp-windows-gnu", x86_64_uwp_windows_gnu),
833
834     ("aarch64-pc-windows-msvc", aarch64_pc_windows_msvc),
835     ("aarch64-uwp-windows-msvc", aarch64_uwp_windows_msvc),
836     ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
837     ("x86_64-uwp-windows-msvc", x86_64_uwp_windows_msvc),
838     ("i686-pc-windows-msvc", i686_pc_windows_msvc),
839     ("i686-uwp-windows-msvc", i686_uwp_windows_msvc),
840     ("i586-pc-windows-msvc", i586_pc_windows_msvc),
841     ("thumbv7a-pc-windows-msvc", thumbv7a_pc_windows_msvc),
842     ("thumbv7a-uwp-windows-msvc", thumbv7a_uwp_windows_msvc),
843
844     ("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
845     ("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
846     ("wasm32-unknown-unknown", wasm32_unknown_unknown),
847     ("wasm32-wasi", wasm32_wasi),
848     ("wasm64-unknown-unknown", wasm64_unknown_unknown),
849
850     ("thumbv6m-none-eabi", thumbv6m_none_eabi),
851     ("thumbv7m-none-eabi", thumbv7m_none_eabi),
852     ("thumbv7em-none-eabi", thumbv7em_none_eabi),
853     ("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
854     ("thumbv8m.base-none-eabi", thumbv8m_base_none_eabi),
855     ("thumbv8m.main-none-eabi", thumbv8m_main_none_eabi),
856     ("thumbv8m.main-none-eabihf", thumbv8m_main_none_eabihf),
857
858     ("armv7a-none-eabi", armv7a_none_eabi),
859     ("armv7a-none-eabihf", armv7a_none_eabihf),
860
861     ("msp430-none-elf", msp430_none_elf),
862
863     ("aarch64-unknown-hermit", aarch64_unknown_hermit),
864     ("x86_64-unknown-hermit", x86_64_unknown_hermit),
865
866     ("x86_64-unknown-none-hermitkernel", x86_64_unknown_none_hermitkernel),
867
868     ("riscv32i-unknown-none-elf", riscv32i_unknown_none_elf),
869     ("riscv32imc-unknown-none-elf", riscv32imc_unknown_none_elf),
870     ("riscv32imac-unknown-none-elf", riscv32imac_unknown_none_elf),
871     ("riscv32gc-unknown-linux-gnu", riscv32gc_unknown_linux_gnu),
872     ("riscv32gc-unknown-linux-musl", riscv32gc_unknown_linux_musl),
873     ("riscv64imac-unknown-none-elf", riscv64imac_unknown_none_elf),
874     ("riscv64gc-unknown-none-elf", riscv64gc_unknown_none_elf),
875     ("riscv64gc-unknown-linux-gnu", riscv64gc_unknown_linux_gnu),
876     ("riscv64gc-unknown-linux-musl", riscv64gc_unknown_linux_musl),
877
878     ("aarch64-unknown-none", aarch64_unknown_none),
879     ("aarch64-unknown-none-softfloat", aarch64_unknown_none_softfloat),
880
881     ("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
882
883     ("x86_64-unknown-uefi", x86_64_unknown_uefi),
884     ("i686-unknown-uefi", i686_unknown_uefi),
885
886     ("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
887
888     ("i686-wrs-vxworks", i686_wrs_vxworks),
889     ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
890     ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
891     ("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
892     ("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
893     ("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
894     ("powerpc64-wrs-vxworks", powerpc64_wrs_vxworks),
895
896     ("mipsel-sony-psp", mipsel_sony_psp),
897     ("mipsel-unknown-none", mipsel_unknown_none),
898     ("thumbv4t-none-eabi", thumbv4t_none_eabi),
899
900     ("aarch64_be-unknown-linux-gnu", aarch64_be_unknown_linux_gnu),
901     ("aarch64-unknown-linux-gnu_ilp32", aarch64_unknown_linux_gnu_ilp32),
902     ("aarch64_be-unknown-linux-gnu_ilp32", aarch64_be_unknown_linux_gnu_ilp32),
903
904     ("bpfeb-unknown-none", bpfeb_unknown_none),
905     ("bpfel-unknown-none", bpfel_unknown_none),
906 }
907
908 /// Everything `rustc` knows about how to compile for a specific target.
909 ///
910 /// Every field here must be specified, and has no default value.
911 #[derive(PartialEq, Clone, Debug)]
912 pub struct Target {
913     /// Target triple to pass to LLVM.
914     pub llvm_target: String,
915     /// Number of bits in a pointer. Influences the `target_pointer_width` `cfg` variable.
916     pub pointer_width: u32,
917     /// Architecture to use for ABI considerations. Valid options include: "x86",
918     /// "x86_64", "arm", "aarch64", "mips", "powerpc", "powerpc64", and others.
919     pub arch: String,
920     /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
921     pub data_layout: String,
922     /// Optional settings with defaults.
923     pub options: TargetOptions,
924 }
925
926 pub trait HasTargetSpec {
927     fn target_spec(&self) -> &Target;
928 }
929
930 impl HasTargetSpec for Target {
931     #[inline]
932     fn target_spec(&self) -> &Target {
933         self
934     }
935 }
936
937 /// Optional aspects of a target specification.
938 ///
939 /// This has an implementation of `Default`, see each field for what the default is. In general,
940 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
941 ///
942 /// `TargetOptions` as a separate structure is mostly an implementation detail of `Target`
943 /// construction, all its fields logically belong to `Target` and available from `Target`
944 /// through `Deref` impls.
945 #[derive(PartialEq, Clone, Debug)]
946 pub struct TargetOptions {
947     /// Whether the target is built-in or loaded from a custom target specification.
948     pub is_builtin: bool,
949
950     /// Used as the `target_endian` `cfg` variable. Defaults to little endian.
951     pub endian: Endian,
952     /// Width of c_int type. Defaults to "32".
953     pub c_int_width: String,
954     /// OS name to use for conditional compilation (`target_os`). Defaults to "none".
955     /// "none" implies a bare metal target without `std` library.
956     /// A couple of targets having `std` also use "unknown" as an `os` value,
957     /// but they are exceptions.
958     pub os: String,
959     /// Environment name to use for conditional compilation (`target_env`). Defaults to "".
960     pub env: String,
961     /// Vendor name to use for conditional compilation (`target_vendor`). Defaults to "unknown".
962     pub vendor: String,
963     /// Default linker flavor used if `-C linker-flavor` or `-C linker` are not passed
964     /// on the command line. Defaults to `LinkerFlavor::Gcc`.
965     pub linker_flavor: LinkerFlavor,
966
967     /// Linker to invoke
968     pub linker: Option<String>,
969
970     /// LLD flavor used if `lld` (or `rust-lld`) is specified as a linker
971     /// without clarifying its flavor in any way.
972     pub lld_flavor: LldFlavor,
973
974     /// Linker arguments that are passed *before* any user-defined libraries.
975     pub pre_link_args: LinkArgs,
976     /// Objects to link before and after all other object code.
977     pub pre_link_objects: CrtObjects,
978     pub post_link_objects: CrtObjects,
979     /// Same as `(pre|post)_link_objects`, but when we fail to pull the objects with help of the
980     /// target's native gcc and fall back to the "self-contained" mode and pull them manually.
981     /// See `crt_objects.rs` for some more detailed documentation.
982     pub pre_link_objects_fallback: CrtObjects,
983     pub post_link_objects_fallback: CrtObjects,
984     /// Which logic to use to determine whether to fall back to the "self-contained" mode or not.
985     pub crt_objects_fallback: Option<CrtObjectsFallback>,
986
987     /// Linker arguments that are unconditionally passed after any
988     /// user-defined but before post-link objects. Standard platform
989     /// libraries that should be always be linked to, usually go here.
990     pub late_link_args: LinkArgs,
991     /// Linker arguments used in addition to `late_link_args` if at least one
992     /// Rust dependency is dynamically linked.
993     pub late_link_args_dynamic: LinkArgs,
994     /// Linker arguments used in addition to `late_link_args` if aall Rust
995     /// dependencies are statically linked.
996     pub late_link_args_static: LinkArgs,
997     /// Linker arguments that are unconditionally passed *after* any
998     /// user-defined libraries.
999     pub post_link_args: LinkArgs,
1000     /// Optional link script applied to `dylib` and `executable` crate types.
1001     /// This is a string containing the script, not a path. Can only be applied
1002     /// to linkers where `linker_is_gnu` is true.
1003     pub link_script: Option<String>,
1004
1005     /// Environment variables to be set for the linker invocation.
1006     pub link_env: Vec<(String, String)>,
1007     /// Environment variables to be removed for the linker invocation.
1008     pub link_env_remove: Vec<String>,
1009
1010     /// Extra arguments to pass to the external assembler (when used)
1011     pub asm_args: Vec<String>,
1012
1013     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
1014     /// to "generic".
1015     pub cpu: String,
1016     /// Default target features to pass to LLVM. These features will *always* be
1017     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
1018     /// -mattr=$features`.
1019     pub features: String,
1020     /// Whether dynamic linking is available on this target. Defaults to false.
1021     pub dynamic_linking: bool,
1022     /// If dynamic linking is available, whether only cdylibs are supported.
1023     pub only_cdylib: bool,
1024     /// Whether executables are available on this target. iOS, for example, only allows static
1025     /// libraries. Defaults to false.
1026     pub executables: bool,
1027     /// Relocation model to use in object file. Corresponds to `llc
1028     /// -relocation-model=$relocation_model`. Defaults to `Pic`.
1029     pub relocation_model: RelocModel,
1030     /// Code model to use. Corresponds to `llc -code-model=$code_model`.
1031     /// Defaults to `None` which means "inherited from the base LLVM target".
1032     pub code_model: Option<CodeModel>,
1033     /// TLS model to use. Options are "global-dynamic" (default), "local-dynamic", "initial-exec"
1034     /// and "local-exec". This is similar to the -ftls-model option in GCC/Clang.
1035     pub tls_model: TlsModel,
1036     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
1037     pub disable_redzone: bool,
1038     /// Eliminate frame pointers from stack frames if possible. Defaults to true.
1039     pub eliminate_frame_pointer: bool,
1040     /// Emit each function in its own section. Defaults to true.
1041     pub function_sections: bool,
1042     /// String to prepend to the name of every dynamic library. Defaults to "lib".
1043     pub dll_prefix: String,
1044     /// String to append to the name of every dynamic library. Defaults to ".so".
1045     pub dll_suffix: String,
1046     /// String to append to the name of every executable.
1047     pub exe_suffix: String,
1048     /// String to prepend to the name of every static library. Defaults to "lib".
1049     pub staticlib_prefix: String,
1050     /// String to append to the name of every static library. Defaults to ".a".
1051     pub staticlib_suffix: String,
1052     /// Values of the `target_family` cfg set for this target.
1053     ///
1054     /// Common options are: "unix", "windows". Defaults to no families.
1055     ///
1056     /// See <https://doc.rust-lang.org/reference/conditional-compilation.html#target_family>.
1057     pub families: Vec<String>,
1058     /// Whether the target toolchain's ABI supports returning small structs as an integer.
1059     pub abi_return_struct_as_int: bool,
1060     /// Whether the target toolchain is like macOS's. Only useful for compiling against iOS/macOS,
1061     /// in particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
1062     pub is_like_osx: bool,
1063     /// Whether the target toolchain is like Solaris's.
1064     /// Only useful for compiling against Illumos/Solaris,
1065     /// as they have a different set of linker flags. Defaults to false.
1066     pub is_like_solaris: bool,
1067     /// Whether the target is like Windows.
1068     /// This is a combination of several more specific properties represented as a single flag:
1069     ///   - The target uses a Windows ABI,
1070     ///   - uses PE/COFF as a format for object code,
1071     ///   - uses Windows-style dllexport/dllimport for shared libraries,
1072     ///   - uses import libraries and .def files for symbol exports,
1073     ///   - executables support setting a subsystem.
1074     pub is_like_windows: bool,
1075     /// Whether the target is like MSVC.
1076     /// This is a combination of several more specific properties represented as a single flag:
1077     ///   - The target has all the properties from `is_like_windows`
1078     ///     (for in-tree targets "is_like_msvc â‡’ is_like_windows" is ensured by a unit test),
1079     ///   - has some MSVC-specific Windows ABI properties,
1080     ///   - uses a link.exe-like linker,
1081     ///   - uses CodeView/PDB for debuginfo and natvis for its visualization,
1082     ///   - uses SEH-based unwinding,
1083     ///   - supports control flow guard mechanism.
1084     pub is_like_msvc: bool,
1085     /// Whether the target toolchain is like Emscripten's. Only useful for compiling with
1086     /// Emscripten toolchain.
1087     /// Defaults to false.
1088     pub is_like_emscripten: bool,
1089     /// Whether the target toolchain is like Fuchsia's.
1090     pub is_like_fuchsia: bool,
1091     /// Whether a target toolchain is like WASM.
1092     pub is_like_wasm: bool,
1093     /// Version of DWARF to use if not using the default.
1094     /// Useful because some platforms (osx, bsd) only want up to DWARF2.
1095     pub dwarf_version: Option<u32>,
1096     /// Whether the linker support GNU-like arguments such as -O. Defaults to true.
1097     pub linker_is_gnu: bool,
1098     /// The MinGW toolchain has a known issue that prevents it from correctly
1099     /// handling COFF object files with more than 2<sup>15</sup> sections. Since each weak
1100     /// symbol needs its own COMDAT section, weak linkage implies a large
1101     /// number sections that easily exceeds the given limit for larger
1102     /// codebases. Consequently we want a way to disallow weak linkage on some
1103     /// platforms.
1104     pub allows_weak_linkage: bool,
1105     /// Whether the linker support rpaths or not. Defaults to false.
1106     pub has_rpath: bool,
1107     /// Whether to disable linking to the default libraries, typically corresponds
1108     /// to `-nodefaultlibs`. Defaults to true.
1109     pub no_default_libraries: bool,
1110     /// Dynamically linked executables can be compiled as position independent
1111     /// if the default relocation model of position independent code is not
1112     /// changed. This is a requirement to take advantage of ASLR, as otherwise
1113     /// the functions in the executable are not randomized and can be used
1114     /// during an exploit of a vulnerability in any code.
1115     pub position_independent_executables: bool,
1116     /// Executables that are both statically linked and position-independent are supported.
1117     pub static_position_independent_executables: bool,
1118     /// Determines if the target always requires using the PLT for indirect
1119     /// library calls or not. This controls the default value of the `-Z plt` flag.
1120     pub needs_plt: bool,
1121     /// Either partial, full, or off. Full RELRO makes the dynamic linker
1122     /// resolve all symbols at startup and marks the GOT read-only before
1123     /// starting the program, preventing overwriting the GOT.
1124     pub relro_level: RelroLevel,
1125     /// Format that archives should be emitted in. This affects whether we use
1126     /// LLVM to assemble an archive or fall back to the system linker, and
1127     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
1128     /// the system linker to be used.
1129     pub archive_format: String,
1130     /// Is asm!() allowed? Defaults to true.
1131     pub allow_asm: bool,
1132     /// Whether the runtime startup code requires the `main` function be passed
1133     /// `argc` and `argv` values.
1134     pub main_needs_argc_argv: bool,
1135
1136     /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for
1137     /// this target.
1138     pub has_elf_tls: bool,
1139     // This is mainly for easy compatibility with emscripten.
1140     // If we give emcc .o files that are actually .bc files it
1141     // will 'just work'.
1142     pub obj_is_bitcode: bool,
1143     /// Whether the target requires that emitted object code includes bitcode.
1144     pub forces_embed_bitcode: bool,
1145     /// Content of the LLVM cmdline section associated with embedded bitcode.
1146     pub bitcode_llvm_cmdline: String,
1147
1148     /// Don't use this field; instead use the `.min_atomic_width()` method.
1149     pub min_atomic_width: Option<u64>,
1150
1151     /// Don't use this field; instead use the `.max_atomic_width()` method.
1152     pub max_atomic_width: Option<u64>,
1153
1154     /// Whether the target supports atomic CAS operations natively
1155     pub atomic_cas: bool,
1156
1157     /// Panic strategy: "unwind" or "abort"
1158     pub panic_strategy: PanicStrategy,
1159
1160     /// A list of ABIs unsupported by the current target. Note that generic ABIs
1161     /// are considered to be supported on all platforms and cannot be marked
1162     /// unsupported.
1163     pub unsupported_abis: Vec<Abi>,
1164
1165     /// Whether or not linking dylibs to a static CRT is allowed.
1166     pub crt_static_allows_dylibs: bool,
1167     /// Whether or not the CRT is statically linked by default.
1168     pub crt_static_default: bool,
1169     /// Whether or not crt-static is respected by the compiler (or is a no-op).
1170     pub crt_static_respected: bool,
1171
1172     /// The implementation of stack probes to use.
1173     pub stack_probes: StackProbeType,
1174
1175     /// The minimum alignment for global symbols.
1176     pub min_global_align: Option<u64>,
1177
1178     /// Default number of codegen units to use in debug mode
1179     pub default_codegen_units: Option<u64>,
1180
1181     /// Whether to generate trap instructions in places where optimization would
1182     /// otherwise produce control flow that falls through into unrelated memory.
1183     pub trap_unreachable: bool,
1184
1185     /// This target requires everything to be compiled with LTO to emit a final
1186     /// executable, aka there is no native linker for this target.
1187     pub requires_lto: bool,
1188
1189     /// This target has no support for threads.
1190     pub singlethread: bool,
1191
1192     /// Whether library functions call lowering/optimization is disabled in LLVM
1193     /// for this target unconditionally.
1194     pub no_builtins: bool,
1195
1196     /// The default visibility for symbols in this target should be "hidden"
1197     /// rather than "default"
1198     pub default_hidden_visibility: bool,
1199
1200     /// Whether a .debug_gdb_scripts section will be added to the output object file
1201     pub emit_debug_gdb_scripts: bool,
1202
1203     /// Whether or not to unconditionally `uwtable` attributes on functions,
1204     /// typically because the platform needs to unwind for things like stack
1205     /// unwinders.
1206     pub requires_uwtable: bool,
1207
1208     /// Whether or not to emit `uwtable` attributes on functions if `-C force-unwind-tables`
1209     /// is not specified and `uwtable` is not required on this target.
1210     pub default_uwtable: bool,
1211
1212     /// Whether or not SIMD types are passed by reference in the Rust ABI,
1213     /// typically required if a target can be compiled with a mixed set of
1214     /// target features. This is `true` by default, and `false` for targets like
1215     /// wasm32 where the whole program either has simd or not.
1216     pub simd_types_indirect: bool,
1217
1218     /// Pass a list of symbol which should be exported in the dylib to the linker.
1219     pub limit_rdylib_exports: bool,
1220
1221     /// If set, have the linker export exactly these symbols, instead of using
1222     /// the usual logic to figure this out from the crate itself.
1223     pub override_export_symbols: Option<Vec<String>>,
1224
1225     /// Determines how or whether the MergeFunctions LLVM pass should run for
1226     /// this target. Either "disabled", "trampolines", or "aliases".
1227     /// The MergeFunctions pass is generally useful, but some targets may need
1228     /// to opt out. The default is "aliases".
1229     ///
1230     /// Workaround for: <https://github.com/rust-lang/rust/issues/57356>
1231     pub merge_functions: MergeFunctions,
1232
1233     /// Use platform dependent mcount function
1234     pub mcount: String,
1235
1236     /// LLVM ABI name, corresponds to the '-mabi' parameter available in multilib C compilers
1237     pub llvm_abiname: String,
1238
1239     /// Whether or not RelaxElfRelocation flag will be passed to the linker
1240     pub relax_elf_relocations: bool,
1241
1242     /// Additional arguments to pass to LLVM, similar to the `-C llvm-args` codegen option.
1243     pub llvm_args: Vec<String>,
1244
1245     /// Whether to use legacy .ctors initialization hooks rather than .init_array. Defaults
1246     /// to false (uses .init_array).
1247     pub use_ctors_section: bool,
1248
1249     /// Whether the linker is instructed to add a `GNU_EH_FRAME` ELF header
1250     /// used to locate unwinding information is passed
1251     /// (only has effect if the linker is `ld`-like).
1252     pub eh_frame_header: bool,
1253
1254     /// Is true if the target is an ARM architecture using thumb v1 which allows for
1255     /// thumb and arm interworking.
1256     pub has_thumb_interworking: bool,
1257
1258     /// How to handle split debug information, if at all. Specifying `None` has
1259     /// target-specific meaning.
1260     pub split_debuginfo: SplitDebuginfo,
1261
1262     /// The sanitizers supported by this target
1263     ///
1264     /// Note that the support here is at a codegen level. If the machine code with sanitizer
1265     /// enabled can generated on this target, but the necessary supporting libraries are not
1266     /// distributed with the target, the sanitizer should still appear in this list for the target.
1267     pub supported_sanitizers: SanitizerSet,
1268
1269     /// If present it's a default value to use for adjusting the C ABI.
1270     pub default_adjusted_cabi: Option<Abi>,
1271 }
1272
1273 impl Default for TargetOptions {
1274     /// Creates a set of "sane defaults" for any target. This is still
1275     /// incomplete, and if used for compilation, will certainly not work.
1276     fn default() -> TargetOptions {
1277         TargetOptions {
1278             is_builtin: false,
1279             endian: Endian::Little,
1280             c_int_width: "32".to_string(),
1281             os: "none".to_string(),
1282             env: String::new(),
1283             vendor: "unknown".to_string(),
1284             linker_flavor: LinkerFlavor::Gcc,
1285             linker: option_env!("CFG_DEFAULT_LINKER").map(|s| s.to_string()),
1286             lld_flavor: LldFlavor::Ld,
1287             pre_link_args: LinkArgs::new(),
1288             post_link_args: LinkArgs::new(),
1289             link_script: None,
1290             asm_args: Vec::new(),
1291             cpu: "generic".to_string(),
1292             features: String::new(),
1293             dynamic_linking: false,
1294             only_cdylib: false,
1295             executables: false,
1296             relocation_model: RelocModel::Pic,
1297             code_model: None,
1298             tls_model: TlsModel::GeneralDynamic,
1299             disable_redzone: false,
1300             eliminate_frame_pointer: true,
1301             function_sections: true,
1302             dll_prefix: "lib".to_string(),
1303             dll_suffix: ".so".to_string(),
1304             exe_suffix: String::new(),
1305             staticlib_prefix: "lib".to_string(),
1306             staticlib_suffix: ".a".to_string(),
1307             families: Vec::new(),
1308             abi_return_struct_as_int: false,
1309             is_like_osx: false,
1310             is_like_solaris: false,
1311             is_like_windows: false,
1312             is_like_emscripten: false,
1313             is_like_msvc: false,
1314             is_like_fuchsia: false,
1315             is_like_wasm: false,
1316             dwarf_version: None,
1317             linker_is_gnu: true,
1318             allows_weak_linkage: true,
1319             has_rpath: false,
1320             no_default_libraries: true,
1321             position_independent_executables: false,
1322             static_position_independent_executables: false,
1323             needs_plt: false,
1324             relro_level: RelroLevel::None,
1325             pre_link_objects: Default::default(),
1326             post_link_objects: Default::default(),
1327             pre_link_objects_fallback: Default::default(),
1328             post_link_objects_fallback: Default::default(),
1329             crt_objects_fallback: None,
1330             late_link_args: LinkArgs::new(),
1331             late_link_args_dynamic: LinkArgs::new(),
1332             late_link_args_static: LinkArgs::new(),
1333             link_env: Vec::new(),
1334             link_env_remove: Vec::new(),
1335             archive_format: "gnu".to_string(),
1336             main_needs_argc_argv: true,
1337             allow_asm: true,
1338             has_elf_tls: false,
1339             obj_is_bitcode: false,
1340             forces_embed_bitcode: false,
1341             bitcode_llvm_cmdline: String::new(),
1342             min_atomic_width: None,
1343             max_atomic_width: None,
1344             atomic_cas: true,
1345             panic_strategy: PanicStrategy::Unwind,
1346             unsupported_abis: vec![],
1347             crt_static_allows_dylibs: false,
1348             crt_static_default: false,
1349             crt_static_respected: false,
1350             stack_probes: StackProbeType::None,
1351             min_global_align: None,
1352             default_codegen_units: None,
1353             trap_unreachable: true,
1354             requires_lto: false,
1355             singlethread: false,
1356             no_builtins: false,
1357             default_hidden_visibility: false,
1358             emit_debug_gdb_scripts: true,
1359             requires_uwtable: false,
1360             default_uwtable: false,
1361             simd_types_indirect: true,
1362             limit_rdylib_exports: true,
1363             override_export_symbols: None,
1364             merge_functions: MergeFunctions::Aliases,
1365             mcount: "mcount".to_string(),
1366             llvm_abiname: "".to_string(),
1367             relax_elf_relocations: false,
1368             llvm_args: vec![],
1369             use_ctors_section: false,
1370             eh_frame_header: true,
1371             has_thumb_interworking: false,
1372             split_debuginfo: SplitDebuginfo::Off,
1373             supported_sanitizers: SanitizerSet::empty(),
1374             default_adjusted_cabi: None,
1375         }
1376     }
1377 }
1378
1379 /// `TargetOptions` being a separate type is basically an implementation detail of `Target` that is
1380 /// used for providing defaults. Perhaps there's a way to merge `TargetOptions` into `Target` so
1381 /// this `Deref` implementation is no longer necessary.
1382 impl Deref for Target {
1383     type Target = TargetOptions;
1384
1385     fn deref(&self) -> &Self::Target {
1386         &self.options
1387     }
1388 }
1389 impl DerefMut for Target {
1390     fn deref_mut(&mut self) -> &mut Self::Target {
1391         &mut self.options
1392     }
1393 }
1394
1395 impl Target {
1396     /// Given a function ABI, turn it into the correct ABI for this target.
1397     pub fn adjust_abi(&self, abi: Abi) -> Abi {
1398         match abi {
1399             Abi::System { unwind } => {
1400                 if self.is_like_windows && self.arch == "x86" {
1401                     Abi::Stdcall { unwind }
1402                 } else {
1403                     Abi::C { unwind }
1404                 }
1405             }
1406             // These ABI kinds are ignored on non-x86 Windows targets.
1407             // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions
1408             // and the individual pages for __stdcall et al.
1409             Abi::Stdcall { unwind } | Abi::Thiscall { unwind } => {
1410                 if self.is_like_windows && self.arch != "x86" { Abi::C { unwind } } else { abi }
1411             }
1412             Abi::Fastcall | Abi::Vectorcall => {
1413                 if self.is_like_windows && self.arch != "x86" {
1414                     Abi::C { unwind: false }
1415                 } else {
1416                     abi
1417                 }
1418             }
1419             Abi::EfiApi => {
1420                 if self.arch == "x86_64" {
1421                     Abi::Win64
1422                 } else {
1423                     Abi::C { unwind: false }
1424                 }
1425             }
1426
1427             Abi::C { unwind } => self.default_adjusted_cabi.unwrap_or(Abi::C { unwind }),
1428
1429             abi => abi,
1430         }
1431     }
1432
1433     /// Minimum integer size in bits that this target can perform atomic
1434     /// operations on.
1435     pub fn min_atomic_width(&self) -> u64 {
1436         self.min_atomic_width.unwrap_or(8)
1437     }
1438
1439     /// Maximum integer size in bits that this target can perform atomic
1440     /// operations on.
1441     pub fn max_atomic_width(&self) -> u64 {
1442         self.max_atomic_width.unwrap_or_else(|| self.pointer_width.into())
1443     }
1444
1445     pub fn is_abi_supported(&self, abi: Abi) -> bool {
1446         abi.generic() || !self.unsupported_abis.contains(&abi)
1447     }
1448
1449     /// Loads a target descriptor from a JSON object.
1450     pub fn from_json(obj: Json) -> Result<Target, String> {
1451         // While ugly, this code must remain this way to retain
1452         // compatibility with existing JSON fields and the internal
1453         // expected naming of the Target and TargetOptions structs.
1454         // To ensure compatibility is retained, the built-in targets
1455         // are round-tripped through this code to catch cases where
1456         // the JSON parser is not updated to match the structs.
1457
1458         let get_req_field = |name: &str| {
1459             obj.find(name)
1460                 .and_then(Json::as_string)
1461                 .map(str::to_string)
1462                 .ok_or_else(|| format!("Field {} in target specification is required", name))
1463         };
1464
1465         let mut base = Target {
1466             llvm_target: get_req_field("llvm-target")?,
1467             pointer_width: get_req_field("target-pointer-width")?
1468                 .parse::<u32>()
1469                 .map_err(|_| "target-pointer-width must be an integer".to_string())?,
1470             data_layout: get_req_field("data-layout")?,
1471             arch: get_req_field("arch")?,
1472             options: Default::default(),
1473         };
1474
1475         macro_rules! key {
1476             ($key_name:ident) => ( {
1477                 let name = (stringify!($key_name)).replace("_", "-");
1478                 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1479                     base.$key_name = s.to_string();
1480                 }
1481             } );
1482             ($key_name:ident = $json_name:expr) => ( {
1483                 let name = $json_name;
1484                 if let Some(s) = obj.find(&name).and_then(Json::as_string) {
1485                     base.$key_name = s.to_string();
1486                 }
1487             } );
1488             ($key_name:ident, bool) => ( {
1489                 let name = (stringify!($key_name)).replace("_", "-");
1490                 if let Some(s) = obj.find(&name).and_then(Json::as_boolean) {
1491                     base.$key_name = s;
1492                 }
1493             } );
1494             ($key_name:ident, Option<u32>) => ( {
1495                 let name = (stringify!($key_name)).replace("_", "-");
1496                 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1497                     if s < 1 || s > 5 {
1498                         return Err("Not a valid DWARF version number".to_string());
1499                     }
1500                     base.$key_name = Some(s as u32);
1501                 }
1502             } );
1503             ($key_name:ident, Option<u64>) => ( {
1504                 let name = (stringify!($key_name)).replace("_", "-");
1505                 if let Some(s) = obj.find(&name).and_then(Json::as_u64) {
1506                     base.$key_name = Some(s);
1507                 }
1508             } );
1509             ($key_name:ident, MergeFunctions) => ( {
1510                 let name = (stringify!($key_name)).replace("_", "-");
1511                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1512                     match s.parse::<MergeFunctions>() {
1513                         Ok(mergefunc) => base.$key_name = mergefunc,
1514                         _ => return Some(Err(format!("'{}' is not a valid value for \
1515                                                       merge-functions. Use 'disabled', \
1516                                                       'trampolines', or 'aliases'.",
1517                                                       s))),
1518                     }
1519                     Some(Ok(()))
1520                 })).unwrap_or(Ok(()))
1521             } );
1522             ($key_name:ident, RelocModel) => ( {
1523                 let name = (stringify!($key_name)).replace("_", "-");
1524                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1525                     match s.parse::<RelocModel>() {
1526                         Ok(relocation_model) => base.$key_name = relocation_model,
1527                         _ => return Some(Err(format!("'{}' is not a valid relocation model. \
1528                                                       Run `rustc --print relocation-models` to \
1529                                                       see the list of supported values.", s))),
1530                     }
1531                     Some(Ok(()))
1532                 })).unwrap_or(Ok(()))
1533             } );
1534             ($key_name:ident, CodeModel) => ( {
1535                 let name = (stringify!($key_name)).replace("_", "-");
1536                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1537                     match s.parse::<CodeModel>() {
1538                         Ok(code_model) => base.$key_name = Some(code_model),
1539                         _ => return Some(Err(format!("'{}' is not a valid code model. \
1540                                                       Run `rustc --print code-models` to \
1541                                                       see the list of supported values.", s))),
1542                     }
1543                     Some(Ok(()))
1544                 })).unwrap_or(Ok(()))
1545             } );
1546             ($key_name:ident, TlsModel) => ( {
1547                 let name = (stringify!($key_name)).replace("_", "-");
1548                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1549                     match s.parse::<TlsModel>() {
1550                         Ok(tls_model) => base.$key_name = tls_model,
1551                         _ => return Some(Err(format!("'{}' is not a valid TLS model. \
1552                                                       Run `rustc --print tls-models` to \
1553                                                       see the list of supported values.", s))),
1554                     }
1555                     Some(Ok(()))
1556                 })).unwrap_or(Ok(()))
1557             } );
1558             ($key_name:ident, PanicStrategy) => ( {
1559                 let name = (stringify!($key_name)).replace("_", "-");
1560                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1561                     match s {
1562                         "unwind" => base.$key_name = PanicStrategy::Unwind,
1563                         "abort" => base.$key_name = PanicStrategy::Abort,
1564                         _ => return Some(Err(format!("'{}' is not a valid value for \
1565                                                       panic-strategy. Use 'unwind' or 'abort'.",
1566                                                      s))),
1567                 }
1568                 Some(Ok(()))
1569             })).unwrap_or(Ok(()))
1570             } );
1571             ($key_name:ident, RelroLevel) => ( {
1572                 let name = (stringify!($key_name)).replace("_", "-");
1573                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1574                     match s.parse::<RelroLevel>() {
1575                         Ok(level) => base.$key_name = level,
1576                         _ => return Some(Err(format!("'{}' is not a valid value for \
1577                                                       relro-level. Use 'full', 'partial, or 'off'.",
1578                                                       s))),
1579                     }
1580                     Some(Ok(()))
1581                 })).unwrap_or(Ok(()))
1582             } );
1583             ($key_name:ident, SplitDebuginfo) => ( {
1584                 let name = (stringify!($key_name)).replace("_", "-");
1585                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1586                     match s.parse::<SplitDebuginfo>() {
1587                         Ok(level) => base.$key_name = level,
1588                         _ => return Some(Err(format!("'{}' is not a valid value for \
1589                                                       split-debuginfo. Use 'off' or 'dsymutil'.",
1590                                                       s))),
1591                     }
1592                     Some(Ok(()))
1593                 })).unwrap_or(Ok(()))
1594             } );
1595             ($key_name:ident, list) => ( {
1596                 let name = (stringify!($key_name)).replace("_", "-");
1597                 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1598                     base.$key_name = v.iter()
1599                         .map(|a| a.as_string().unwrap().to_string())
1600                         .collect();
1601                 }
1602             } );
1603             ($key_name:ident, opt_list) => ( {
1604                 let name = (stringify!($key_name)).replace("_", "-");
1605                 if let Some(v) = obj.find(&name).and_then(Json::as_array) {
1606                     base.$key_name = Some(v.iter()
1607                         .map(|a| a.as_string().unwrap().to_string())
1608                         .collect());
1609                 }
1610             } );
1611             ($key_name:ident, optional) => ( {
1612                 let name = (stringify!($key_name)).replace("_", "-");
1613                 if let Some(o) = obj.find(&name[..]) {
1614                     base.$key_name = o
1615                         .as_string()
1616                         .map(|s| s.to_string() );
1617                 }
1618             } );
1619             ($key_name:ident, LldFlavor) => ( {
1620                 let name = (stringify!($key_name)).replace("_", "-");
1621                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1622                     if let Some(flavor) = LldFlavor::from_str(&s) {
1623                         base.$key_name = flavor;
1624                     } else {
1625                         return Some(Err(format!(
1626                             "'{}' is not a valid value for lld-flavor. \
1627                              Use 'darwin', 'gnu', 'link' or 'wasm.",
1628                             s)))
1629                     }
1630                     Some(Ok(()))
1631                 })).unwrap_or(Ok(()))
1632             } );
1633             ($key_name:ident, LinkerFlavor) => ( {
1634                 let name = (stringify!($key_name)).replace("_", "-");
1635                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1636                     match LinkerFlavor::from_str(s) {
1637                         Some(linker_flavor) => base.$key_name = linker_flavor,
1638                         _ => return Some(Err(format!("'{}' is not a valid value for linker-flavor. \
1639                                                       Use {}", s, LinkerFlavor::one_of()))),
1640                     }
1641                     Some(Ok(()))
1642                 })).unwrap_or(Ok(()))
1643             } );
1644             ($key_name:ident, StackProbeType) => ( {
1645                 let name = (stringify!($key_name)).replace("_", "-");
1646                 obj.find(&name[..]).and_then(|o| match StackProbeType::from_json(o) {
1647                     Ok(v) => {
1648                         base.$key_name = v;
1649                         Some(Ok(()))
1650                     },
1651                     Err(s) => Some(Err(
1652                         format!("`{:?}` is not a valid value for `{}`: {}", o, name, s)
1653                     )),
1654                 }).unwrap_or(Ok(()))
1655             } );
1656             ($key_name:ident, SanitizerSet) => ( {
1657                 let name = (stringify!($key_name)).replace("_", "-");
1658                 obj.find(&name[..]).and_then(|o| o.as_array()).and_then(|a| {
1659                     for s in a {
1660                         base.$key_name |= match s.as_string() {
1661                             Some("address") => SanitizerSet::ADDRESS,
1662                             Some("leak") => SanitizerSet::LEAK,
1663                             Some("memory") => SanitizerSet::MEMORY,
1664                             Some("thread") => SanitizerSet::THREAD,
1665                             Some("hwaddress") => SanitizerSet::HWADDRESS,
1666                             Some(s) => return Some(Err(format!("unknown sanitizer {}", s))),
1667                             _ => return Some(Err(format!("not a string: {:?}", s))),
1668                         };
1669                     }
1670                     Some(Ok(()))
1671                 }).unwrap_or(Ok(()))
1672             } );
1673
1674             ($key_name:ident, crt_objects_fallback) => ( {
1675                 let name = (stringify!($key_name)).replace("_", "-");
1676                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1677                     match s.parse::<CrtObjectsFallback>() {
1678                         Ok(fallback) => base.$key_name = Some(fallback),
1679                         _ => return Some(Err(format!("'{}' is not a valid CRT objects fallback. \
1680                                                       Use 'musl', 'mingw' or 'wasm'", s))),
1681                     }
1682                     Some(Ok(()))
1683                 })).unwrap_or(Ok(()))
1684             } );
1685             ($key_name:ident, link_objects) => ( {
1686                 let name = (stringify!($key_name)).replace("_", "-");
1687                 if let Some(val) = obj.find(&name[..]) {
1688                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1689                         JSON object with fields per CRT object kind.", name))?;
1690                     let mut args = CrtObjects::new();
1691                     for (k, v) in obj {
1692                         let kind = LinkOutputKind::from_str(&k).ok_or_else(|| {
1693                             format!("{}: '{}' is not a valid value for CRT object kind. \
1694                                      Use '(dynamic,static)-(nopic,pic)-exe' or \
1695                                      '(dynamic,static)-dylib' or 'wasi-reactor-exe'", name, k)
1696                         })?;
1697
1698                         let v = v.as_array().ok_or_else(||
1699                             format!("{}.{}: expected a JSON array", name, k)
1700                         )?.iter().enumerate()
1701                             .map(|(i,s)| {
1702                                 let s = s.as_string().ok_or_else(||
1703                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1704                                 Ok(s.to_owned())
1705                             })
1706                             .collect::<Result<Vec<_>, String>>()?;
1707
1708                         args.insert(kind, v);
1709                     }
1710                     base.$key_name = args;
1711                 }
1712             } );
1713             ($key_name:ident, link_args) => ( {
1714                 let name = (stringify!($key_name)).replace("_", "-");
1715                 if let Some(val) = obj.find(&name[..]) {
1716                     let obj = val.as_object().ok_or_else(|| format!("{}: expected a \
1717                         JSON object with fields per linker-flavor.", name))?;
1718                     let mut args = LinkArgs::new();
1719                     for (k, v) in obj {
1720                         let flavor = LinkerFlavor::from_str(&k).ok_or_else(|| {
1721                             format!("{}: '{}' is not a valid value for linker-flavor. \
1722                                      Use 'em', 'gcc', 'ld' or 'msvc'", name, k)
1723                         })?;
1724
1725                         let v = v.as_array().ok_or_else(||
1726                             format!("{}.{}: expected a JSON array", name, k)
1727                         )?.iter().enumerate()
1728                             .map(|(i,s)| {
1729                                 let s = s.as_string().ok_or_else(||
1730                                     format!("{}.{}[{}]: expected a JSON string", name, k, i))?;
1731                                 Ok(s.to_owned())
1732                             })
1733                             .collect::<Result<Vec<_>, String>>()?;
1734
1735                         args.insert(flavor, v);
1736                     }
1737                     base.$key_name = args;
1738                 }
1739             } );
1740             ($key_name:ident, env) => ( {
1741                 let name = (stringify!($key_name)).replace("_", "-");
1742                 if let Some(a) = obj.find(&name[..]).and_then(|o| o.as_array()) {
1743                     for o in a {
1744                         if let Some(s) = o.as_string() {
1745                             let p = s.split('=').collect::<Vec<_>>();
1746                             if p.len() == 2 {
1747                                 let k = p[0].to_string();
1748                                 let v = p[1].to_string();
1749                                 base.$key_name.push((k, v));
1750                             }
1751                         }
1752                     }
1753                 }
1754             } );
1755             ($key_name:ident, Option<Abi>) => ( {
1756                 let name = (stringify!($key_name)).replace("_", "-");
1757                 obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
1758                     match lookup_abi(s) {
1759                         Some(abi) => base.$key_name = Some(abi),
1760                         _ => return Some(Err(format!("'{}' is not a valid value for abi", s))),
1761                     }
1762                     Some(Ok(()))
1763                 })).unwrap_or(Ok(()))
1764             } );
1765             ($key_name:ident, TargetFamilies) => ( {
1766                 let value = obj.find("target-family");
1767                 if let Some(v) = value.and_then(Json::as_array) {
1768                     base.$key_name = v.iter()
1769                         .map(|a| a.as_string().unwrap().to_string())
1770                         .collect();
1771                 } else if let Some(v) = value.and_then(Json::as_string) {
1772                     base.$key_name = vec![v.to_string()];
1773                 }
1774             } );
1775         }
1776
1777         if let Some(s) = obj.find("target-endian").and_then(Json::as_string) {
1778             base.endian = s.parse()?;
1779         }
1780         key!(is_builtin, bool);
1781         key!(c_int_width = "target-c-int-width");
1782         key!(os);
1783         key!(env);
1784         key!(vendor);
1785         key!(linker_flavor, LinkerFlavor)?;
1786         key!(linker, optional);
1787         key!(lld_flavor, LldFlavor)?;
1788         key!(pre_link_objects, link_objects);
1789         key!(post_link_objects, link_objects);
1790         key!(pre_link_objects_fallback, link_objects);
1791         key!(post_link_objects_fallback, link_objects);
1792         key!(crt_objects_fallback, crt_objects_fallback)?;
1793         key!(pre_link_args, link_args);
1794         key!(late_link_args, link_args);
1795         key!(late_link_args_dynamic, link_args);
1796         key!(late_link_args_static, link_args);
1797         key!(post_link_args, link_args);
1798         key!(link_script, optional);
1799         key!(link_env, env);
1800         key!(link_env_remove, list);
1801         key!(asm_args, list);
1802         key!(cpu);
1803         key!(features);
1804         key!(dynamic_linking, bool);
1805         key!(only_cdylib, bool);
1806         key!(executables, bool);
1807         key!(relocation_model, RelocModel)?;
1808         key!(code_model, CodeModel)?;
1809         key!(tls_model, TlsModel)?;
1810         key!(disable_redzone, bool);
1811         key!(eliminate_frame_pointer, bool);
1812         key!(function_sections, bool);
1813         key!(dll_prefix);
1814         key!(dll_suffix);
1815         key!(exe_suffix);
1816         key!(staticlib_prefix);
1817         key!(staticlib_suffix);
1818         key!(families, TargetFamilies);
1819         key!(abi_return_struct_as_int, bool);
1820         key!(is_like_osx, bool);
1821         key!(is_like_solaris, bool);
1822         key!(is_like_windows, bool);
1823         key!(is_like_msvc, bool);
1824         key!(is_like_emscripten, bool);
1825         key!(is_like_fuchsia, bool);
1826         key!(is_like_wasm, bool);
1827         key!(dwarf_version, Option<u32>);
1828         key!(linker_is_gnu, bool);
1829         key!(allows_weak_linkage, bool);
1830         key!(has_rpath, bool);
1831         key!(no_default_libraries, bool);
1832         key!(position_independent_executables, bool);
1833         key!(static_position_independent_executables, bool);
1834         key!(needs_plt, bool);
1835         key!(relro_level, RelroLevel)?;
1836         key!(archive_format);
1837         key!(allow_asm, bool);
1838         key!(main_needs_argc_argv, bool);
1839         key!(has_elf_tls, bool);
1840         key!(obj_is_bitcode, bool);
1841         key!(forces_embed_bitcode, bool);
1842         key!(bitcode_llvm_cmdline);
1843         key!(max_atomic_width, Option<u64>);
1844         key!(min_atomic_width, Option<u64>);
1845         key!(atomic_cas, bool);
1846         key!(panic_strategy, PanicStrategy)?;
1847         key!(crt_static_allows_dylibs, bool);
1848         key!(crt_static_default, bool);
1849         key!(crt_static_respected, bool);
1850         key!(stack_probes, StackProbeType)?;
1851         key!(min_global_align, Option<u64>);
1852         key!(default_codegen_units, Option<u64>);
1853         key!(trap_unreachable, bool);
1854         key!(requires_lto, bool);
1855         key!(singlethread, bool);
1856         key!(no_builtins, bool);
1857         key!(default_hidden_visibility, bool);
1858         key!(emit_debug_gdb_scripts, bool);
1859         key!(requires_uwtable, bool);
1860         key!(default_uwtable, bool);
1861         key!(simd_types_indirect, bool);
1862         key!(limit_rdylib_exports, bool);
1863         key!(override_export_symbols, opt_list);
1864         key!(merge_functions, MergeFunctions)?;
1865         key!(mcount = "target-mcount");
1866         key!(llvm_abiname);
1867         key!(relax_elf_relocations, bool);
1868         key!(llvm_args, list);
1869         key!(use_ctors_section, bool);
1870         key!(eh_frame_header, bool);
1871         key!(has_thumb_interworking, bool);
1872         key!(split_debuginfo, SplitDebuginfo)?;
1873         key!(supported_sanitizers, SanitizerSet)?;
1874         key!(default_adjusted_cabi, Option<Abi>)?;
1875
1876         // NB: The old name is deprecated, but support for it is retained for
1877         // compatibility.
1878         for name in ["abi-blacklist", "unsupported-abis"].iter() {
1879             if let Some(array) = obj.find(name).and_then(Json::as_array) {
1880                 for name in array.iter().filter_map(|abi| abi.as_string()) {
1881                     match lookup_abi(name) {
1882                         Some(abi) => {
1883                             if abi.generic() {
1884                                 return Err(format!(
1885                                     "The ABI \"{}\" is considered to be supported on all \
1886                                     targets and cannot be marked unsupported",
1887                                     abi
1888                                 ));
1889                             }
1890
1891                             base.unsupported_abis.push(abi)
1892                         }
1893                         None => {
1894                             return Err(format!(
1895                                 "Unknown ABI \"{}\" in target specification",
1896                                 name
1897                             ));
1898                         }
1899                     }
1900                 }
1901             }
1902         }
1903
1904         Ok(base)
1905     }
1906
1907     /// Search for a JSON file specifying the given target triple.
1908     ///
1909     /// If none is found in `$RUST_TARGET_PATH`, look for a file called `target.json` inside the
1910     /// sysroot under the target-triple's `rustlib` directory.  Note that it could also just be a
1911     /// bare filename already, so also check for that. If one of the hardcoded targets we know
1912     /// about, just return it directly.
1913     ///
1914     /// The error string could come from any of the APIs called, including filesystem access and
1915     /// JSON decoding.
1916     pub fn search(target_triple: &TargetTriple, sysroot: &PathBuf) -> Result<Target, String> {
1917         use rustc_serialize::json;
1918         use std::env;
1919         use std::fs;
1920
1921         fn load_file(path: &Path) -> Result<Target, String> {
1922             let contents = fs::read(path).map_err(|e| e.to_string())?;
1923             let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
1924             Target::from_json(obj)
1925         }
1926
1927         match *target_triple {
1928             TargetTriple::TargetTriple(ref target_triple) => {
1929                 // check if triple is in list of built-in targets
1930                 if let Some(t) = load_builtin(target_triple) {
1931                     return Ok(t);
1932                 }
1933
1934                 // search for a file named `target_triple`.json in RUST_TARGET_PATH
1935                 let path = {
1936                     let mut target = target_triple.to_string();
1937                     target.push_str(".json");
1938                     PathBuf::from(target)
1939                 };
1940
1941                 let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default();
1942
1943                 for dir in env::split_paths(&target_path) {
1944                     let p = dir.join(&path);
1945                     if p.is_file() {
1946                         return load_file(&p);
1947                     }
1948                 }
1949
1950                 // Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
1951                 // as a fallback.
1952                 let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
1953                 let p = std::array::IntoIter::new([
1954                     Path::new(sysroot),
1955                     Path::new(&rustlib_path),
1956                     Path::new("target.json"),
1957                 ])
1958                 .collect::<PathBuf>();
1959                 if p.is_file() {
1960                     return load_file(&p);
1961                 }
1962
1963                 Err(format!("Could not find specification for target {:?}", target_triple))
1964             }
1965             TargetTriple::TargetPath(ref target_path) => {
1966                 if target_path.is_file() {
1967                     return load_file(&target_path);
1968                 }
1969                 Err(format!("Target path {:?} is not a valid file", target_path))
1970             }
1971         }
1972     }
1973 }
1974
1975 impl ToJson for Target {
1976     fn to_json(&self) -> Json {
1977         let mut d = BTreeMap::new();
1978         let default: TargetOptions = Default::default();
1979
1980         macro_rules! target_val {
1981             ($attr:ident) => {{
1982                 let name = (stringify!($attr)).replace("_", "-");
1983                 d.insert(name, self.$attr.to_json());
1984             }};
1985             ($attr:ident, $key_name:expr) => {{
1986                 let name = $key_name;
1987                 d.insert(name.to_string(), self.$attr.to_json());
1988             }};
1989         }
1990
1991         macro_rules! target_option_val {
1992             ($attr:ident) => {{
1993                 let name = (stringify!($attr)).replace("_", "-");
1994                 if default.$attr != self.$attr {
1995                     d.insert(name, self.$attr.to_json());
1996                 }
1997             }};
1998             ($attr:ident, $key_name:expr) => {{
1999                 let name = $key_name;
2000                 if default.$attr != self.$attr {
2001                     d.insert(name.to_string(), self.$attr.to_json());
2002                 }
2003             }};
2004             (link_args - $attr:ident) => {{
2005                 let name = (stringify!($attr)).replace("_", "-");
2006                 if default.$attr != self.$attr {
2007                     let obj = self
2008                         .$attr
2009                         .iter()
2010                         .map(|(k, v)| (k.desc().to_owned(), v.clone()))
2011                         .collect::<BTreeMap<_, _>>();
2012                     d.insert(name, obj.to_json());
2013                 }
2014             }};
2015             (env - $attr:ident) => {{
2016                 let name = (stringify!($attr)).replace("_", "-");
2017                 if default.$attr != self.$attr {
2018                     let obj = self
2019                         .$attr
2020                         .iter()
2021                         .map(|&(ref k, ref v)| k.clone() + "=" + &v)
2022                         .collect::<Vec<_>>();
2023                     d.insert(name, obj.to_json());
2024                 }
2025             }};
2026         }
2027
2028         target_val!(llvm_target);
2029         d.insert("target-pointer-width".to_string(), self.pointer_width.to_string().to_json());
2030         target_val!(arch);
2031         target_val!(data_layout);
2032
2033         target_option_val!(is_builtin);
2034         target_option_val!(endian, "target-endian");
2035         target_option_val!(c_int_width, "target-c-int-width");
2036         target_option_val!(os);
2037         target_option_val!(env);
2038         target_option_val!(vendor);
2039         target_option_val!(linker_flavor);
2040         target_option_val!(linker);
2041         target_option_val!(lld_flavor);
2042         target_option_val!(pre_link_objects);
2043         target_option_val!(post_link_objects);
2044         target_option_val!(pre_link_objects_fallback);
2045         target_option_val!(post_link_objects_fallback);
2046         target_option_val!(crt_objects_fallback);
2047         target_option_val!(link_args - pre_link_args);
2048         target_option_val!(link_args - late_link_args);
2049         target_option_val!(link_args - late_link_args_dynamic);
2050         target_option_val!(link_args - late_link_args_static);
2051         target_option_val!(link_args - post_link_args);
2052         target_option_val!(link_script);
2053         target_option_val!(env - link_env);
2054         target_option_val!(link_env_remove);
2055         target_option_val!(asm_args);
2056         target_option_val!(cpu);
2057         target_option_val!(features);
2058         target_option_val!(dynamic_linking);
2059         target_option_val!(only_cdylib);
2060         target_option_val!(executables);
2061         target_option_val!(relocation_model);
2062         target_option_val!(code_model);
2063         target_option_val!(tls_model);
2064         target_option_val!(disable_redzone);
2065         target_option_val!(eliminate_frame_pointer);
2066         target_option_val!(function_sections);
2067         target_option_val!(dll_prefix);
2068         target_option_val!(dll_suffix);
2069         target_option_val!(exe_suffix);
2070         target_option_val!(staticlib_prefix);
2071         target_option_val!(staticlib_suffix);
2072         target_option_val!(families, "target-family");
2073         target_option_val!(abi_return_struct_as_int);
2074         target_option_val!(is_like_osx);
2075         target_option_val!(is_like_solaris);
2076         target_option_val!(is_like_windows);
2077         target_option_val!(is_like_msvc);
2078         target_option_val!(is_like_emscripten);
2079         target_option_val!(is_like_fuchsia);
2080         target_option_val!(is_like_wasm);
2081         target_option_val!(dwarf_version);
2082         target_option_val!(linker_is_gnu);
2083         target_option_val!(allows_weak_linkage);
2084         target_option_val!(has_rpath);
2085         target_option_val!(no_default_libraries);
2086         target_option_val!(position_independent_executables);
2087         target_option_val!(static_position_independent_executables);
2088         target_option_val!(needs_plt);
2089         target_option_val!(relro_level);
2090         target_option_val!(archive_format);
2091         target_option_val!(allow_asm);
2092         target_option_val!(main_needs_argc_argv);
2093         target_option_val!(has_elf_tls);
2094         target_option_val!(obj_is_bitcode);
2095         target_option_val!(forces_embed_bitcode);
2096         target_option_val!(bitcode_llvm_cmdline);
2097         target_option_val!(min_atomic_width);
2098         target_option_val!(max_atomic_width);
2099         target_option_val!(atomic_cas);
2100         target_option_val!(panic_strategy);
2101         target_option_val!(crt_static_allows_dylibs);
2102         target_option_val!(crt_static_default);
2103         target_option_val!(crt_static_respected);
2104         target_option_val!(stack_probes);
2105         target_option_val!(min_global_align);
2106         target_option_val!(default_codegen_units);
2107         target_option_val!(trap_unreachable);
2108         target_option_val!(requires_lto);
2109         target_option_val!(singlethread);
2110         target_option_val!(no_builtins);
2111         target_option_val!(default_hidden_visibility);
2112         target_option_val!(emit_debug_gdb_scripts);
2113         target_option_val!(requires_uwtable);
2114         target_option_val!(default_uwtable);
2115         target_option_val!(simd_types_indirect);
2116         target_option_val!(limit_rdylib_exports);
2117         target_option_val!(override_export_symbols);
2118         target_option_val!(merge_functions);
2119         target_option_val!(mcount, "target-mcount");
2120         target_option_val!(llvm_abiname);
2121         target_option_val!(relax_elf_relocations);
2122         target_option_val!(llvm_args);
2123         target_option_val!(use_ctors_section);
2124         target_option_val!(eh_frame_header);
2125         target_option_val!(has_thumb_interworking);
2126         target_option_val!(split_debuginfo);
2127         target_option_val!(supported_sanitizers);
2128
2129         if let Some(abi) = self.default_adjusted_cabi {
2130             d.insert("default-adjusted-cabi".to_string(), Abi::name(abi).to_json());
2131         }
2132
2133         if default.unsupported_abis != self.unsupported_abis {
2134             d.insert(
2135                 "unsupported-abis".to_string(),
2136                 self.unsupported_abis
2137                     .iter()
2138                     .map(|&name| Abi::name(name).to_json())
2139                     .collect::<Vec<_>>()
2140                     .to_json(),
2141             );
2142         }
2143
2144         Json::Object(d)
2145     }
2146 }
2147
2148 /// Either a target triple string or a path to a JSON file.
2149 #[derive(PartialEq, Clone, Debug, Hash, Encodable, Decodable)]
2150 pub enum TargetTriple {
2151     TargetTriple(String),
2152     TargetPath(PathBuf),
2153 }
2154
2155 impl TargetTriple {
2156     /// Creates a target triple from the passed target triple string.
2157     pub fn from_triple(triple: &str) -> Self {
2158         TargetTriple::TargetTriple(triple.to_string())
2159     }
2160
2161     /// Creates a target triple from the passed target path.
2162     pub fn from_path(path: &Path) -> Result<Self, io::Error> {
2163         let canonicalized_path = path.canonicalize()?;
2164         Ok(TargetTriple::TargetPath(canonicalized_path))
2165     }
2166
2167     /// Returns a string triple for this target.
2168     ///
2169     /// If this target is a path, the file name (without extension) is returned.
2170     pub fn triple(&self) -> &str {
2171         match *self {
2172             TargetTriple::TargetTriple(ref triple) => triple,
2173             TargetTriple::TargetPath(ref path) => path
2174                 .file_stem()
2175                 .expect("target path must not be empty")
2176                 .to_str()
2177                 .expect("target path must be valid unicode"),
2178         }
2179     }
2180
2181     /// Returns an extended string triple for this target.
2182     ///
2183     /// If this target is a path, a hash of the path is appended to the triple returned
2184     /// by `triple()`.
2185     pub fn debug_triple(&self) -> String {
2186         use std::collections::hash_map::DefaultHasher;
2187         use std::hash::{Hash, Hasher};
2188
2189         let triple = self.triple();
2190         if let TargetTriple::TargetPath(ref path) = *self {
2191             let mut hasher = DefaultHasher::new();
2192             path.hash(&mut hasher);
2193             let hash = hasher.finish();
2194             format!("{}-{}", triple, hash)
2195         } else {
2196             triple.to_owned()
2197         }
2198     }
2199 }
2200
2201 impl fmt::Display for TargetTriple {
2202     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2203         write!(f, "{}", self.debug_triple())
2204     }
2205 }