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