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