]> git.lizzy.rs Git - rust.git/blob - src/librustc_back/target/mod.rs
Use question_mark feature in librustc_back.
[rust.git] / src / librustc_back / target / mod.rs
1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
12 //!
13 //! Rust targets a wide variety of usecases, and in the interest of flexibility,
14 //! allows new target triples to be defined in configuration files. Most users
15 //! will not need to care about these, but this is invaluable when porting Rust
16 //! to a new platform, and allows for an unprecedented level of control over how
17 //! the compiler works.
18 //!
19 //! # Using custom targets
20 //!
21 //! A target triple, as passed via `rustc --target=TRIPLE`, will first be
22 //! compared against the list of built-in targets. This is to ease distributing
23 //! rustc (no need for configuration files) and also to hold these built-in
24 //! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
25 //! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
26 //! will be loaded as the target configuration. If the file does not exist,
27 //! rustc will search each directory in the environment variable
28 //! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
29 //! be loaded. If no file is found in any of those directories, a fatal error
30 //! will be given.
31 //!
32 //! Projects defining their own targets should use
33 //! `--target=path/to/my-awesome-platform.json` instead of adding to
34 //! `RUST_TARGET_PATH`.
35 //!
36 //! # Defining a new target
37 //!
38 //! Targets are defined using [JSON](http://json.org/). The `Target` struct in
39 //! this module defines the format the JSON file should take, though each
40 //! underscore in the field names should be replaced with a hyphen (`-`) in the
41 //! JSON file. Some fields are required in every target specification, such as
42 //! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
43 //! `arch`, and `os`. In general, options passed to rustc with `-C` override
44 //! the target's settings, though `target-feature` and `link-args` will *add*
45 //! to the list specified by the target, rather than replace.
46
47 use serialize::json::{Json, ToJson};
48 use std::collections::BTreeMap;
49 use std::default::Default;
50 use std::io::prelude::*;
51 use syntax::abi::Abi;
52
53 mod android_base;
54 mod apple_base;
55 mod apple_ios_base;
56 mod bitrig_base;
57 mod dragonfly_base;
58 mod freebsd_base;
59 mod linux_base;
60 mod linux_musl_base;
61 mod openbsd_base;
62 mod netbsd_base;
63 mod solaris_base;
64 mod windows_base;
65 mod windows_msvc_base;
66
67 pub type TargetResult = Result<Target, String>;
68
69 macro_rules! supported_targets {
70     ( $(($triple:expr, $module:ident)),+ ) => (
71         $(mod $module;)*
72
73         /// List of supported targets
74         const TARGETS: &'static [&'static str] = &[$($triple),*];
75
76         fn load_specific(target: &str) -> TargetResult {
77             match target {
78                 $(
79                     $triple => {
80                         let mut t = $module::target()?;
81                         t.options.is_builtin = true;
82
83                         // round-trip through the JSON parser to ensure at
84                         // run-time that the parser works correctly
85                         t = Target::from_json(t.to_json())?;
86                         debug!("Got builtin target: {:?}", t);
87                         Ok(t)
88                     },
89                 )+
90                 _ => Err(format!("Unable to find target: {}", target))
91             }
92         }
93
94         pub fn get_targets() -> Box<Iterator<Item=String>> {
95             Box::new(TARGETS.iter().filter_map(|t| -> Option<String> {
96                 load_specific(t)
97                     .and(Ok(t.to_string()))
98                     .ok()
99             }))
100         }
101
102         #[cfg(test)]
103         mod test_json_encode_decode {
104             use serialize::json::ToJson;
105             use super::Target;
106             $(use super::$module;)*
107
108             $(
109                 #[test]
110                 fn $module() {
111                     // Grab the TargetResult struct. If we successfully retrieved
112                     // a Target, then the test JSON encoding/decoding can run for this
113                     // Target on this testing platform (i.e., checking the iOS targets
114                     // only on a Mac test platform).
115                     let _ = $module::target().map(|original| {
116                         let as_json = original.to_json();
117                         let parsed = Target::from_json(as_json).unwrap();
118                         assert_eq!(original, parsed);
119                     });
120                 }
121             )*
122         }
123     )
124 }
125
126 supported_targets! {
127     ("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
128     ("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
129     ("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
130     ("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
131     ("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
132     ("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
133     ("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
134     ("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
135     ("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
136     ("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
137     ("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
138     ("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
139     ("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
140     ("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
141     ("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
142     ("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
143     ("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
144     ("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
145     ("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
146     ("i686-unknown-linux-musl", i686_unknown_linux_musl),
147     ("mips-unknown-linux-musl", mips_unknown_linux_musl),
148     ("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
149     ("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
150     ("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
151
152     ("i686-linux-android", i686_linux_android),
153     ("arm-linux-androideabi", arm_linux_androideabi),
154     ("armv7-linux-androideabi", armv7_linux_androideabi),
155     ("aarch64-linux-android", aarch64_linux_android),
156
157     ("i686-unknown-freebsd", i686_unknown_freebsd),
158     ("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
159
160     ("i686-unknown-dragonfly", i686_unknown_dragonfly),
161     ("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
162
163     ("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
164     ("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
165     ("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
166     ("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
167
168     ("x86_64-apple-darwin", x86_64_apple_darwin),
169     ("i686-apple-darwin", i686_apple_darwin),
170
171     ("i386-apple-ios", i386_apple_ios),
172     ("x86_64-apple-ios", x86_64_apple_ios),
173     ("aarch64-apple-ios", aarch64_apple_ios),
174     ("armv7-apple-ios", armv7_apple_ios),
175     ("armv7s-apple-ios", armv7s_apple_ios),
176
177     ("x86_64-sun-solaris", x86_64_sun_solaris),
178
179     ("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
180     ("i686-pc-windows-gnu", i686_pc_windows_gnu),
181
182     ("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
183     ("i686-pc-windows-msvc", i686_pc_windows_msvc),
184     ("i586-pc-windows-msvc", i586_pc_windows_msvc),
185
186     ("le32-unknown-nacl", le32_unknown_nacl),
187     ("asmjs-unknown-emscripten", asmjs_unknown_emscripten)
188 }
189
190 /// Everything `rustc` knows about how to compile for a specific target.
191 ///
192 /// Every field here must be specified, and has no default value.
193 #[derive(PartialEq, Clone, Debug)]
194 pub struct Target {
195     /// Target triple to pass to LLVM.
196     pub llvm_target: String,
197     /// String to use as the `target_endian` `cfg` variable.
198     pub target_endian: String,
199     /// String to use as the `target_pointer_width` `cfg` variable.
200     pub target_pointer_width: String,
201     /// OS name to use for conditional compilation.
202     pub target_os: String,
203     /// Environment name to use for conditional compilation.
204     pub target_env: String,
205     /// Vendor name to use for conditional compilation.
206     pub target_vendor: String,
207     /// Architecture to use for ABI considerations. Valid options: "x86",
208     /// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
209     pub arch: String,
210     /// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
211     pub data_layout: String,
212     /// Optional settings with defaults.
213     pub options: TargetOptions,
214 }
215
216 /// Optional aspects of a target specification.
217 ///
218 /// This has an implementation of `Default`, see each field for what the default is. In general,
219 /// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
220 #[derive(PartialEq, Clone, Debug)]
221 pub struct TargetOptions {
222     /// Whether the target is built-in or loaded from a custom target specification.
223     pub is_builtin: bool,
224
225     /// Linker to invoke. Defaults to "cc".
226     pub linker: String,
227     /// Archive utility to use when managing archives. Defaults to "ar".
228     pub ar: String,
229
230     /// Linker arguments that are unconditionally passed *before* any
231     /// user-defined libraries.
232     pub pre_link_args: Vec<String>,
233     /// Objects to link before all others, always found within the
234     /// sysroot folder.
235     pub pre_link_objects_exe: Vec<String>, // ... when linking an executable
236     pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
237     /// Linker arguments that are unconditionally passed after any
238     /// user-defined but before post_link_objects.  Standard platform
239     /// libraries that should be always be linked to, usually go here.
240     pub late_link_args: Vec<String>,
241     /// Objects to link after all others, always found within the
242     /// sysroot folder.
243     pub post_link_objects: Vec<String>,
244     /// Linker arguments that are unconditionally passed *after* any
245     /// user-defined libraries.
246     pub post_link_args: Vec<String>,
247
248     /// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
249     /// to "generic".
250     pub cpu: String,
251     /// Default target features to pass to LLVM. These features will *always* be
252     /// passed, and cannot be disabled even via `-C`. Corresponds to `llc
253     /// -mattr=$features`.
254     pub features: String,
255     /// Whether dynamic linking is available on this target. Defaults to false.
256     pub dynamic_linking: bool,
257     /// Whether executables are available on this target. iOS, for example, only allows static
258     /// libraries. Defaults to false.
259     pub executables: bool,
260     /// Relocation model to use in object file. Corresponds to `llc
261     /// -relocation-model=$relocation_model`. Defaults to "pic".
262     pub relocation_model: String,
263     /// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
264     pub code_model: String,
265     /// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
266     pub disable_redzone: bool,
267     /// Eliminate frame pointers from stack frames if possible. Defaults to true.
268     pub eliminate_frame_pointer: bool,
269     /// Emit each function in its own section. Defaults to true.
270     pub function_sections: bool,
271     /// String to prepend to the name of every dynamic library. Defaults to "lib".
272     pub dll_prefix: String,
273     /// String to append to the name of every dynamic library. Defaults to ".so".
274     pub dll_suffix: String,
275     /// String to append to the name of every executable.
276     pub exe_suffix: String,
277     /// String to prepend to the name of every static library. Defaults to "lib".
278     pub staticlib_prefix: String,
279     /// String to append to the name of every static library. Defaults to ".a".
280     pub staticlib_suffix: String,
281     /// OS family to use for conditional compilation. Valid options: "unix", "windows".
282     pub target_family: Option<String>,
283     /// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
284     /// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
285     pub is_like_osx: bool,
286     /// Whether the target toolchain is like Solaris's.
287     /// Only useful for compiling against Illumos/Solaris,
288     /// as they have a different set of linker flags. Defaults to false.
289     pub is_like_solaris: bool,
290     /// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
291     /// only really used for figuring out how to find libraries, since Windows uses its own
292     /// library naming convention. Defaults to false.
293     pub is_like_windows: bool,
294     pub is_like_msvc: bool,
295     /// Whether the target toolchain is like Android's. Only useful for compiling against Android.
296     /// Defaults to false.
297     pub is_like_android: bool,
298     /// Whether the linker support GNU-like arguments such as -O. Defaults to false.
299     pub linker_is_gnu: bool,
300     /// The MinGW toolchain has a known issue that prevents it from correctly
301     /// handling COFF object files with more than 2^15 sections. Since each weak
302     /// symbol needs its own COMDAT section, weak linkage implies a large
303     /// number sections that easily exceeds the given limit for larger
304     /// codebases. Consequently we want a way to disallow weak linkage on some
305     /// platforms.
306     pub allows_weak_linkage: bool,
307     /// Whether the linker support rpaths or not. Defaults to false.
308     pub has_rpath: bool,
309     /// Whether to disable linking to compiler-rt. Defaults to false, as LLVM
310     /// will emit references to the functions that compiler-rt provides.
311     pub no_compiler_rt: bool,
312     /// Whether to disable linking to the default libraries, typically corresponds
313     /// to `-nodefaultlibs`. Defaults to true.
314     pub no_default_libraries: bool,
315     /// Dynamically linked executables can be compiled as position independent
316     /// if the default relocation model of position independent code is not
317     /// changed. This is a requirement to take advantage of ASLR, as otherwise
318     /// the functions in the executable are not randomized and can be used
319     /// during an exploit of a vulnerability in any code.
320     pub position_independent_executables: bool,
321     /// Format that archives should be emitted in. This affects whether we use
322     /// LLVM to assemble an archive or fall back to the system linker, and
323     /// currently only "gnu" is used to fall into LLVM. Unknown strings cause
324     /// the system linker to be used.
325     pub archive_format: String,
326     /// Is asm!() allowed? Defaults to true.
327     pub allow_asm: bool,
328     /// Whether the target uses a custom unwind resumption routine.
329     /// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
330     /// defined in libgcc.  If this option is enabled, the target must provide
331     /// `eh_unwind_resume` lang item.
332     pub custom_unwind_resume: bool,
333
334     /// Default crate for allocation symbols to link against
335     pub lib_allocation_crate: String,
336     pub exe_allocation_crate: String,
337
338     /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
339     /// this target.
340     pub has_elf_tls: bool,
341     // This is mainly for easy compatibility with emscripten.
342     // If we give emcc .o files that are actually .bc files it
343     // will 'just work'.
344     pub obj_is_bitcode: bool,
345
346     /// Maximum integer size in bits that this target can perform atomic
347     /// operations on.
348     pub max_atomic_width: u64,
349 }
350
351 impl Default for TargetOptions {
352     /// Create a set of "sane defaults" for any target. This is still
353     /// incomplete, and if used for compilation, will certainly not work.
354     fn default() -> TargetOptions {
355         TargetOptions {
356             is_builtin: false,
357             linker: option_env!("CFG_DEFAULT_LINKER").unwrap_or("cc").to_string(),
358             ar: option_env!("CFG_DEFAULT_AR").unwrap_or("ar").to_string(),
359             pre_link_args: Vec::new(),
360             post_link_args: Vec::new(),
361             cpu: "generic".to_string(),
362             features: "".to_string(),
363             dynamic_linking: false,
364             executables: false,
365             relocation_model: "pic".to_string(),
366             code_model: "default".to_string(),
367             disable_redzone: false,
368             eliminate_frame_pointer: true,
369             function_sections: true,
370             dll_prefix: "lib".to_string(),
371             dll_suffix: ".so".to_string(),
372             exe_suffix: "".to_string(),
373             staticlib_prefix: "lib".to_string(),
374             staticlib_suffix: ".a".to_string(),
375             target_family: None,
376             is_like_osx: false,
377             is_like_solaris: false,
378             is_like_windows: false,
379             is_like_android: false,
380             is_like_msvc: false,
381             linker_is_gnu: false,
382             allows_weak_linkage: true,
383             has_rpath: false,
384             no_compiler_rt: false,
385             no_default_libraries: true,
386             position_independent_executables: false,
387             pre_link_objects_exe: Vec::new(),
388             pre_link_objects_dll: Vec::new(),
389             post_link_objects: Vec::new(),
390             late_link_args: Vec::new(),
391             archive_format: "gnu".to_string(),
392             custom_unwind_resume: false,
393             lib_allocation_crate: "alloc_system".to_string(),
394             exe_allocation_crate: "alloc_system".to_string(),
395             allow_asm: true,
396             has_elf_tls: false,
397             obj_is_bitcode: false,
398             max_atomic_width: 0,
399         }
400     }
401 }
402
403 impl Target {
404     /// Given a function ABI, turn "System" into the correct ABI for this target.
405     pub fn adjust_abi(&self, abi: Abi) -> Abi {
406         match abi {
407             Abi::System => {
408                 if self.options.is_like_windows && self.arch == "x86" {
409                     Abi::Stdcall
410                 } else {
411                     Abi::C
412                 }
413             },
414             abi => abi
415         }
416     }
417
418     /// Load a target descriptor from a JSON object.
419     pub fn from_json(obj: Json) -> TargetResult {
420         // While ugly, this code must remain this way to retain
421         // compatibility with existing JSON fields and the internal
422         // expected naming of the Target and TargetOptions structs.
423         // To ensure compatibility is retained, the built-in targets
424         // are round-tripped through this code to catch cases where
425         // the JSON parser is not updated to match the structs.
426
427         let get_req_field = |name: &str| {
428             match obj.find(name)
429                      .map(|s| s.as_string())
430                      .and_then(|os| os.map(|s| s.to_string())) {
431                 Some(val) => Ok(val),
432                 None => {
433                     return Err(format!("Field {} in target specification is required", name))
434                 }
435             }
436         };
437
438         let get_opt_field = |name: &str, default: &str| {
439             obj.find(name).and_then(|s| s.as_string())
440                .map(|s| s.to_string())
441                .unwrap_or(default.to_string())
442         };
443
444         let mut base = Target {
445             llvm_target: get_req_field("llvm-target")?,
446             target_endian: get_req_field("target-endian")?,
447             target_pointer_width: get_req_field("target-pointer-width")?,
448             data_layout: get_req_field("data-layout")?,
449             arch: get_req_field("arch")?,
450             target_os: get_req_field("os")?,
451             target_env: get_opt_field("env", ""),
452             target_vendor: get_opt_field("vendor", "unknown"),
453             options: Default::default(),
454         };
455
456         // Default max-atomic-width to target-pointer-width
457         base.options.max_atomic_width = base.target_pointer_width.parse().unwrap();
458
459         macro_rules! key {
460             ($key_name:ident) => ( {
461                 let name = (stringify!($key_name)).replace("_", "-");
462                 obj.find(&name[..]).map(|o| o.as_string()
463                                     .map(|s| base.options.$key_name = s.to_string()));
464             } );
465             ($key_name:ident, bool) => ( {
466                 let name = (stringify!($key_name)).replace("_", "-");
467                 obj.find(&name[..])
468                     .map(|o| o.as_boolean()
469                          .map(|s| base.options.$key_name = s));
470             } );
471             ($key_name:ident, u64) => ( {
472                 let name = (stringify!($key_name)).replace("_", "-");
473                 obj.find(&name[..])
474                     .map(|o| o.as_u64()
475                          .map(|s| base.options.$key_name = s));
476             } );
477             ($key_name:ident, list) => ( {
478                 let name = (stringify!($key_name)).replace("_", "-");
479                 obj.find(&name[..]).map(|o| o.as_array()
480                     .map(|v| base.options.$key_name = v.iter()
481                         .map(|a| a.as_string().unwrap().to_string()).collect()
482                         )
483                     );
484             } );
485             ($key_name:ident, optional) => ( {
486                 let name = (stringify!($key_name)).replace("_", "-");
487                 if let Some(o) = obj.find(&name[..]) {
488                     base.options.$key_name = o
489                         .as_string()
490                         .map(|s| s.to_string() );
491                 }
492             } );
493         }
494
495         key!(is_builtin, bool);
496         key!(linker);
497         key!(ar);
498         key!(pre_link_args, list);
499         key!(pre_link_objects_exe, list);
500         key!(pre_link_objects_dll, list);
501         key!(late_link_args, list);
502         key!(post_link_objects, list);
503         key!(post_link_args, list);
504         key!(cpu);
505         key!(features);
506         key!(dynamic_linking, bool);
507         key!(executables, bool);
508         key!(relocation_model);
509         key!(code_model);
510         key!(disable_redzone, bool);
511         key!(eliminate_frame_pointer, bool);
512         key!(function_sections, bool);
513         key!(dll_prefix);
514         key!(dll_suffix);
515         key!(exe_suffix);
516         key!(staticlib_prefix);
517         key!(staticlib_suffix);
518         key!(target_family, optional);
519         key!(is_like_osx, bool);
520         key!(is_like_solaris, bool);
521         key!(is_like_windows, bool);
522         key!(is_like_msvc, bool);
523         key!(is_like_android, bool);
524         key!(linker_is_gnu, bool);
525         key!(allows_weak_linkage, bool);
526         key!(has_rpath, bool);
527         key!(no_compiler_rt, bool);
528         key!(no_default_libraries, bool);
529         key!(position_independent_executables, bool);
530         key!(archive_format);
531         key!(allow_asm, bool);
532         key!(custom_unwind_resume, bool);
533         key!(lib_allocation_crate);
534         key!(exe_allocation_crate);
535         key!(has_elf_tls, bool);
536         key!(obj_is_bitcode, bool);
537         key!(max_atomic_width, u64);
538
539         Ok(base)
540     }
541
542     /// Search RUST_TARGET_PATH for a JSON file specifying the given target
543     /// triple. Note that it could also just be a bare filename already, so also
544     /// check for that. If one of the hardcoded targets we know about, just
545     /// return it directly.
546     ///
547     /// The error string could come from any of the APIs called, including
548     /// filesystem access and JSON decoding.
549     pub fn search(target: &str) -> Result<Target, String> {
550         use std::env;
551         use std::ffi::OsString;
552         use std::fs::File;
553         use std::path::{Path, PathBuf};
554         use serialize::json;
555
556         fn load_file(path: &Path) -> Result<Target, String> {
557             let mut f = File::open(path).map_err(|e| e.to_string())?;
558             let mut contents = Vec::new();
559             f.read_to_end(&mut contents).map_err(|e| e.to_string())?;
560             let obj = json::from_reader(&mut &contents[..])
561                            .map_err(|e| e.to_string())?;
562             Target::from_json(obj)
563         }
564
565         if let Ok(t) = load_specific(target) {
566             return Ok(t)
567         }
568
569         let path = Path::new(target);
570
571         if path.is_file() {
572             return load_file(&path);
573         }
574
575         let path = {
576             let mut target = target.to_string();
577             target.push_str(".json");
578             PathBuf::from(target)
579         };
580
581         let target_path = env::var_os("RUST_TARGET_PATH")
582                               .unwrap_or(OsString::new());
583
584         // FIXME 16351: add a sane default search path?
585
586         for dir in env::split_paths(&target_path) {
587             let p =  dir.join(&path);
588             if p.is_file() {
589                 return load_file(&p);
590             }
591         }
592
593         Err(format!("Could not find specification for target {:?}", target))
594     }
595 }
596
597 impl ToJson for Target {
598     fn to_json(&self) -> Json {
599         let mut d = BTreeMap::new();
600         let default: TargetOptions = Default::default();
601
602         macro_rules! target_val {
603             ($attr:ident) => ( {
604                 let name = (stringify!($attr)).replace("_", "-");
605                 d.insert(name.to_string(), self.$attr.to_json());
606             } );
607             ($attr:ident, $key_name:expr) => ( {
608                 let name = $key_name;
609                 d.insert(name.to_string(), self.$attr.to_json());
610             } );
611         }
612
613         macro_rules! target_option_val {
614             ($attr:ident) => ( {
615                 let name = (stringify!($attr)).replace("_", "-");
616                 if default.$attr != self.options.$attr {
617                     d.insert(name.to_string(), self.options.$attr.to_json());
618                 }
619             } );
620             ($attr:ident, $key_name:expr) => ( {
621                 let name = $key_name;
622                 if default.$attr != self.options.$attr {
623                     d.insert(name.to_string(), self.options.$attr.to_json());
624                 }
625             } );
626         }
627
628         target_val!(llvm_target);
629         target_val!(target_endian);
630         target_val!(target_pointer_width);
631         target_val!(arch);
632         target_val!(target_os, "os");
633         target_val!(target_env, "env");
634         target_val!(target_vendor, "vendor");
635         target_val!(arch);
636         target_val!(data_layout);
637
638         target_option_val!(is_builtin);
639         target_option_val!(linker);
640         target_option_val!(ar);
641         target_option_val!(pre_link_args);
642         target_option_val!(pre_link_objects_exe);
643         target_option_val!(pre_link_objects_dll);
644         target_option_val!(late_link_args);
645         target_option_val!(post_link_objects);
646         target_option_val!(post_link_args);
647         target_option_val!(cpu);
648         target_option_val!(features);
649         target_option_val!(dynamic_linking);
650         target_option_val!(executables);
651         target_option_val!(relocation_model);
652         target_option_val!(code_model);
653         target_option_val!(disable_redzone);
654         target_option_val!(eliminate_frame_pointer);
655         target_option_val!(function_sections);
656         target_option_val!(dll_prefix);
657         target_option_val!(dll_suffix);
658         target_option_val!(exe_suffix);
659         target_option_val!(staticlib_prefix);
660         target_option_val!(staticlib_suffix);
661         target_option_val!(target_family);
662         target_option_val!(is_like_osx);
663         target_option_val!(is_like_solaris);
664         target_option_val!(is_like_windows);
665         target_option_val!(is_like_msvc);
666         target_option_val!(is_like_android);
667         target_option_val!(linker_is_gnu);
668         target_option_val!(allows_weak_linkage);
669         target_option_val!(has_rpath);
670         target_option_val!(no_compiler_rt);
671         target_option_val!(no_default_libraries);
672         target_option_val!(position_independent_executables);
673         target_option_val!(archive_format);
674         target_option_val!(allow_asm);
675         target_option_val!(custom_unwind_resume);
676         target_option_val!(lib_allocation_crate);
677         target_option_val!(exe_allocation_crate);
678         target_option_val!(has_elf_tls);
679         target_option_val!(obj_is_bitcode);
680         target_option_val!(max_atomic_width);
681
682         Json::Object(d)
683     }
684 }
685
686 fn maybe_jemalloc() -> String {
687     if cfg!(feature = "jemalloc") {
688         "alloc_jemalloc".to_string()
689     } else {
690         "alloc_system".to_string()
691     }
692 }