File: build.rs

package info (click to toggle)
aws-crt-python 0.16.8%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 78,328 kB
  • sloc: ansic: 330,743; python: 18,949; makefile: 6,271; sh: 3,712; asm: 754; cpp: 699; ruby: 208; java: 77; perl: 73; javascript: 46; xml: 11
file content (263 lines) | stat: -rw-r--r-- 7,299 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::path::{Path, PathBuf};

fn main() {
    let external = External::default();
    if external.is_enabled() {
        external.link();
    } else {
        #[cfg(feature = "cmake")]
        {
            // branch on a runtime value so we don't get unused code warnings
            if option_env("CARGO_FEATURE_CMAKE").is_some() {
                build_cmake();
            } else {
                build_vendored();
            }
        }

        #[cfg(not(feature = "cmake"))]
        build_vendored();
    }
}

fn env<N: AsRef<str>>(name: N) -> String {
    option_env(name).expect("missing env var")
}

fn option_env<N: AsRef<str>>(name: N) -> Option<String> {
    let name = name.as_ref();
    eprintln!("cargo:rerun-if-env-changed={}", name);
    std::env::var(name).ok()
}

struct FeatureDetector<'a> {
    out_dir: &'a std::path::Path,
}

impl<'a> FeatureDetector<'a> {
    pub fn new(out_dir: &'a Path) -> Self {
        Self { out_dir }
    }

    pub fn supports(&self, name: &str) -> bool {
        let out = self.out_dir.join("features").join(name);
        let out = out.to_str().unwrap();

        cc::Build::new()
            .file(
                std::path::Path::new("lib/tests/features")
                    .join(name)
                    .with_extension("c"),
            )
            // don't print anything
            .cargo_metadata(false)
            // make sure it doesn't warn
            .warnings(true)
            .debug(false)
            // set the archiver to the `true` program, since we don't actually link anything
            .archiver("true")
            .try_compile(out)
            .is_ok()
    }
}

fn build_vendored() {
    let mut build = cc::Build::new();

    let pq = option_env("CARGO_FEATURE_PQ").is_some();

    // TODO each pq section needs to be built separately since it
    //      has its own relative include paths
    assert!(!pq, "pq builds are not currently supported without cmake");

    build.files(include!("./files.rs").iter().copied().filter(|file| {
        // the pq entry file is still needed
        if *file == "lib/pq-crypto/s2n_pq.c" {
            return true;
        }

        if file.starts_with("lib/pq-crypto/") {
            return pq;
        }

        true
    }));

    build
        // pull the include path from the openssl-sys dependency
        .include(env("DEP_OPENSSL_INCLUDE"))
        .include("lib")
        .include("lib/api")
        .flag("-std=c11")
        .flag("-fgnu89-inline")
        // make sure the stack is non-executable
        .flag_if_supported("-z relro")
        .flag_if_supported("-z now")
        .flag_if_supported("-z noexecstack")
        // we use some deprecated libcrypto features so don't warn here
        .flag_if_supported("-Wno-deprecated-declarations")
        .define("_POSIX_C_SOURCE", "200112L");

    if env("PROFILE") == "release" {
        // fortify source is only available in release mode
        build.define("_FORTIFY_SOURCE", "2");

        // build s2n-tls with LTO if supported
        build
            .flag_if_supported("-flto")
            .flag_if_supported("-ffat-lto-objects")
            .define("NDEBUG", "1");
    }

    if !pq {
        build.define("S2N_NO_PQ", "1");
    }

    let out_dir = PathBuf::from(env("OUT_DIR"));

    let features = FeatureDetector::new(&out_dir);

    if features.supports("execinfo") {
        build.define("S2N_HAVE_EXECINFO", "1");
    }

    if features.supports("cpuid") {
        build.define("S2N_CPUID_AVAILABLE", "1");
    }

    if features.supports("features") {
        build.define("S2N_FEATURES_AVAILABLE", "1");
    }

    if features.supports("fallthrough") {
        build.define("FALL_THROUGH_SUPPORTED", "1");
    }

    if features.supports("__restrict__") {
        build.define("__RESTRICT__SUPPORTED", "1");
    }

    if features.supports("madvise") {
        build.define("MADVISE_SUPPORTED", "1");
    }

    if features.supports("minherit") {
        build.define("MINHERIT_SUPPORTED", "1");
    }

    if features.supports("clone") {
        build.define("CLONE_SUPPORTED", "1");
    }

    // don't spit out a bunch of warnings to the end user, since they won't really be able
    // to do anything with it
    build.warnings(false);

    build.compile("s2n-tls");

    // tell rust we're linking with libcrypto
    println!("cargo:rustc-link-lib=crypto");

    // let consumers know where to find our header files
    let include_dir = out_dir.join("include");
    std::fs::create_dir_all(&include_dir).unwrap();
    std::fs::copy("lib/api/s2n.h", include_dir.join("s2n.h")).unwrap();
    println!("cargo:include={}", include_dir.display());
}

#[cfg(feature = "cmake")]
fn build_cmake() {
    let mut config = cmake::Config::new("lib");

    // sometimes openssl-sys decides not to set this value so we may need to set it anyway
    if option_env("DEP_OPENSSL_ROOT").is_none() {
        let include = env("DEP_OPENSSL_INCLUDE");
        if let Some(root) = Path::new(&include).parent() {
            std::env::set_var("DEP_OPENSSL_ROOT", root);
        }
    }

    config
        .register_dep("openssl")
        .configure_arg("-DBUILD_TESTING=off");

    if option_env("CARGO_FEATURE_PQ").is_none() {
        config.configure_arg("-DS2N_NO_PQ=on");
    }

    let dst = config.build();

    let lib = search(dst.join("lib64"))
        .or_else(|| search(dst.join("lib")))
        .or_else(|| search(dst.join("build").join("lib")))
        .expect("could not build libs2n");

    // link the built artifact
    if lib.join("libs2n.a").exists() {
        println!("cargo:rustc-link-lib=static=s2n");
    } else {
        println!("cargo:rustc-link-lib=s2n");
    }

    println!("cargo:include={}", dst.join("include").display());

    // tell rust we're linking with libcrypto
    println!("cargo:rustc-link-lib=crypto");

    fn search(path: PathBuf) -> Option<PathBuf> {
        if path.exists() {
            println!("cargo:rustc-link-search={}", path.display());
            Some(path)
        } else {
            None
        }
    }
}

struct External {
    lib_dir: Option<PathBuf>,
    include_dir: Option<PathBuf>,
}

impl Default for External {
    fn default() -> Self {
        let dir = option_env("S2N_TLS_DIR").map(PathBuf::from);

        let lib_dir = option_env("S2N_TLS_LIB_DIR")
            .map(PathBuf::from)
            .or_else(|| dir.as_ref().map(|d| d.join("lib")));

        let include_dir = option_env("S2N_TLS_INCLUDE_DIR")
            .map(PathBuf::from)
            .or_else(|| dir.as_ref().map(|d| d.join("include")));

        Self {
            lib_dir,
            include_dir,
        }
    }
}

impl External {
    fn is_enabled(&self) -> bool {
        self.lib_dir.is_some()
    }

    fn link(&self) {
        println!(
            "cargo:rustc-link-search={}",
            self.lib_dir.as_ref().unwrap().display()
        );
        println!("cargo:rustc-link-lib=s2n");

        // tell rust we're linking with libcrypto
        println!("cargo:rustc-link-lib=crypto");

        if let Some(include_dir) = self.include_dir.as_ref() {
            println!("cargo:include={}", include_dir.display());
        }
    }
}