openssl_src/
lib.rs

1extern crate cc;
2
3use std::env;
4use std::ffi::{OsStr, OsString};
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9pub fn source_dir() -> PathBuf {
10    Path::new(env!("CARGO_MANIFEST_DIR")).join("openssl")
11}
12
13pub fn version() -> &'static str {
14    env!("CARGO_PKG_VERSION")
15}
16
17pub struct Build {
18    out_dir: Option<PathBuf>,
19    target: Option<String>,
20    host: Option<String>,
21    // Only affects non-windows builds for now.
22    openssl_dir: Option<PathBuf>,
23}
24
25pub struct Artifacts {
26    include_dir: PathBuf,
27    lib_dir: PathBuf,
28    bin_dir: PathBuf,
29    libs: Vec<String>,
30    target: String,
31}
32
33impl Build {
34    pub fn new() -> Build {
35        Build {
36            out_dir: env::var_os("OUT_DIR").map(|s| PathBuf::from(s).join("openssl-build")),
37            target: env::var("TARGET").ok(),
38            host: env::var("HOST").ok(),
39            openssl_dir: Some(PathBuf::from("/usr/local/ssl")),
40        }
41    }
42
43    pub fn out_dir<P: AsRef<Path>>(&mut self, path: P) -> &mut Build {
44        self.out_dir = Some(path.as_ref().to_path_buf());
45        self
46    }
47
48    pub fn target(&mut self, target: &str) -> &mut Build {
49        self.target = Some(target.to_string());
50        self
51    }
52
53    pub fn host(&mut self, host: &str) -> &mut Build {
54        self.host = Some(host.to_string());
55        self
56    }
57
58    pub fn openssl_dir<P: AsRef<Path>>(&mut self, path: P) -> &mut Build {
59        self.openssl_dir = Some(path.as_ref().to_path_buf());
60        self
61    }
62
63    fn cmd_make(&self) -> Result<Command, &'static str> {
64        let host = &self.host.as_ref().ok_or("HOST dir not set")?[..];
65        Ok(
66            if host.contains("dragonfly")
67                || host.contains("freebsd")
68                || host.contains("openbsd")
69                || host.contains("solaris")
70                || host.contains("illumos")
71            {
72                Command::new("gmake")
73            } else {
74                Command::new("make")
75            },
76        )
77    }
78
79    #[cfg(windows)]
80    fn check_env_var(&self, var_name: &str) -> Option<bool> {
81        env::var_os(var_name).and_then(|s| {
82            if s == "1" {
83                // a message to stdout, let user know asm is force enabled
84                println!(
85                    "cargo:warning={}: nasm.exe is force enabled by the \
86                    'OPENSSL_RUST_USE_NASM' env var.",
87                    env!("CARGO_PKG_NAME")
88                );
89                Some(true)
90            } else if s == "0" {
91                // a message to stdout, let user know asm is force disabled
92                println!(
93                    "cargo:warning={}: nasm.exe is force disabled by the \
94                    'OPENSSL_RUST_USE_NASM' env var.",
95                    env!("CARGO_PKG_NAME")
96                );
97                Some(false)
98            } else {
99                println!(
100                    "cargo:warning=The environment variable {} is set to an unacceptable value: {:?}",
101                    var_name, s
102                );
103                None
104            }
105        })
106    }
107
108    #[cfg(windows)]
109    fn is_nasm_ready(&self) -> bool {
110        self.check_env_var("OPENSSL_RUST_USE_NASM")
111            .unwrap_or_else(|| {
112                // On Windows, use cmd `where` command to check if nasm is installed
113                Command::new("cmd")
114                    .args(&["/C", "where nasm"])
115                    .output()
116                    .map(|w| w.status.success())
117                    .unwrap_or(false)
118            })
119    }
120
121    #[cfg(not(windows))]
122    fn is_nasm_ready(&self) -> bool {
123        // We assume that nobody would run nasm.exe on a non-windows system.
124        false
125    }
126
127    /// Exits the process on failure. Use `try_build` to handle the error.
128    pub fn build(&mut self) -> Artifacts {
129        match self.try_build() {
130            Ok(a) => a,
131            Err(e) => {
132                println!("cargo:warning=openssl-src: failed to build OpenSSL from source");
133                eprintln!("\n\n\n{e}\n\n\n");
134                std::process::exit(1);
135            }
136        }
137    }
138
139    pub fn try_build(&mut self) -> Result<Artifacts, String> {
140        let target = &self.target.as_ref().ok_or("TARGET dir not set")?[..];
141        let host = &self.host.as_ref().ok_or("HOST dir not set")?[..];
142        let out_dir = self.out_dir.as_ref().ok_or("OUT_DIR not set")?;
143        let build_dir = out_dir.join("build");
144        let install_dir = out_dir.join("install");
145
146        if build_dir.exists() {
147            fs::remove_dir_all(&build_dir).map_err(|e| format!("build_dir: {e}"))?;
148        }
149        if install_dir.exists() {
150            fs::remove_dir_all(&install_dir).map_err(|e| format!("install_dir: {e}"))?;
151        }
152
153        let inner_dir = build_dir.join("src");
154        fs::create_dir_all(&inner_dir).map_err(|e| format!("{}: {e}", inner_dir.display()))?;
155        cp_r(&source_dir(), &inner_dir)?;
156
157        let perl_program =
158            env::var("OPENSSL_SRC_PERL").unwrap_or(env::var("PERL").unwrap_or("perl".to_string()));
159        let mut configure = Command::new(perl_program);
160        configure.arg("./Configure");
161
162        // Change the install directory to happen inside of the build directory.
163        if host.contains("pc-windows-gnu") {
164            configure.arg(&format!("--prefix={}", sanitize_sh(&install_dir)));
165        } else if host.contains("pc-windows-msvc") || host.contains("win7-windows-msvc") {
166            // On Windows, the prefix argument does not support \ path seperators
167            // when cross compiling.
168            // Always use / as a path seperator instead of \, since that works for both
169            // native and cross builds.
170            configure.arg(&format!(
171                "--prefix={}",
172                install_dir
173                    .to_str()
174                    .ok_or("bad install_dir")?
175                    .replace("\\", "/")
176            ));
177        } else {
178            configure.arg(&format!("--prefix={}", install_dir.display()));
179        }
180
181        // Specify that openssl directory where things are loaded at runtime is
182        // not inside our build directory. Instead this should be located in the
183        // default locations of the OpenSSL build scripts, or as specified by whatever
184        // configured this builder.
185        if target.contains("windows") {
186            configure.arg("--openssldir=SYS$MANAGER:[OPENSSL]");
187        } else {
188            let openssl_dir = self
189                .openssl_dir
190                .as_ref()
191                .ok_or("path to the openssl directory must be set")?;
192            let mut dir_arg: OsString = "--openssldir=".into();
193            dir_arg.push(openssl_dir);
194            configure.arg(dir_arg);
195        }
196
197        configure
198            // No shared objects, we just want static libraries
199            .arg("no-shared")
200            .arg("no-module")
201            // Should be off by default on OpenSSL 1.1.0, but let's be extra sure
202            .arg("no-ssl3")
203            // No need to build tests, we won't run them anyway
204            .arg("no-tests")
205            // Nothing related to zlib please
206            .arg("no-comp")
207            .arg("no-zlib")
208            .arg("no-zlib-dynamic")
209            // Avoid multilib-postfix for build targets that specify it
210            .arg("--libdir=lib");
211
212        if cfg!(feature = "no-dso") {
213            // engine requires DSO support
214            if cfg!(feature = "force-engine") {
215                println!("Feature 'force-engine' requires DSO, ignoring 'no-dso' feature.");
216            } else {
217                configure.arg("no-dso");
218            }
219        }
220
221        if cfg!(not(feature = "legacy")) {
222            configure.arg("no-legacy");
223        }
224
225        if cfg!(feature = "weak-crypto") {
226            configure
227                .arg("enable-md2")
228                .arg("enable-rc5")
229                .arg("enable-weak-ssl-ciphers");
230        } else {
231            configure
232                .arg("no-md2")
233                .arg("no-rc5")
234                .arg("no-weak-ssl-ciphers");
235        }
236
237        if cfg!(not(feature = "camellia")) {
238            configure.arg("no-camellia");
239        }
240
241        if cfg!(not(feature = "idea")) {
242            configure.arg("no-idea");
243        }
244
245        if cfg!(not(feature = "seed")) {
246            configure.arg("no-seed");
247        }
248
249        if cfg!(feature = "ktls") {
250            configure.arg("enable-ktls");
251        }
252
253        if target.contains("musl") {
254            // Engine module fails to compile on musl (it needs linux/version.h
255            // right now) but we don't actually need this most of the time.
256            // Disable engine module unless force-engine feature specified
257            if !cfg!(feature = "force-engine") {
258                configure.arg("no-engine");
259            }
260        } else if target.contains("windows") {
261            // We can build the engine feature, but the build doesn't seem
262            // to correctly pick up crypt32.lib functions such as
263            // `__imp_CertOpenStore` when building the capieng engine.
264            // Let's disable just capieng.
265            configure.arg("no-capieng");
266        }
267
268        if target.contains("musl") {
269            // MUSL doesn't implement some of the libc functions that the async
270            // stuff depends on, and we don't bind to any of that in any case.
271            configure.arg("no-async");
272        }
273
274        // On Android it looks like not passing no-stdio may cause a build
275        // failure (#13), but most other platforms need it for things like
276        // loading system certificates so only disable it on Android.
277        if target.contains("android") {
278            configure.arg("no-stdio");
279        }
280
281        if target.contains("msvc") {
282            // On MSVC we need nasm.exe to compile the assembly files.
283            // ASM compiling will be enabled if nasm.exe is installed, unless
284            // the environment variable `OPENSSL_RUST_USE_NASM` is set.
285            if self.is_nasm_ready() {
286                // a message to stdout, let user know asm is enabled
287                println!(
288                    "{}: Enable the assembly language routines in building OpenSSL.",
289                    env!("CARGO_PKG_NAME")
290                );
291            } else {
292                configure.arg("no-asm");
293            }
294        }
295
296        let os = match target {
297            "aarch64-apple-darwin" => "darwin64-arm64-cc",
298            // Note that this, and all other android targets, aren't using the
299            // `android64-aarch64` (or equivalent) builtin target. That
300            // apparently has a crazy amount of build logic in OpenSSL 1.1.1
301            // that bypasses basically everything `cc` does, so let's just cop
302            // out and say it's linux and hope it works.
303            "aarch64-linux-android" => "linux-aarch64",
304            "aarch64-unknown-freebsd" => "BSD-generic64",
305            "aarch64-unknown-openbsd" => "BSD-generic64",
306            "aarch64-unknown-linux-gnu" => "linux-aarch64",
307            "aarch64-unknown-linux-musl" => "linux-aarch64",
308            "aarch64-alpine-linux-musl" => "linux-aarch64",
309            "aarch64-chimera-linux-musl" => "linux-aarch64",
310            "aarch64-unknown-netbsd" => "BSD-generic64",
311            "aarch64_be-unknown-netbsd" => "BSD-generic64",
312            "aarch64-pc-windows-msvc" => "VC-WIN64-ARM",
313            "aarch64-uwp-windows-msvc" => "VC-WIN64-ARM-UWP",
314            "arm-linux-androideabi" => "linux-armv4",
315            "armv7-linux-androideabi" => "linux-armv4",
316            "arm-unknown-linux-gnueabi" => "linux-armv4",
317            "arm-unknown-linux-gnueabihf" => "linux-armv4",
318            "arm-unknown-linux-musleabi" => "linux-armv4",
319            "arm-unknown-linux-musleabihf" => "linux-armv4",
320            "arm-chimera-linux-musleabihf" => "linux-armv4",
321            "armv5te-unknown-linux-gnueabi" => "linux-armv4",
322            "armv5te-unknown-linux-musleabi" => "linux-armv4",
323            "armv6-unknown-freebsd" => "BSD-generic32",
324            "armv6-alpine-linux-musleabihf" => "linux-armv6",
325            "armv7-unknown-freebsd" => "BSD-armv4",
326            "armv7-unknown-linux-gnueabi" => "linux-armv4",
327            "armv7-unknown-linux-musleabi" => "linux-armv4",
328            "armv7-unknown-linux-gnueabihf" => "linux-armv4",
329            "armv7-unknown-linux-musleabihf" => "linux-armv4",
330            "armv7-alpine-linux-musleabihf" => "linux-armv4",
331            "armv7-chimera-linux-musleabihf" => "linux-armv4",
332            "armv7-unknown-netbsd-eabihf" => "BSD-generic32",
333            "asmjs-unknown-emscripten" => "gcc",
334            "i586-unknown-linux-gnu" => "linux-elf",
335            "i586-unknown-linux-musl" => "linux-elf",
336            "i586-alpine-linux-musl" => "linux-elf",
337            "i586-unknown-netbsd" => "BSD-x86-elf",
338            "i686-apple-darwin" => "darwin-i386-cc",
339            "i686-linux-android" => "linux-elf",
340            "i686-pc-windows-gnu" => "mingw",
341            "i686-pc-windows-msvc" => "VC-WIN32",
342            "i686-win7-windows-msvc" => "VC-WIN32",
343            "i686-unknown-freebsd" => "BSD-x86-elf",
344            "i686-unknown-haiku" => "haiku-x86",
345            "i686-unknown-linux-gnu" => "linux-elf",
346            "i686-unknown-linux-musl" => "linux-elf",
347            "i686-unknown-netbsd" => "BSD-x86-elf",
348            "i686-uwp-windows-msvc" => "VC-WIN32-UWP",
349            "loongarch64-unknown-linux-gnu" => "linux-generic64",
350            "loongarch64-unknown-linux-musl" => "linux-generic64",
351            "mips-unknown-linux-gnu" => "linux-mips32",
352            "mips-unknown-linux-musl" => "linux-mips32",
353            "mips64-unknown-linux-gnuabi64" => "linux64-mips64",
354            "mips64-unknown-linux-muslabi64" => "linux64-mips64",
355            "mips64el-unknown-linux-gnuabi64" => "linux64-mips64",
356            "mips64el-unknown-linux-muslabi64" => "linux64-mips64",
357            "mipsel-unknown-linux-gnu" => "linux-mips32",
358            "mipsel-unknown-linux-musl" => "linux-mips32",
359            "powerpc-unknown-freebsd" => "BSD-ppc",
360            "powerpc-unknown-linux-gnu" => "linux-ppc",
361            "powerpc-unknown-linux-gnuspe" => "linux-ppc",
362            "powerpc-chimera-linux-musl" => "linux-ppc",
363            "powerpc-unknown-netbsd" => "BSD-generic32",
364            "powerpc64-unknown-freebsd" => "BSD-ppc64",
365            "powerpc64-unknown-linux-gnu" => "linux-ppc64",
366            "powerpc64-unknown-linux-musl" => "linux-ppc64",
367            "powerpc64-chimera-linux-musl" => "linux-ppc64",
368            "powerpc64le-unknown-freebsd" => "BSD-ppc64le",
369            "powerpc64le-unknown-linux-gnu" => "linux-ppc64le",
370            "powerpc64le-unknown-linux-musl" => "linux-ppc64le",
371            "powerpc64le-alpine-linux-musl" => "linux-ppc64le",
372            "powerpc64le-chimera-linux-musl" => "linux-ppc64le",
373            "riscv64gc-unknown-freebsd" => "BSD-riscv64",
374            "riscv64gc-unknown-linux-gnu" => "linux64-riscv64",
375            "riscv64gc-unknown-linux-musl" => "linux64-riscv64",
376            "riscv64-alpine-linux-musl" => "linux64-riscv64",
377            "riscv64-chimera-linux-musl" => "linux64-riscv64",
378            "riscv64gc-unknown-netbsd" => "BSD-generic64",
379            "s390x-unknown-linux-gnu" => "linux64-s390x",
380            "sparc64-unknown-netbsd" => "BSD-generic64",
381            "s390x-unknown-linux-musl" => "linux64-s390x",
382            "s390x-alpine-linux-musl" => "linux64-s390x",
383            "sparcv9-sun-solaris" => "solaris64-sparcv9-gcc",
384            "thumbv7a-uwp-windows-msvc" => "VC-WIN32-ARM-UWP",
385            "x86_64-apple-darwin" => "darwin64-x86_64-cc",
386            "x86_64-linux-android" => "linux-x86_64",
387            "x86_64-linux" => "linux-x86_64",
388            "x86_64-pc-windows-gnu" => "mingw64",
389            "x86_64-pc-windows-gnullvm" => "mingw64",
390            "x86_64-pc-windows-msvc" => "VC-WIN64A",
391            "x86_64-win7-windows-msvc" => "VC-WIN64A",
392            "x86_64-unknown-freebsd" => "BSD-x86_64",
393            "x86_64-unknown-dragonfly" => "BSD-x86_64",
394            "x86_64-unknown-haiku" => "haiku-x86_64",
395            "x86_64-unknown-illumos" => "solaris64-x86_64-gcc",
396            "x86_64-unknown-linux-gnu" => "linux-x86_64",
397            "x86_64-unknown-linux-musl" => "linux-x86_64",
398            "x86_64-alpine-linux-musl" => "linux-x86_64",
399            "x86_64-chimera-linux-musl" => "linux-x86_64",
400            "x86_64-unknown-openbsd" => "BSD-x86_64",
401            "x86_64-unknown-netbsd" => "BSD-x86_64",
402            "x86_64-uwp-windows-msvc" => "VC-WIN64A-UWP",
403            "x86_64-pc-solaris" => "solaris64-x86_64-gcc",
404            "wasm32-unknown-emscripten" => "gcc",
405            "wasm32-unknown-unknown" => "gcc",
406            "wasm32-wasi" => "gcc",
407            "aarch64-apple-ios" => "ios64-cross",
408            "x86_64-apple-ios" => "iossimulator-xcrun",
409            "aarch64-apple-ios-sim" => "iossimulator-xcrun",
410            "aarch64-unknown-linux-ohos" => "linux-aarch64",
411            "armv7-unknown-linux-ohos" => "linux-generic32",
412            "x86_64-unknown-linux-ohos" => "linux-x86_64",
413            _ => {
414                return Err(format!(
415                    "don't know how to configure OpenSSL for {}",
416                    target
417                ))
418            }
419        };
420
421        let mut ios_isysroot: std::option::Option<String> = None;
422
423        configure.arg(os);
424
425        // If we're not on MSVC we configure cross compilers and cross tools and
426        // whatnot. Note that this doesn't happen on MSVC b/c things are pretty
427        // different there and this isn't needed most of the time anyway.
428        if !target.contains("msvc") {
429            let mut cc = cc::Build::new();
430            cc.target(target).host(host).warnings(false).opt_level(2);
431            let compiler = cc.get_compiler();
432            let mut cc_env = compiler.cc_env();
433            if cc_env.is_empty() {
434                cc_env = compiler.path().to_path_buf().into_os_string();
435            }
436            configure.env("CC", cc_env);
437            let path = compiler.path().to_str().ok_or("compiler path")?;
438
439            // Both `cc::Build` and `./Configure` take into account
440            // `CROSS_COMPILE` environment variable. So to avoid double
441            // prefix, we unset `CROSS_COMPILE` for `./Configure`.
442            configure.env_remove("CROSS_COMPILE");
443
444            let ar = cc.get_archiver();
445            configure.env("AR", ar.get_program());
446            if ar.get_args().count() != 0 {
447                // On some platforms (like emscripten on windows), the ar to use may not be a
448                // single binary, but instead a multi-argument command like `cmd /c emar.bar`.
449                // We can't convey that through `AR` alone, and so also need to set ARFLAGS.
450                configure.env(
451                    "ARFLAGS",
452                    ar.get_args().collect::<Vec<_>>().join(OsStr::new(" ")),
453                );
454            }
455            let ranlib = cc.get_ranlib();
456            // OpenSSL does not support RANLIBFLAGS. Jam the flags in RANLIB.
457            let mut args = vec![ranlib.get_program()];
458            args.extend(ranlib.get_args());
459            configure.env("RANLIB", args.join(OsStr::new(" ")));
460
461            // Make sure we pass extra flags like `-ffunction-sections` and
462            // other things like ARM codegen flags.
463            let mut skip_next = false;
464            let mut is_isysroot = false;
465            for arg in compiler.args() {
466                // For whatever reason `-static` on MUSL seems to cause
467                // issues...
468                if target.contains("musl") && arg == "-static" {
469                    continue;
470                }
471
472                // cc includes an `-arch` flag for Apple platforms, but we've
473                // already selected an arch implicitly via the target above, and
474                // OpenSSL contains about the conflict if both are specified.
475                if target.contains("apple") {
476                    if arg == "-arch" {
477                        skip_next = true;
478                        continue;
479                    }
480                }
481
482                // cargo-lipo specifies this but OpenSSL complains
483                if target.contains("apple-ios") {
484                    if arg == "-isysroot" {
485                        is_isysroot = true;
486                        continue;
487                    }
488
489                    if is_isysroot {
490                        is_isysroot = false;
491                        ios_isysroot = Some(arg.to_str().ok_or("isysroot arg")?.to_string());
492                        continue;
493                    }
494                }
495
496                if skip_next {
497                    skip_next = false;
498                    continue;
499                }
500
501                configure.arg(arg);
502            }
503
504            if os.contains("iossimulator") {
505                if let Some(ref isysr) = ios_isysroot {
506                    configure.env(
507                        "CC",
508                        &format!(
509                            "xcrun -sdk iphonesimulator cc -isysroot {}",
510                            sanitize_sh(&Path::new(isysr))
511                        ),
512                    );
513                }
514            }
515
516            if target == "x86_64-pc-windows-gnu" {
517                // For whatever reason OpenSSL 1.1.1 fails to build on
518                // `x86_64-pc-windows-gnu` in our docker container due to an
519                // error about "too many sections". Having no idea what this
520                // error is about some quick googling yields
521                // https://github.com/cginternals/glbinding/issues/135 which
522                // mysteriously mentions `-Wa,-mbig-obj`, passing a new argument
523                // to the assembler. Now I have no idea what `-mbig-obj` does
524                // for Windows nor why it would matter, but it does seem to fix
525                // compilation issues.
526                //
527                // Note that another entirely unrelated issue -
528                // https://github.com/assimp/assimp/issues/177 - was fixed by
529                // splitting a large file, so presumably OpenSSL has a large
530                // file soemwhere in it? Who knows!
531                configure.arg("-Wa,-mbig-obj");
532            }
533
534            if target.contains("pc-windows-gnu") && path.ends_with("-gcc") {
535                // As of OpenSSL 1.1.1 the build system is now trying to execute
536                // `windres` which doesn't exist when we're cross compiling from
537                // Linux, so we may need to instruct it manually to know what
538                // executable to run.
539                let windres = format!("{}-windres", &path[..path.len() - 4]);
540                configure.env("WINDRES", &windres);
541            }
542
543            if target.contains("emscripten") {
544                // As of OpenSSL 1.1.1 the source apparently wants to include
545                // `stdatomic.h`, but this doesn't exist on Emscripten. After
546                // reading OpenSSL's source where the error is, we define this
547                // magical (and probably
548                // compiler-internal-should-not-be-user-defined) macro to say
549                // "no atomics are available" and avoid including such a header.
550                configure.arg("-D__STDC_NO_ATOMICS__");
551            }
552
553            if target.contains("wasi") {
554                configure.args([
555                    // Termios isn't available whatsoever on WASM/WASI so we disable that
556                    "no-ui-console",
557                    // WASI doesn't support UNIX sockets so we preemptively disable it
558                    "no-sock",
559                    // WASI doesn't have a concept of syslog, so we disable it
560                    "-DNO_SYSLOG",
561                    // WASI doesn't support (p)threads. Disabling preemptively.
562                    "no-threads",
563                    // WASI/WASM aren't really friends with ASM, so we disable it as well.
564                    "no-asm",
565                    // Disables the AFALG engine (AFALG-ENGine)
566                    // Since AFALG depends on `AF_ALG` support on the linux kernel side
567                    // it makes sense that we can't use it.
568                    "no-afalgeng",
569                    "-DOPENSSL_NO_AFALGENG=1",
570                    // wasm lacks signal support; to enable minimal signal emulation, compile with
571                    // -D_WASI_EMULATED_SIGNAL and link with -lwasi-emulated-signal
572                    // The link argument is output in the `Artifacts::print_cargo_metadata` method
573                    "-D_WASI_EMULATED_SIGNAL",
574                    // WASI lacks process-associated clocks; to enable emulation of the `times` function using the wall
575                    // clock, which isn't sensitive to whether the program is running or suspended, compile with
576                    // -D_WASI_EMULATED_PROCESS_CLOCKS and link with -lwasi-emulated-process-clocks
577                    // The link argument is output in the `Artifacts::print_cargo_metadata` method
578                    "-D_WASI_EMULATED_PROCESS_CLOCKS",
579                    // WASI lacks a true mmap; to enable minimal mmap emulation, compile
580                    // with -D_WASI_EMULATED_MMAN and link with -lwasi-emulated-mman
581                    // The link argument is output in the `Artifacts::print_cargo_metadata` method
582                    "-D_WASI_EMULATED_MMAN",
583                    // WASI lacks process identifiers; to enable emulation of the `getpid` function using a
584                    // placeholder value, which doesn't reflect the host PID of the program, compile with
585                    // -D_WASI_EMULATED_GETPID and link with -lwasi-emulated-getpid
586                    // The link argument is output in the `Artifacts::print_cargo_metadata` method
587                    "-D_WASI_EMULATED_GETPID",
588                    // WASI doesn't have chmod right now, so don't try to use it.
589                    "-DNO_CHMOD",
590                ]);
591            }
592
593            if target.contains("musl") {
594                // Hack around openssl/openssl#7207 for now
595                configure.arg("-DOPENSSL_NO_SECURE_MEMORY");
596            }
597        }
598
599        // And finally, run the perl configure script!
600        configure.current_dir(&inner_dir);
601        self.run_command(configure, "configuring OpenSSL build")?;
602
603        // On MSVC we use `nmake.exe` with a slightly different invocation, so
604        // have that take a different path than the standard `make` below.
605        if target.contains("msvc") {
606            let mut build =
607                cc::windows_registry::find(target, "nmake.exe").ok_or("failed to find nmake")?;
608            build.arg("build_libs").current_dir(&inner_dir);
609            self.run_command(build, "building OpenSSL")?;
610
611            let mut install =
612                cc::windows_registry::find(target, "nmake.exe").ok_or("failed to find nmake")?;
613            install.arg("install_dev").current_dir(&inner_dir);
614            self.run_command(install, "installing OpenSSL")?;
615        } else {
616            let mut depend = self.cmd_make()?;
617            depend.arg("depend").current_dir(&inner_dir);
618            self.run_command(depend, "building OpenSSL dependencies")?;
619
620            let mut build = self.cmd_make()?;
621            build.arg("build_libs").current_dir(&inner_dir);
622            if !cfg!(windows) {
623                if let Some(s) = env::var_os("CARGO_MAKEFLAGS") {
624                    build.env("MAKEFLAGS", s);
625                }
626            }
627
628            if let Some(ref isysr) = ios_isysroot {
629                let components: Vec<&str> = isysr.split("/SDKs/").collect();
630                build.env("CROSS_TOP", components[0]);
631                build.env("CROSS_SDK", components[1]);
632            }
633
634            self.run_command(build, "building OpenSSL")?;
635
636            let mut install = self.cmd_make()?;
637            install.arg("install_dev").current_dir(&inner_dir);
638            self.run_command(install, "installing OpenSSL")?;
639        }
640
641        let libs = if target.contains("msvc") {
642            vec!["libssl".to_string(), "libcrypto".to_string()]
643        } else {
644            vec!["ssl".to_string(), "crypto".to_string()]
645        };
646
647        fs::remove_dir_all(&inner_dir).map_err(|e| format!("{}: {e}", inner_dir.display()))?;
648
649        Ok(Artifacts {
650            lib_dir: install_dir.join("lib"),
651            bin_dir: install_dir.join("bin"),
652            include_dir: install_dir.join("include"),
653            libs: libs,
654            target: target.to_string(),
655        })
656    }
657
658    #[track_caller]
659    fn run_command(&self, mut command: Command, desc: &str) -> Result<(), String> {
660        println!("running {:?}", command);
661        let status = command.status();
662
663        let verbose_error = match status {
664            Ok(status) if status.success() => return Ok(()),
665            Ok(status) => format!(
666                "'{exe}' reported failure with {status}",
667                exe = command.get_program().to_string_lossy()
668            ),
669            Err(failed) => match failed.kind() {
670                std::io::ErrorKind::NotFound => format!(
671                    "Command '{exe}' not found. Is {exe} installed?",
672                    exe = command.get_program().to_string_lossy()
673                ),
674                _ => format!(
675                    "Could not run '{exe}', because {failed}",
676                    exe = command.get_program().to_string_lossy()
677                ),
678            },
679        };
680        println!("cargo:warning={desc}: {verbose_error}");
681        Err(format!(
682            "Error {desc}:
683    {verbose_error}
684    Command failed: {command:?}"
685        ))
686    }
687}
688
689fn cp_r(src: &Path, dst: &Path) -> Result<(), String> {
690    for f in fs::read_dir(src).map_err(|e| format!("{}: {e}", src.display()))? {
691        let f = match f {
692            Ok(f) => f,
693            _ => continue,
694        };
695        let path = f.path();
696        let name = path
697            .file_name()
698            .ok_or_else(|| format!("bad dir {}", src.display()))?;
699
700        // Skip git metadata as it's been known to cause issues (#26) and
701        // otherwise shouldn't be required
702        if name.to_str() == Some(".git") {
703            continue;
704        }
705
706        let dst = dst.join(name);
707        let ty = f.file_type().map_err(|e| e.to_string())?;
708        if ty.is_dir() {
709            fs::create_dir_all(&dst).map_err(|e| e.to_string())?;
710            cp_r(&path, &dst)?;
711        } else if ty.is_symlink() && path.iter().any(|p| p == "cloudflare-quiche") {
712            // not needed to build
713            continue;
714        } else {
715            let _ = fs::remove_file(&dst);
716            if let Err(e) = fs::copy(&path, &dst) {
717                return Err(format!(
718                    "failed to copy '{}' to '{}': {e}",
719                    path.display(),
720                    dst.display()
721                ));
722            }
723        }
724    }
725    Ok(())
726}
727
728fn sanitize_sh(path: &Path) -> String {
729    if !cfg!(windows) {
730        return path.to_string_lossy().into_owned();
731    }
732    let path = path.to_string_lossy().replace("\\", "/");
733    return change_drive(&path).unwrap_or(path);
734
735    fn change_drive(s: &str) -> Option<String> {
736        let mut ch = s.chars();
737        let drive = ch.next().unwrap_or('C');
738        if ch.next() != Some(':') {
739            return None;
740        }
741        if ch.next() != Some('/') {
742            return None;
743        }
744        Some(format!("/{}/{}", drive, &s[drive.len_utf8() + 2..]))
745    }
746}
747
748impl Artifacts {
749    pub fn include_dir(&self) -> &Path {
750        &self.include_dir
751    }
752
753    pub fn lib_dir(&self) -> &Path {
754        &self.lib_dir
755    }
756
757    pub fn libs(&self) -> &[String] {
758        &self.libs
759    }
760
761    pub fn print_cargo_metadata(&self) {
762        println!("cargo:rustc-link-search=native={}", self.lib_dir.display());
763        for lib in self.libs.iter() {
764            println!("cargo:rustc-link-lib=static={}", lib);
765        }
766        println!("cargo:include={}", self.include_dir.display());
767        println!("cargo:lib={}", self.lib_dir.display());
768        if self.target.contains("windows") {
769            println!("cargo:rustc-link-lib=user32");
770            println!("cargo:rustc-link-lib=crypt32");
771        } else if self.target == "wasm32-wasi" {
772            println!("cargo:rustc-link-lib=wasi-emulated-signal");
773            println!("cargo:rustc-link-lib=wasi-emulated-process-clocks");
774            println!("cargo:rustc-link-lib=wasi-emulated-mman");
775            println!("cargo:rustc-link-lib=wasi-emulated-getpid");
776        }
777    }
778}