libcronet-sys 0.2.0

Low-level FFI bindings to Chromium Cronet (libcronet), with optional prebuilt-binary download.
Documentation
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Build script for `libcronet-sys`.
//!
//! Responsibilities:
//!   1. (`download` feature) Fetch the matching prebuilt `libcronet` for the
//!      target from github.com/rust-proxy/cronet-binaries into `OUT_DIR`, with
//!      mandatory SHA-256 verification against a pinned checksum. No network is
//!      touched unless `download`, or `download-static` with the static backend,
//!      is enabled.
//!   2. (`static-link` feature) Emit `cargo:rustc-link-*` directives so the
//!      linker finds `libcronet.a` — either from `CRONET_LIB_DIR` or from the
//!      file just downloaded.
//!
//! In the default (dynamic) mode without `download`, this script does nothing
//! but register its rerun triggers.
//!
//! ## Relevant environment variables
//!
//! - `CRONET_LIB_DIR`         — dir containing `libcronet.a` (static mode).
//! - `CRONET_STATIC_NAME`     — static lib stem (default `cronet`).
//! - `CRONET_DOWNLOAD_TAG`    — release tag to fetch (default `v154.0.8037.49`).
//! - `CRONET_DOWNLOAD_ASSET`  — override the auto-detected asset file name.
//! - `CRONET_DOWNLOAD_SHA256` — expected SHA-256 for a custom/unpinned asset.
//! - `CRONET_DOWNLOAD_LINK_FLAGS_SHA256` — expected SHA-256 for Windows link flags.
//! - `CRONET_DOWNLOAD_DIR`    — cache dir for downloads (default `OUT_DIR`).

mod build_target;

use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Base URL for release downloads.
#[cfg(any(feature = "download", feature = "download-static"))]
const RELEASE_BASE: &str = "https://github.com/rust-proxy/cronet-binaries/releases/download";

/// Pinned SHA-256 checksums for the fixed `v154.0.8037.49` release.
/// Update the release tag and this table together when adopting a new build.
#[cfg(any(feature = "download", feature = "download-static"))]
#[rustfmt::skip]
const CHECKSUMS: &[(&str, &str)] = &[
    ("libcronet-android-386.a", "c3427955d6ddf603bc572a9e9dc546972a5f5ad195a20289fab09b5365220991"),
    ("libcronet-android-amd64.a", "f015e90bd4ed965580215f36a493cd7f9346b5355bb5e164acec9109b0fa2f82"),
    ("libcronet-android-arm.a", "7718d4f5574b5e7a552790c38c3daedeb2ca6c499fce4f0c81d1409de3cdc6c1"),
    ("libcronet-android-arm64.a", "e5d6e58a6aa24287358376a76fd280b4d8d62472c4b215dbb853d3a27b2722ae"),
    ("libcronet-darwin-amd64.a", "dddb764dad4ea2008699f6b9dd0b70d3042d917097bd657200b149e3446307b2"),
    ("libcronet-darwin-arm64.a", "3c03d46121140a66044dc42b17197ac046870b945cbb2ef292223645a17d6034"),
    ("libcronet-ios-amd64_simulator.a", "090d37b81c9e9c028607ba129b6d3eba6d11a8e813cc0daa6baf248659da666f"),
    ("libcronet-ios-arm64.a", "825811d26ad6eaf6dfe9041ed7e097eb4412acaa1f9012226a30f94d9a6262a7"),
    ("libcronet-ios-arm64_simulator.a", "c9642da81f761c2a859cbf6ef97b41889a42fee27d3dac262c966914c3992582"),
    ("libcronet-linux-386.a", "62c5c85c34cf5b90796d98a25074bc4005a073a7a94a805b332ed357e6ca67fa"),
    ("libcronet-linux-386.link-flags.txt", "eb76fb6666e3939472c0bc30d26186496f40e1e722f4ba4f971315cefa7005a3"),
    ("libcronet-linux-386.so", "d15e359cd27f6a04313af363aa092eda1d02fe8b8131dce7ee51a860943fab56"),
    ("libcronet-linux-386_musl.a", "33e257b9cf9cc13e6673165c8855981adc46d3017dabcb47eed15f5d37805a00"),
    ("libcronet-linux-386_musl.link-flags.txt", "6a314d8af0d1f1512f0bb9227c8071e5e28c5b1dc8af57b6d7382edc52525e9f"),
    ("libcronet-linux-amd64.a", "b5819a90e0628daf23a4e5f72c085b5fd297090964556291bb1c045cf5892b68"),
    ("libcronet-linux-amd64.link-flags.txt", "eb76fb6666e3939472c0bc30d26186496f40e1e722f4ba4f971315cefa7005a3"),
    ("libcronet-linux-amd64.so", "e66882e193318719f2ab880ef54e27fd0fd4e824a6d7829074770758af0e9409"),
    ("libcronet-linux-amd64_musl.a", "b16d40eb14b8ef7780336a271b7a1ceeecbb3bd5a41086c299f904829e1abb1e"),
    ("libcronet-linux-amd64_musl.link-flags.txt", "6a314d8af0d1f1512f0bb9227c8071e5e28c5b1dc8af57b6d7382edc52525e9f"),
    ("libcronet-linux-arm.a", "8faff0742e7a3c8b5d73c222dcd0815ba0f02b7c8f6289adbdb288baafe67d82"),
    ("libcronet-linux-arm.link-flags.txt", "eb76fb6666e3939472c0bc30d26186496f40e1e722f4ba4f971315cefa7005a3"),
    ("libcronet-linux-arm.so", "b0ea1dc4ffe88e33b2912d5d950b2388632930f9f1f115e534a754a0f10bdaf4"),
    ("libcronet-linux-arm64.a", "8947ed692d9c6006c3a31e88cf2f272be03e2c07d6673bc3d7a8157c483b4d40"),
    ("libcronet-linux-arm64.link-flags.txt", "eb76fb6666e3939472c0bc30d26186496f40e1e722f4ba4f971315cefa7005a3"),
    ("libcronet-linux-arm64.so", "2b32ce765358ed57123df3409583b3b0cf022e0324692ab167bcfef764daff5a"),
    ("libcronet-linux-arm64_musl.a", "c42e69c678d71a616232488c004e0eba81c166c7fbe3bfd52502fe3a08f166bc"),
    ("libcronet-linux-arm64_musl.link-flags.txt", "6a314d8af0d1f1512f0bb9227c8071e5e28c5b1dc8af57b6d7382edc52525e9f"),
    ("libcronet-linux-arm_musl.a", "9bf40169d35c760e2c425c99c2d99b4b2aa3ceb3fb3d283b3cfaabd07eaaa729"),
    ("libcronet-linux-arm_musl.link-flags.txt", "6a314d8af0d1f1512f0bb9227c8071e5e28c5b1dc8af57b6d7382edc52525e9f"),
    ("libcronet-linux-loong64.a", "ddb409653b1ee0fde3b7e5523d2fe727ceed26e0051ac31319f9ff18535c397c"),
    ("libcronet-linux-loong64.link-flags.txt", "eb76fb6666e3939472c0bc30d26186496f40e1e722f4ba4f971315cefa7005a3"),
    ("libcronet-linux-loong64.so", "f9062a1c6076bc4588fe7d6b3503f9d0575579a84a193f6770ba4a8c13b9e45f"),
    ("libcronet-linux-loong64_musl.a", "e97571dbb0a2b1aff7df1db09a2f4ceeef008a2ea1b5eacfdca3a2cc5f29c3bb"),
    ("libcronet-linux-loong64_musl.link-flags.txt", "6a314d8af0d1f1512f0bb9227c8071e5e28c5b1dc8af57b6d7382edc52525e9f"),
    ("libcronet-linux-mips64le.a", "363b43ad7c5c57e84c3e4aa42176ccafa078d4db72be88b212686f055c5df29d"),
    ("libcronet-linux-mips64le.link-flags.txt", "eb76fb6666e3939472c0bc30d26186496f40e1e722f4ba4f971315cefa7005a3"),
    ("libcronet-linux-mips64le.so", "e49e029ed8c7ba46515285ad634ab0337b39ca5a91fa8c5df9d5b174f7700342"),
    ("libcronet-linux-mipsle.a", "6e497a21e291ed532208d66effc94640fa234362d286ab368ebda850751227ec"),
    ("libcronet-linux-mipsle.link-flags.txt", "2906b769664b8caba306bd9027ea645f7831df4a60accdac9380e0ca915b31c5"),
    ("libcronet-linux-mipsle.so", "23410260427e84a6aafa91242886a95c683dfcbced14dfc6b9292be73f5a5fff"),
    ("libcronet-linux-mipsle_musl.a", "3b87dd49d85712313089f1dd4d747fbd4954c12f70d323b436f7b5a8b5dafb46"),
    ("libcronet-linux-mipsle_musl.link-flags.txt", "7c4f3c9ad180baeaf47dc3f42d868f648bf93749e28a235ffc3981cc08379e75"),
    ("libcronet-linux-riscv64.a", "053174c3cd4644cc66a7ef9741a92d05921f9979294c0703701c9f930192cf6c"),
    ("libcronet-linux-riscv64.link-flags.txt", "eb76fb6666e3939472c0bc30d26186496f40e1e722f4ba4f971315cefa7005a3"),
    ("libcronet-linux-riscv64.so", "ffd9eff98dc70fc3d425b94f15d17cfb05145b1a965631491321b1f86c1ffe23"),
    ("libcronet-linux-riscv64_musl.a", "f7c2a710399f8a561bc2bddca27fd43a0d45b7e54a6c93ae9bcac8a5a0830346"),
    ("libcronet-linux-riscv64_musl.link-flags.txt", "6a314d8af0d1f1512f0bb9227c8071e5e28c5b1dc8af57b6d7382edc52525e9f"),
    ("libcronet-tvos-amd64_simulator.a", "0b68b67817e1a7b73f6f5f127448610b2ecafba53e4d1c573f6d5e35eb936c19"),
    ("libcronet-tvos-arm64.a", "77105e2c081195f9eda140b4791091b6ae1263f9056e0d1ca936c0ed0c459db2"),
    ("libcronet-tvos-arm64_simulator.a", "1dce25ed61503ce289408a41a81fc34397dfb757c9e75c345c58814529d8107c"),
    ("libcronet-windows-amd64.dll", "ec80234fcef453bbbedf826da2d906b5a5d65a0a53de08164577fb64cdf074fe"),
    ("libcronet-windows-amd64.lib", "018b05fd8c774268d75a89b670137b11c357de2a8b8fb4da8dc6c06729382976"),
    ("libcronet-windows-amd64.link-flags.txt", "e186384087ef385a1038abfecc8585d1f6ab7f9160d341ec73b272a5ce53d6d0"),
    ("libcronet-windows-amd64_md.dll", "a3f874828f12d75484effc3db2fe5e5423d4237620c3a2db1c322d5716e1b235"),
    ("libcronet-windows-amd64_md.lib", "6f8d002fd8387909d1738d8d963c047e7040f1f6591cf7ef7722990491d58e5e"),
    ("libcronet-windows-amd64_md.link-flags.txt", "5e66d459cabf06246fbdc1561bf1d6e04ccf34ed91a30dabfc25f7cd39a03334"),
    ("libcronet-windows-arm64.dll", "0b84a8cb62f050fe8884c0466e3226058519a4c94727c20e42515314b9f05b04"),
    ("libcronet-windows-arm64.lib", "ef3b20064c4e8b22e69681b60c83ecfa4eb738da53c88c28b30e2f55af3ba1e3"),
    ("libcronet-windows-arm64.link-flags.txt", "e186384087ef385a1038abfecc8585d1f6ab7f9160d341ec73b272a5ce53d6d0"),
    ("libcronet-windows-arm64_md.dll", "6929a88656585a885e5b44c57c8ff9968936cf9982275dbd8e7d1cbcf18ce7f5"),
    ("libcronet-windows-arm64_md.lib", "97a8ca210341cbb439d04c514bcfdf9c0f591fdeaca7b3c925173897009d09cd"),
    ("libcronet-windows-arm64_md.link-flags.txt", "5e66d459cabf06246fbdc1561bf1d6e04ccf34ed91a30dabfc25f7cd39a03334"),
]; // keep sorted by name

fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=build_target.rs");
    for var in [
        "CRONET_LIB_DIR",
        "CARGO_CFG_TARGET_FEATURE",
        "CRONET_STATIC_NAME",
        "CRONET_DOWNLOAD_TAG",
        "CRONET_DOWNLOAD_ASSET",
        "CRONET_DOWNLOAD_SHA256",
        "CRONET_DOWNLOAD_LINK_FLAGS_SHA256",
        "CRONET_DOWNLOAD_DIR",
        "HTTPS_PROXY",
        "HTTP_PROXY",
        "ALL_PROXY",
        "https_proxy",
        "http_proxy",
        "all_proxy",
    ] {
        println!("cargo:rerun-if-env-changed={var}");
    }

    let static_link = build_target::uses_static_link(
        &env::var("CARGO_CFG_TARGET_VENDOR").expect("Cargo sets the target vendor"),
        cfg!(feature = "dynamic"),
        cfg!(feature = "static-link"),
    );
    println!("cargo:rustc-check-cfg=cfg(cronet_static_link)");
    if static_link {
        println!("cargo:rustc-cfg=cronet_static_link");
    }

    // 1. Optionally download (and verify) the prebuilt for this target.
    // A supplied native archive takes precedence over automatic downloads.
    let downloaded = if build_target::download_enabled(
        cfg!(feature = "download"),
        cfg!(feature = "download-static"),
        static_link,
    ) && !(static_link && env::var_os("CRONET_LIB_DIR").is_some())
    {
        maybe_download(static_link)
    } else {
        None
    };

    // Expose the on-disk path to the crate so dynamic-mode users can load it.
    if let Some(path) = &downloaded {
        println!(
            "cargo:rustc-env=CRONET_DOWNLOADED_LIB_PATH={}",
            path.display()
        );
    }

    // 2. Static-link wiring.
    if static_link {
        configure_static_link(downloaded.as_deref());
    }
}

/// Map the current target to the release asset file name.
///
/// Returns `None` for targets we don't have a mapping for — callers should then
/// require `CRONET_DOWNLOAD_ASSET` to be set explicitly.
#[cfg(any(feature = "download", feature = "download-static"))]
fn asset_name(static_link: bool) -> Option<String> {
    if let Ok(explicit) = env::var("CRONET_DOWNLOAD_ASSET") {
        return Some(explicit);
    }

    let os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
    let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
    let abi = env::var("CARGO_CFG_TARGET_ABI").unwrap_or_default();

    build_target::asset_name(
        &os,
        &arch,
        &abi,
        &env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default(),
        &env::var("CARGO_CFG_TARGET_ENDIAN").unwrap_or_default(),
        static_link,
    )
    .map(|asset| {
        build_target::select_crt_asset(
            asset,
            &env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or_default(),
        )
    })
}

#[cfg(any(feature = "download", feature = "download-static"))]
fn expected_sha(asset: &str) -> Option<&'static str> {
    CHECKSUMS
        .iter()
        .find(|(name, _)| *name == asset)
        .map(|(_, sha)| *sha)
}

#[cfg(not(any(feature = "download", feature = "download-static")))]
fn maybe_download(_static_link: bool) -> Option<PathBuf> {
    None
}

#[cfg(any(feature = "download", feature = "download-static"))]
fn maybe_download(static_link: bool) -> Option<PathBuf> {
    let asset = asset_name(static_link).unwrap_or_else(|| {
        panic!(
            "libcronet-sys: cannot determine prebuilt asset for target os={:?} arch={:?}; \
             set CRONET_DOWNLOAD_ASSET explicitly",
            env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(),
            env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(),
        )
    });

    let archive = download_asset(&asset, "CRONET_DOWNLOAD_SHA256");
    if static_link && env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
        let flags_asset = format!(
            "{}.link-flags.txt",
            asset
                .strip_suffix(".lib")
                .expect("Windows static downloads must use a .lib archive")
        );
        let flags = download_asset(&flags_asset, "CRONET_DOWNLOAD_LINK_FLAGS_SHA256");
        let staged = PathBuf::from(env::var("OUT_DIR").unwrap()).join("link_flags.txt");
        std::fs::copy(flags, staged).expect("stage verified Windows system link flags");
    }
    Some(archive)
}

#[cfg(any(feature = "download", feature = "download-static"))]
fn download_asset(asset: &str, checksum_env: &str) -> PathBuf {
    use std::io::Read;

    let tag = env::var("CRONET_DOWNLOAD_TAG").unwrap_or_else(|_| "v154.0.8037.49".to_string());

    // Determine the expected checksum: pinned table first, env override second.
    let expected = expected_sha(asset)
        .map(str::to_string)
        .or_else(|| env::var(checksum_env).ok())
        .unwrap_or_else(|| {
            panic!(
                "libcronet-sys: no pinned SHA-256 for asset {asset:?} and \
                 {checksum_env} is unset; refusing to use an unverified binary"
            )
        });

    let cache_dir = env::var("CRONET_DOWNLOAD_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from(env::var("OUT_DIR").unwrap()));
    std::fs::create_dir_all(&cache_dir).expect("create download cache dir");
    let dest = cache_dir.join(asset);

    // Reuse a previously-downloaded, still-valid copy.
    if let Ok(bytes) = std::fs::read(&dest)
        && sha256_hex(&bytes) == expected
    {
        println!("cargo:warning=libcronet-sys: using cached {asset}");
        return dest;
    }
    // Missing, stale or corrupt cache entries must be downloaded and verified.

    let url = format!("{RELEASE_BASE}/{tag}/{asset}");
    println!("cargo:warning=libcronet-sys: downloading {url}");

    let agent = ureq::AgentBuilder::new()
        .try_proxy_from_env(true)
        .redirects(10)
        .timeout(std::time::Duration::from_secs(120))
        .build();
    let resp = agent
        .get(&url)
        .call()
        .unwrap_or_else(|e| panic!("libcronet-sys: download of {url} failed: {e}"));

    let mut bytes = Vec::new();
    resp.into_reader()
        .read_to_end(&mut bytes)
        .unwrap_or_else(|e| panic!("libcronet-sys: reading {url} failed: {e}"));

    let got = sha256_hex(&bytes);
    assert_eq!(
        got, expected,
        "libcronet-sys: SHA-256 mismatch for {asset}\n  expected: {expected}\n  got:      {got}\n\
         The upstream release may have changed; verify and update the pinned checksum."
    );

    // Write atomically: temp file in the same dir, then rename.
    let tmp = dest.with_extension("download.tmp");
    std::fs::write(&tmp, &bytes).expect("write downloaded binary");
    std::fs::rename(&tmp, &dest).expect("finalize downloaded binary");
    dest
}

#[cfg(any(feature = "download", feature = "download-static"))]
fn sha256_hex(bytes: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(bytes);
    let mut s = String::with_capacity(64);
    for b in digest {
        use std::fmt::Write;
        let _ = write!(s, "{b:02x}");
    }
    s
}

fn objcopy() -> Command {
    let output = Command::new(env::var_os("RUSTC").expect("Cargo sets RUSTC"))
        .args(["--print", "sysroot"])
        .output()
        .expect("locate the host Rust toolchain");
    assert!(output.status.success(), "rustc --print sysroot failed");
    let root = std::str::from_utf8(&output.stdout).expect("UTF-8 Rust toolchain path");
    let root = Path::new(root.trim());
    let bundled = root
        .join("lib/rustlib")
        .join(env::var_os("HOST").expect("Cargo sets HOST"))
        .join("bin")
        .join(format!("rust-objcopy{}", env::consts::EXE_SUFFIX));
    if !bundled.is_file() {
        return Command::new("llvm-objcopy");
    }
    // A direct cargo invocation (including cross containers) may not have
    // rustup's loader path for the bundled tool's LLVM shared library.
    let (var, dir) = match env::consts::OS {
        "windows" => ("PATH", "bin"),
        "macos" => ("DYLD_LIBRARY_PATH", "lib"),
        _ => ("LD_LIBRARY_PATH", "lib"),
    };
    let mut paths = vec![root.join(dir)];
    if let Some(existing) = env::var_os(var) {
        paths.extend(env::split_paths(&existing));
    }
    let mut command = Command::new(bundled);
    command.env(var, env::join_paths(paths).expect("objcopy loader path"));
    command
}

/// Let static glibc provide its public allocator and close entry points. The
/// C++ operators and Cronet's internal allocator dispatch still live in the
/// archive. The close and malloc_usable_size interposers need RTLD_NEXT, which
/// cannot resolve libc in a static executable.
fn stage_static_glibc_archive(source: &Path, staged: &Path) {
    let mut cmd = objcopy();
    for symbol in [
        "aligned_alloc",
        "calloc",
        "cfree",
        "close",
        "free",
        "malloc",
        "malloc_usable_size",
        "memalign",
        "posix_memalign",
        "pvalloc",
        "realloc",
        "valloc",
    ] {
        cmd.arg("--localize-symbol").arg(symbol);
    }
    copy_archive(cmd, source, staged);
}

#[cfg(feature = "static-link")]
fn stage_android_archive(source: &Path, staged: &Path) {
    use object::read::archive::ArchiveFile;
    use std::collections::BTreeSet;

    let bytes = std::fs::read(source).expect("read Android Cronet archive");
    let archive = ArchiveFile::parse(&*bytes).expect("parse Android Cronet archive");
    let mut wrappers = BTreeSet::new();
    for entry in archive
        .symbols()
        .expect("read archive index")
        .into_iter()
        .flatten()
    {
        let entry = entry.expect("read archive symbol");
        if let Some(name) = entry.name().strip_prefix(b"__wrap_") {
            wrappers.insert(std::str::from_utf8(name).expect("UTF-8 linker wrapper name"));
        }
    }
    if wrappers.is_empty() {
        std::fs::copy(source, staged).expect("stage Android Cronet archive");
        return;
    }
    // Apply Chromium's --wrap semantics inside the archive. The final Rust
    // executable can use its own allocator and its own linker wrappers.
    let mut cmd = objcopy();
    for name in wrappers {
        let wrapper = format!("cronet_sys_wrap_{name}");
        for rename in [
            format!("{name}={wrapper}"),
            format!("__wrap_{name}={wrapper}"),
            format!("__real_{name}={name}"),
        ] {
            cmd.arg("--redefine-sym").arg(rename);
        }
    }
    copy_archive(cmd, source, staged);
}

fn copy_archive(mut cmd: Command, source: &Path, staged: &Path) {
    let status = cmd
        .arg(source)
        .arg(staged)
        .status()
        .unwrap_or_else(|e| panic!("libcronet-sys: failed to run {:?}: {e}", cmd.get_program()));
    assert!(
        status.success(),
        "libcronet-sys: failed to prepare static archive {}",
        source.display()
    );
}

/// Emit link directives for static linking.
fn configure_static_link(downloaded: Option<&Path>) {
    let lib_name = env::var("CRONET_STATIC_NAME").unwrap_or_else(|_| "cronet".to_string());
    let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
    let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
    let crt_static = env::var("CARGO_CFG_TARGET_FEATURE")
        .unwrap_or_default()
        .split(',')
        .any(|feature| feature == "crt-static");
    let filename = if target_env == "msvc" {
        format!("{lib_name}.lib")
    } else {
        format!("lib{lib_name}.a")
    };
    let mut lib_dir = env::var_os("CRONET_LIB_DIR").map(PathBuf::from);
    let mut link_name = lib_name.as_str();
    let supplied = lib_dir.as_ref().map(|dir| dir.join(&filename));
    let downloaded = downloaded.filter(|p| p.extension().is_some_and(|e| e == "a" || e == "lib"));
    if let Some(source) = supplied.as_deref().or(downloaded) {
        println!("cargo:rerun-if-changed={}", source.display());
        let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
        let prepare: Option<fn(&Path, &Path)> = match (target_os.as_str(), target_env.as_str()) {
            ("linux", "gnu") if crt_static => Some(stage_static_glibc_archive),
            #[cfg(feature = "static-link")]
            ("android", _) => Some(stage_android_archive),
            _ => None,
        };
        if let Some(prepare) = prepare {
            // A consumer's -L path may also contain the original archive.
            link_name = "cronet_sys_native";
            let dir = out_dir.join("static");
            std::fs::create_dir_all(&dir).expect("create static archive staging directory");
            prepare(source, &dir.join(format!("lib{link_name}.a")));
            lib_dir = Some(dir);
        } else if supplied.is_none() {
            let staged = out_dir.join(&filename);
            if source != staged {
                std::fs::copy(source, staged).expect("stage downloaded static lib");
            }
            lib_dir = Some(out_dir);
        }
    }
    if let Some(dir) = &lib_dir {
        println!("cargo:rustc-link-search=native={}", dir.display());
    }
    println!("cargo:rustc-link-lib=static={link_name}");

    // Platform-specific runtime/system dependencies of libcronet.
    match target_os.as_str() {
        "linux" => {
            // Chromium bundles its C++ runtime in the complete archive.
            for lib in build_target::linux_libraries(&target_env) {
                println!("cargo:rustc-link-lib={lib}");
            }
        }
        "windows" => {
            assert_eq!(
                target_env, "msvc",
                "libcronet-sys: Windows static archives require an MSVC target"
            );
            let flags = lib_dir
                .as_ref()
                .expect("set CRONET_LIB_DIR for Windows static linking")
                .join("link_flags.txt");
            println!("cargo:rerun-if-changed={}", flags.display());
            let contents = std::fs::read_to_string(&flags)
                .expect("provide the link_flags.txt generated alongside cronet.lib");
            let libraries =
                build_target::windows_libraries(&contents).expect("invalid Windows link_flags.txt");
            build_target::validate_windows_crt(&libraries, crt_static)
                .expect("Cronet and Rust must use matching Windows CRTs");
            for lib in libraries {
                println!("cargo:rustc-link-lib={lib}");
            }
        }
        "macos" | "ios" | "tvos" => {
            println!("cargo:rustc-link-lib=framework=CFNetwork");
            println!("cargo:rustc-link-lib=framework=CoreFoundation");
            println!("cargo:rustc-link-lib=framework=Foundation");
            let ui_framework = if target_os == "macos" {
                "AppKit"
            } else {
                "UIKit"
            };
            println!("cargo:rustc-link-lib=framework={ui_framework}");
            println!("cargo:rustc-link-lib=framework=Security");
            println!("cargo:rustc-link-lib=framework=SystemConfiguration");
        }
        "android" => {
            // Published archives bundle libc++. For custom archives the NDK
            // linker can supply missing C++ symbols from its own sysroot.
            println!("cargo:rustc-link-lib=static:-bundle=c++_static");
            for lib in ["android", "log", "m", "dl"] {
                println!("cargo:rustc-link-lib={lib}");
            }
        }
        _ => {}
    }
}