]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/native.rs
rustbuild: allow configuring llvm version suffix
[rust.git] / src / bootstrap / native.rs
1 // Copyright 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 //! Compilation of native dependencies like LLVM.
12 //!
13 //! Native projects like LLVM unfortunately aren't suited just yet for
14 //! compilation in build scripts that Cargo has. This is because the
15 //! compilation takes a *very* long time but also because we don't want to
16 //! compile LLVM 3 times as part of a normal bootstrap (we want it cached).
17 //!
18 //! LLVM and compiler-rt are essentially just wired up to everything else to
19 //! ensure that they're always in place if needed.
20
21 use std::env;
22 use std::ffi::OsString;
23 use std::fs::{self, File};
24 use std::io::{Read, Write};
25 use std::path::{Path, PathBuf};
26 use std::process::Command;
27
28 use build_helper::output;
29 use cmake;
30 use cc;
31
32 use util::{self, exe};
33 use build_helper::up_to_date;
34 use builder::{Builder, RunConfig, ShouldRun, Step};
35 use cache::Interned;
36
37 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
38 pub struct Llvm {
39     pub target: Interned<String>,
40     pub emscripten: bool,
41 }
42
43 impl Step for Llvm {
44     type Output = PathBuf; // path to llvm-config
45
46     const ONLY_HOSTS: bool = true;
47
48     fn should_run(run: ShouldRun) -> ShouldRun {
49         run.path("src/llvm").path("src/llvm-emscripten")
50     }
51
52     fn make_run(run: RunConfig) {
53         let emscripten = run.path.ends_with("llvm-emscripten");
54         run.builder.ensure(Llvm {
55             target: run.target,
56             emscripten,
57         });
58     }
59
60     /// Compile LLVM for `target`.
61     fn run(self, builder: &Builder) -> PathBuf {
62         let target = self.target;
63         let emscripten = self.emscripten;
64
65         // If we're using a custom LLVM bail out here, but we can only use a
66         // custom LLVM for the build triple.
67         if !self.emscripten {
68             if let Some(config) = builder.config.target_config.get(&target) {
69                 if let Some(ref s) = config.llvm_config {
70                     check_llvm_version(builder, s);
71                     return s.to_path_buf()
72                 }
73             }
74         }
75
76         let rebuild_trigger = builder.src.join("src/rustllvm/llvm-rebuild-trigger");
77         let mut rebuild_trigger_contents = String::new();
78         t!(t!(File::open(&rebuild_trigger)).read_to_string(&mut rebuild_trigger_contents));
79
80         let (out_dir, llvm_config_ret_dir) = if emscripten {
81             let dir = builder.emscripten_llvm_out(target);
82             let config_dir = dir.join("bin");
83             (dir, config_dir)
84         } else {
85             let mut dir = builder.llvm_out(builder.config.build);
86             if !builder.config.build.contains("msvc") || builder.config.ninja {
87                 dir.push("build");
88             }
89             (builder.llvm_out(target), dir.join("bin"))
90         };
91         let done_stamp = out_dir.join("llvm-finished-building");
92         let build_llvm_config = llvm_config_ret_dir
93             .join(exe("llvm-config", &*builder.config.build));
94         if done_stamp.exists() {
95             let mut done_contents = String::new();
96             t!(t!(File::open(&done_stamp)).read_to_string(&mut done_contents));
97
98             // If LLVM was already built previously and contents of the rebuild-trigger file
99             // didn't change from the previous build, then no action is required.
100             if done_contents == rebuild_trigger_contents {
101                 return build_llvm_config
102             }
103         }
104
105         let _folder = builder.fold_output(|| "llvm");
106         let descriptor = if emscripten { "Emscripten " } else { "" };
107         builder.info(&format!("Building {}LLVM for {}", descriptor, target));
108         let _time = util::timeit(&builder);
109         t!(fs::create_dir_all(&out_dir));
110
111         // http://llvm.org/docs/CMake.html
112         let root = if self.emscripten { "src/llvm-emscripten" } else { "src/llvm" };
113         let mut cfg = cmake::Config::new(builder.src.join(root));
114
115         let profile = match (builder.config.llvm_optimize, builder.config.llvm_release_debuginfo) {
116             (false, _) => "Debug",
117             (true, false) => "Release",
118             (true, true) => "RelWithDebInfo",
119         };
120
121         // NOTE: remember to also update `config.toml.example` when changing the
122         // defaults!
123         let llvm_targets = if self.emscripten {
124             "JSBackend"
125         } else {
126             match builder.config.llvm_targets {
127                 Some(ref s) => s,
128                 None => "X86;ARM;AArch64;Mips;PowerPC;SystemZ;MSP430;Sparc;NVPTX;Hexagon",
129             }
130         };
131
132         let llvm_exp_targets = if self.emscripten {
133             ""
134         } else {
135             &builder.config.llvm_experimental_targets[..]
136         };
137
138         let assertions = if builder.config.llvm_assertions {"ON"} else {"OFF"};
139
140         cfg.out_dir(&out_dir)
141            .profile(profile)
142            .define("LLVM_ENABLE_ASSERTIONS", assertions)
143            .define("LLVM_TARGETS_TO_BUILD", llvm_targets)
144            .define("LLVM_EXPERIMENTAL_TARGETS_TO_BUILD", llvm_exp_targets)
145            .define("LLVM_INCLUDE_EXAMPLES", "OFF")
146            .define("LLVM_INCLUDE_TESTS", "OFF")
147            .define("LLVM_INCLUDE_DOCS", "OFF")
148            .define("LLVM_INCLUDE_BENCHMARKS", "OFF")
149            .define("LLVM_ENABLE_ZLIB", "OFF")
150            .define("WITH_POLLY", "OFF")
151            .define("LLVM_ENABLE_TERMINFO", "OFF")
152            .define("LLVM_ENABLE_LIBEDIT", "OFF")
153            .define("LLVM_PARALLEL_COMPILE_JOBS", builder.jobs().to_string())
154            .define("LLVM_TARGET_ARCH", target.split('-').next().unwrap())
155            .define("LLVM_DEFAULT_TARGET_TRIPLE", target);
156
157         if builder.config.llvm_thin_lto && !emscripten {
158             cfg.define("LLVM_ENABLE_LTO", "Thin")
159                .define("LLVM_ENABLE_LLD", "ON");
160         }
161
162         // By default, LLVM will automatically find OCaml and, if it finds it,
163         // install the LLVM bindings in LLVM_OCAML_INSTALL_PATH, which defaults
164         // to /usr/bin/ocaml.
165         // This causes problem for non-root builds of Rust. Side-step the issue
166         // by setting LLVM_OCAML_INSTALL_PATH to a relative path, so it installs
167         // in the prefix.
168         cfg.define("LLVM_OCAML_INSTALL_PATH",
169             env::var_os("LLVM_OCAML_INSTALL_PATH").unwrap_or_else(|| "usr/lib/ocaml".into()));
170
171         let want_lldb = builder.config.lldb_enabled && !self.emscripten;
172
173         // This setting makes the LLVM tools link to the dynamic LLVM library,
174         // which saves both memory during parallel links and overall disk space
175         // for the tools. We don't do this on every platform as it doesn't work
176         // equally well everywhere.
177         if builder.llvm_link_tools_dynamically(target) && !emscripten {
178             cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
179         }
180
181         // For distribution we want the LLVM tools to be *statically* linked to libstdc++
182         if builder.config.llvm_tools_enabled || want_lldb {
183             if !target.contains("windows") {
184                 if target.contains("apple") {
185                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
186                 } else {
187                     cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
188                 }
189             }
190         }
191
192         if target.contains("msvc") {
193             cfg.define("LLVM_USE_CRT_DEBUG", "MT");
194             cfg.define("LLVM_USE_CRT_RELEASE", "MT");
195             cfg.define("LLVM_USE_CRT_RELWITHDEBINFO", "MT");
196             cfg.static_crt(true);
197         }
198
199         if target.starts_with("i686") {
200             cfg.define("LLVM_BUILD_32_BITS", "ON");
201         }
202
203         if want_lldb {
204             cfg.define("LLVM_EXTERNAL_CLANG_SOURCE_DIR", builder.src.join("src/tools/clang"));
205             cfg.define("LLVM_EXTERNAL_LLDB_SOURCE_DIR", builder.src.join("src/tools/lldb"));
206             // For the time being, disable code signing.
207             cfg.define("LLDB_CODESIGN_IDENTITY", "");
208         } else {
209             // LLDB requires libxml2; but otherwise we want it to be disabled.
210             // See https://github.com/rust-lang/rust/pull/50104
211             cfg.define("LLVM_ENABLE_LIBXML2", "OFF");
212         }
213
214         if let Some(num_linkers) = builder.config.llvm_link_jobs {
215             if num_linkers > 0 {
216                 cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string());
217             }
218         }
219
220         // http://llvm.org/docs/HowToCrossCompileLLVM.html
221         if target != builder.config.build && !emscripten {
222             builder.ensure(Llvm {
223                 target: builder.config.build,
224                 emscripten: false,
225             });
226             // FIXME: if the llvm root for the build triple is overridden then we
227             //        should use llvm-tblgen from there, also should verify that it
228             //        actually exists most of the time in normal installs of LLVM.
229             let host = builder.llvm_out(builder.config.build).join("bin/llvm-tblgen");
230             cfg.define("CMAKE_CROSSCOMPILING", "True")
231                .define("LLVM_TABLEGEN", &host);
232
233             if target.contains("netbsd") {
234                cfg.define("CMAKE_SYSTEM_NAME", "NetBSD");
235             } else if target.contains("freebsd") {
236                cfg.define("CMAKE_SYSTEM_NAME", "FreeBSD");
237             }
238
239             cfg.define("LLVM_NATIVE_BUILD", builder.llvm_out(builder.config.build).join("build"));
240         }
241
242         if let Some(ref suffix) = builder.config.llvm_version_suffix {
243             cfg.define("LLVM_VERSION_SUFFIX", suffix);
244         }
245
246         if let Some(ref python) = builder.config.python {
247             cfg.define("PYTHON_EXECUTABLE", python);
248         }
249
250         configure_cmake(builder, target, &mut cfg, false);
251
252         // FIXME: we don't actually need to build all LLVM tools and all LLVM
253         //        libraries here, e.g. we just want a few components and a few
254         //        tools. Figure out how to filter them down and only build the right
255         //        tools and libs on all platforms.
256
257         if builder.config.dry_run {
258             return build_llvm_config;
259         }
260
261         cfg.build();
262
263         t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
264
265         build_llvm_config
266     }
267 }
268
269 fn check_llvm_version(builder: &Builder, llvm_config: &Path) {
270     if !builder.config.llvm_version_check {
271         return
272     }
273
274     if builder.config.dry_run {
275         return;
276     }
277
278     let mut cmd = Command::new(llvm_config);
279     let version = output(cmd.arg("--version"));
280     let mut parts = version.split('.').take(2)
281         .filter_map(|s| s.parse::<u32>().ok());
282     if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) {
283         if major >= 5 {
284             return
285         }
286     }
287     panic!("\n\nbad LLVM version: {}, need >=5.0\n\n", version)
288 }
289
290 fn configure_cmake(builder: &Builder,
291                    target: Interned<String>,
292                    cfg: &mut cmake::Config,
293                    building_dist_binaries: bool) {
294     if builder.config.ninja {
295         cfg.generator("Ninja");
296     }
297     cfg.target(&target)
298        .host(&builder.config.build);
299
300     let sanitize_cc = |cc: &Path| {
301         if target.contains("msvc") {
302             OsString::from(cc.to_str().unwrap().replace("\\", "/"))
303         } else {
304             cc.as_os_str().to_owned()
305         }
306     };
307
308     // MSVC with CMake uses msbuild by default which doesn't respect these
309     // vars that we'd otherwise configure. In that case we just skip this
310     // entirely.
311     if target.contains("msvc") && !builder.config.ninja {
312         return
313     }
314
315     let (cc, cxx) = match builder.config.llvm_clang_cl {
316         Some(ref cl) => (cl.as_ref(), cl.as_ref()),
317         None => (builder.cc(target), builder.cxx(target).unwrap()),
318     };
319
320     // Handle msvc + ninja + ccache specially (this is what the bots use)
321     if target.contains("msvc") &&
322        builder.config.ninja &&
323        builder.config.ccache.is_some()
324     {
325        let mut wrap_cc = env::current_exe().expect("failed to get cwd");
326        wrap_cc.set_file_name("sccache-plus-cl.exe");
327
328        cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc))
329           .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc));
330        cfg.env("SCCACHE_PATH",
331                builder.config.ccache.as_ref().unwrap())
332           .env("SCCACHE_TARGET", target)
333           .env("SCCACHE_CC", &cc)
334           .env("SCCACHE_CXX", &cxx);
335
336        // Building LLVM on MSVC can be a little ludicrous at times. We're so far
337        // off the beaten path here that I'm not really sure this is even half
338        // supported any more. Here we're trying to:
339        //
340        // * Build LLVM on MSVC
341        // * Build LLVM with `clang-cl` instead of `cl.exe`
342        // * Build a project with `sccache`
343        // * Build for 32-bit as well
344        // * Build with Ninja
345        //
346        // For `cl.exe` there are different binaries to compile 32/64 bit which
347        // we use but for `clang-cl` there's only one which internally
348        // multiplexes via flags. As a result it appears that CMake's detection
349        // of a compiler's architecture and such on MSVC **doesn't** pass any
350        // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we
351        // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which
352        // definitely causes problems since all the env vars are pointing to
353        // 32-bit libraries.
354        //
355        // To hack aroudn this... again... we pass an argument that's
356        // unconditionally passed in the sccache shim. This'll get CMake to
357        // correctly diagnose it's doing a 32-bit compilation and LLVM will
358        // internally configure itself appropriately.
359        if builder.config.llvm_clang_cl.is_some() && target.contains("i686") {
360            cfg.env("SCCACHE_EXTRA_ARGS", "-m32");
361        }
362
363     // If ccache is configured we inform the build a little differently hwo
364     // to invoke ccache while also invoking our compilers.
365     } else if let Some(ref ccache) = builder.config.ccache {
366        cfg.define("CMAKE_C_COMPILER", ccache)
367           .define("CMAKE_C_COMPILER_ARG1", sanitize_cc(cc))
368           .define("CMAKE_CXX_COMPILER", ccache)
369           .define("CMAKE_CXX_COMPILER_ARG1", sanitize_cc(cxx));
370     } else {
371        cfg.define("CMAKE_C_COMPILER", sanitize_cc(cc))
372           .define("CMAKE_CXX_COMPILER", sanitize_cc(cxx));
373     }
374
375     cfg.build_arg("-j").build_arg(builder.jobs().to_string());
376     cfg.define("CMAKE_C_FLAGS", builder.cflags(target).join(" "));
377     let mut cxxflags = builder.cflags(target).join(" ");
378     if building_dist_binaries {
379         if builder.config.llvm_static_stdcpp && !target.contains("windows") {
380             cxxflags.push_str(" -static-libstdc++");
381         }
382     }
383     cfg.define("CMAKE_CXX_FLAGS", cxxflags);
384     if let Some(ar) = builder.ar(target) {
385         if ar.is_absolute() {
386             // LLVM build breaks if `CMAKE_AR` is a relative path, for some reason it
387             // tries to resolve this path in the LLVM build directory.
388             cfg.define("CMAKE_AR", sanitize_cc(ar));
389         }
390     }
391
392     if let Some(ranlib) = builder.ranlib(target) {
393         if ranlib.is_absolute() {
394             // LLVM build breaks if `CMAKE_RANLIB` is a relative path, for some reason it
395             // tries to resolve this path in the LLVM build directory.
396             cfg.define("CMAKE_RANLIB", sanitize_cc(ranlib));
397         }
398     }
399
400     if env::var_os("SCCACHE_ERROR_LOG").is_some() {
401         cfg.env("RUST_LOG", "sccache=warn");
402     }
403 }
404
405 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
406 pub struct Lld {
407     pub target: Interned<String>,
408 }
409
410 impl Step for Lld {
411     type Output = PathBuf;
412     const ONLY_HOSTS: bool = true;
413
414     fn should_run(run: ShouldRun) -> ShouldRun {
415         run.path("src/tools/lld")
416     }
417
418     fn make_run(run: RunConfig) {
419         run.builder.ensure(Lld { target: run.target });
420     }
421
422     /// Compile LLVM for `target`.
423     fn run(self, builder: &Builder) -> PathBuf {
424         if builder.config.dry_run {
425             return PathBuf::from("lld-out-dir-test-gen");
426         }
427         let target = self.target;
428
429         let llvm_config = builder.ensure(Llvm {
430             target: self.target,
431             emscripten: false,
432         });
433
434         let out_dir = builder.lld_out(target);
435         let done_stamp = out_dir.join("lld-finished-building");
436         if done_stamp.exists() {
437             return out_dir
438         }
439
440         let _folder = builder.fold_output(|| "lld");
441         builder.info(&format!("Building LLD for {}", target));
442         let _time = util::timeit(&builder);
443         t!(fs::create_dir_all(&out_dir));
444
445         let mut cfg = cmake::Config::new(builder.src.join("src/tools/lld"));
446         configure_cmake(builder, target, &mut cfg, true);
447
448         // This is an awful, awful hack. Discovered when we migrated to using
449         // clang-cl to compile LLVM/LLD it turns out that LLD, when built out of
450         // tree, will execute `llvm-config --cmakedir` and then tell CMake about
451         // that directory for later processing. Unfortunately if this path has
452         // forward slashes in it (which it basically always does on Windows)
453         // then CMake will hit a syntax error later on as... something isn't
454         // escaped it seems?
455         //
456         // Instead of attempting to fix this problem in upstream CMake and/or
457         // LLVM/LLD we just hack around it here. This thin wrapper will take the
458         // output from llvm-config and replace all instances of `\` with `/` to
459         // ensure we don't hit the same bugs with escaping. It means that you
460         // can't build on a system where your paths require `\` on Windows, but
461         // there's probably a lot of reasons you can't do that other than this.
462         let llvm_config_shim = env::current_exe()
463             .unwrap()
464             .with_file_name("llvm-config-wrapper");
465         cfg.out_dir(&out_dir)
466            .profile("Release")
467            .env("LLVM_CONFIG_REAL", llvm_config)
468            .define("LLVM_CONFIG_PATH", llvm_config_shim)
469            .define("LLVM_INCLUDE_TESTS", "OFF");
470
471         cfg.build();
472
473         t!(File::create(&done_stamp));
474         out_dir
475     }
476 }
477
478 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
479 pub struct TestHelpers {
480     pub target: Interned<String>,
481 }
482
483 impl Step for TestHelpers {
484     type Output = ();
485
486     fn should_run(run: ShouldRun) -> ShouldRun {
487         run.path("src/test/auxiliary/rust_test_helpers.c")
488     }
489
490     fn make_run(run: RunConfig) {
491         run.builder.ensure(TestHelpers { target: run.target })
492     }
493
494     /// Compiles the `rust_test_helpers.c` library which we used in various
495     /// `run-pass` test suites for ABI testing.
496     fn run(self, builder: &Builder) {
497         if builder.config.dry_run {
498             return;
499         }
500         let target = self.target;
501         let dst = builder.test_helpers_out(target);
502         let src = builder.src.join("src/test/auxiliary/rust_test_helpers.c");
503         if up_to_date(&src, &dst.join("librust_test_helpers.a")) {
504             return
505         }
506
507         let _folder = builder.fold_output(|| "build_test_helpers");
508         builder.info("Building test helpers");
509         t!(fs::create_dir_all(&dst));
510         let mut cfg = cc::Build::new();
511
512         // We may have found various cross-compilers a little differently due to our
513         // extra configuration, so inform gcc of these compilers. Note, though, that
514         // on MSVC we still need gcc's detection of env vars (ugh).
515         if !target.contains("msvc") {
516             if let Some(ar) = builder.ar(target) {
517                 cfg.archiver(ar);
518             }
519             cfg.compiler(builder.cc(target));
520         }
521
522         cfg.cargo_metadata(false)
523            .out_dir(&dst)
524            .target(&target)
525            .host(&builder.config.build)
526            .opt_level(0)
527            .warnings(false)
528            .debug(false)
529            .file(builder.src.join("src/test/auxiliary/rust_test_helpers.c"))
530            .compile("rust_test_helpers");
531     }
532 }
533
534 const OPENSSL_VERS: &'static str = "1.0.2n";
535 const OPENSSL_SHA256: &'static str =
536     "370babb75f278c39e0c50e8c4e7493bc0f18db6867478341a832a982fd15a8fe";
537
538 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
539 pub struct Openssl {
540     pub target: Interned<String>,
541 }
542
543 impl Step for Openssl {
544     type Output = ();
545
546     fn should_run(run: ShouldRun) -> ShouldRun {
547         run.never()
548     }
549
550     fn run(self, builder: &Builder) {
551         if builder.config.dry_run {
552             return;
553         }
554         let target = self.target;
555         let out = match builder.openssl_dir(target) {
556             Some(dir) => dir,
557             None => return,
558         };
559
560         let stamp = out.join(".stamp");
561         let mut contents = String::new();
562         drop(File::open(&stamp).and_then(|mut f| f.read_to_string(&mut contents)));
563         if contents == OPENSSL_VERS {
564             return
565         }
566         t!(fs::create_dir_all(&out));
567
568         let name = format!("openssl-{}.tar.gz", OPENSSL_VERS);
569         let tarball = out.join(&name);
570         if !tarball.exists() {
571             let tmp = tarball.with_extension("tmp");
572             // originally from https://www.openssl.org/source/...
573             let url = format!("https://s3-us-west-1.amazonaws.com/rust-lang-ci2/rust-ci-mirror/{}",
574                               name);
575             let mut last_error = None;
576             for _ in 0..3 {
577                 let status = Command::new("curl")
578                                 .arg("-o").arg(&tmp)
579                                 .arg("-f")  // make curl fail if the URL does not return HTTP 200
580                                 .arg(&url)
581                                 .status()
582                                 .expect("failed to spawn curl");
583
584                 // Retry if download failed.
585                 if !status.success() {
586                     last_error = Some(status.to_string());
587                     continue;
588                 }
589
590                 // Ensure the hash is correct.
591                 let mut shasum = if target.contains("apple") ||
592                     builder.config.build.contains("netbsd") {
593                     let mut cmd = Command::new("shasum");
594                     cmd.arg("-a").arg("256");
595                     cmd
596                 } else {
597                     Command::new("sha256sum")
598                 };
599                 let output = output(&mut shasum.arg(&tmp));
600                 let found = output.split_whitespace().next().unwrap();
601
602                 // If the hash is wrong, probably the download is incomplete or S3 served an error
603                 // page. In any case, retry.
604                 if found != OPENSSL_SHA256 {
605                     last_error = Some(format!(
606                         "downloaded openssl sha256 different\n\
607                          expected: {}\n\
608                          found:    {}\n",
609                         OPENSSL_SHA256,
610                         found
611                     ));
612                     continue;
613                 }
614
615                 // Everything is fine, so exit the retry loop.
616                 last_error = None;
617                 break;
618             }
619             if let Some(error) = last_error {
620                 panic!("failed to download openssl source: {}", error);
621             }
622             t!(fs::rename(&tmp, &tarball));
623         }
624         let obj = out.join(format!("openssl-{}", OPENSSL_VERS));
625         let dst = builder.openssl_install_dir(target).unwrap();
626         drop(fs::remove_dir_all(&obj));
627         drop(fs::remove_dir_all(&dst));
628         builder.run(Command::new("tar").arg("zxf").arg(&tarball).current_dir(&out));
629
630         let mut configure = Command::new("perl");
631         configure.arg(obj.join("Configure"));
632         configure.arg(format!("--prefix={}", dst.display()));
633         configure.arg("no-dso");
634         configure.arg("no-ssl2");
635         configure.arg("no-ssl3");
636
637         let os = match &*target {
638             "aarch64-linux-android" => "linux-aarch64",
639             "aarch64-unknown-linux-gnu" => "linux-aarch64",
640             "aarch64-unknown-linux-musl" => "linux-aarch64",
641             "aarch64-unknown-netbsd" => "BSD-generic64",
642             "arm-linux-androideabi" => "android",
643             "arm-unknown-linux-gnueabi" => "linux-armv4",
644             "arm-unknown-linux-gnueabihf" => "linux-armv4",
645             "armv6-unknown-netbsd-eabihf" => "BSD-generic32",
646             "armv7-linux-androideabi" => "android-armv7",
647             "armv7-unknown-linux-gnueabihf" => "linux-armv4",
648             "armv7-unknown-netbsd-eabihf" => "BSD-generic32",
649             "i586-unknown-linux-gnu" => "linux-elf",
650             "i586-unknown-linux-musl" => "linux-elf",
651             "i686-apple-darwin" => "darwin-i386-cc",
652             "i686-linux-android" => "android-x86",
653             "i686-unknown-freebsd" => "BSD-x86-elf",
654             "i686-unknown-linux-gnu" => "linux-elf",
655             "i686-unknown-linux-musl" => "linux-elf",
656             "i686-unknown-netbsd" => "BSD-x86-elf",
657             "mips-unknown-linux-gnu" => "linux-mips32",
658             "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
659             "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
660             "mipsel-unknown-linux-gnu" => "linux-mips32",
661             "powerpc-unknown-linux-gnu" => "linux-ppc",
662             "powerpc-unknown-linux-gnuspe" => "linux-ppc",
663             "powerpc-unknown-netbsd" => "BSD-generic32",
664             "powerpc64-unknown-linux-gnu" => "linux-ppc64",
665             "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
666             "powerpc64le-unknown-linux-musl" => "linux-ppc64le",
667             "s390x-unknown-linux-gnu" => "linux64-s390x",
668             "sparc-unknown-linux-gnu" => "linux-sparcv9",
669             "sparc64-unknown-linux-gnu" => "linux64-sparcv9",
670             "sparc64-unknown-netbsd" => "BSD-sparc64",
671             "x86_64-apple-darwin" => "darwin64-x86_64-cc",
672             "x86_64-linux-android" => "linux-x86_64",
673             "x86_64-unknown-freebsd" => "BSD-x86_64",
674             "x86_64-unknown-dragonfly" => "BSD-x86_64",
675             "x86_64-unknown-linux-gnu" => "linux-x86_64",
676             "x86_64-unknown-linux-gnux32" => "linux-x32",
677             "x86_64-unknown-linux-musl" => "linux-x86_64",
678             "x86_64-unknown-netbsd" => "BSD-x86_64",
679             _ => panic!("don't know how to configure OpenSSL for {}", target),
680         };
681         configure.arg(os);
682         configure.env("CC", builder.cc(target));
683         for flag in builder.cflags(target) {
684             configure.arg(flag);
685         }
686         // There is no specific os target for android aarch64 or x86_64,
687         // so we need to pass some extra cflags
688         if target == "aarch64-linux-android" || target == "x86_64-linux-android" {
689             configure.arg("-mandroid");
690             configure.arg("-fomit-frame-pointer");
691         }
692         if target == "sparc64-unknown-netbsd" {
693             // Need -m64 to get assembly generated correctly for sparc64.
694             configure.arg("-m64");
695             if builder.config.build.contains("netbsd") {
696                 // Disable sparc64 asm on NetBSD builders, it uses
697                 // m4(1)'s -B flag, which NetBSD m4 does not support.
698                 configure.arg("no-asm");
699             }
700         }
701         // Make PIE binaries
702         // Non-PIE linker support was removed in Lollipop
703         // https://source.android.com/security/enhancements/enhancements50
704         if target == "i686-linux-android" {
705             configure.arg("no-asm");
706         }
707         configure.current_dir(&obj);
708         builder.info(&format!("Configuring openssl for {}", target));
709         builder.run_quiet(&mut configure);
710         builder.info(&format!("Building openssl for {}", target));
711         builder.run_quiet(Command::new("make").arg("-j1").current_dir(&obj));
712         builder.info(&format!("Installing openssl for {}", target));
713         builder.run_quiet(Command::new("make").arg("install").arg("-j1").current_dir(&obj));
714
715         let mut f = t!(File::create(&stamp));
716         t!(f.write_all(OPENSSL_VERS.as_bytes()));
717     }
718 }