-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathbuild.rs
More file actions
2651 lines (2442 loc) · 84.9 KB
/
Copy pathbuild.rs
File metadata and controls
2651 lines (2442 loc) · 84.9 KB
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
use fslock::LockFile;
use miniz_oxide::MZFlush;
use miniz_oxide::MZStatus;
use miniz_oxide::StreamResult;
use miniz_oxide::inflate::stream::InflateState;
use miniz_oxide::inflate::stream::inflate;
use std::collections::HashSet;
use std::env;
use std::fs;
use std::io;
use std::io::Read;
use std::io::Seek;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;
use which::which;
fn clang_resource_dir(clang_bin: &Path) -> Result<String, String> {
let output = Command::new(clang_bin)
.arg("-print-resource-dir")
.output()
.map_err(|error| {
format!("could not run {}: {error}", clang_bin.display())
})?;
if !output.status.success() {
return Err(format!(
"{} exited with {}",
clang_bin.display(),
output.status
));
}
let resource_dir = String::from_utf8(output.stdout).map_err(|error| {
format!("{} returned non-UTF-8 output: {error}", clang_bin.display())
})?;
let resource_dir = resource_dir.trim();
if resource_dir.is_empty() {
return Err(format!(
"{} returned an empty resource directory",
clang_bin.display()
));
}
Ok(resource_dir.to_string())
}
fn main() {
println!("cargo:rerun-if-changed=.gn");
println!("cargo:rerun-if-changed=BUILD.gn");
println!("cargo:rerun-if-changed=src/binding.cc");
// These are all the environment variables that we check. This is
// probably more than what is needed, but missing an important
// variable can lead to broken links when switching rusty_v8
// versions.
let envs = vec![
"CCACHE",
"CLANG_BASE_PATH",
"CXXSTDLIB",
"DENO_TRYBUILD",
"DOCS_RS",
"GN",
"GN_ARGS",
"HOST",
"LIBCLANG_PATH",
"NINJA",
"OUT_DIR",
"RUSTY_V8_ARCHIVE",
"RUSTY_V8_ARCHIVE_SHA256",
"RUSTY_V8_BINDGEN_RESOURCE_DIR",
"RUSTY_V8_GLIBC_PREFIX",
"RUSTY_V8_MIRROR",
"RUSTY_V8_MIRROR_TAG",
"RUSTY_V8_MIRROR_FALLBACK",
"RUSTY_V8_MUSL_SYSROOT",
"RUSTY_V8_SKIP_DOWNLOAD",
"RUSTY_V8_SRC_BINDING_PATH",
"RUSTY_V8_SRC_BINDING_URL",
"SCCACHE",
"V8_FORCE_DEBUG",
"V8_FROM_SOURCE",
"PYTHON",
"DISABLE_CLANG",
"EXTRA_GN_ARGS",
"PRINT_GN_ARGS",
"CARGO_ENCODED_RUSTFLAGS",
];
for env in envs {
println!("cargo:rerun-if-env-changed={env}");
}
// Detect if trybuild tests are being compiled.
let is_trybuild = env::var_os("DENO_TRYBUILD").is_some();
// Don't build V8 if "cargo doc" is being run. This is to support docs.rs.
let is_cargo_doc = env::var_os("DOCS_RS").is_some();
// Early exit
if is_cargo_doc {
print_prebuilt_src_binding_path();
return;
}
print_link_flags();
// Don't attempt rebuild but link
if is_trybuild {
println!(
"cargo:rustc-env=RUSTY_V8_SRC_BINDING_PATH={}",
env::var("RUSTY_V8_SRC_BINDING_PATH").unwrap()
);
return;
}
let is_asan = if let Some(rustflags) = env::var_os("CARGO_ENCODED_RUSTFLAGS")
{
let rustflags = rustflags.to_string_lossy();
rustflags.find("-Z sanitizer=address").is_some()
|| rustflags.find("-Zsanitizer=address").is_some()
} else {
false
};
// Cargo likes to run multiple build scripts at once sometimes.
// Nothing that follows is safe to run multiple times at once,
// because we store everything in a parent directory of OUT_DIR.
let _lockfile = acquire_lock();
check_multi_cage_config();
// Build from source
if env_bool("V8_FROM_SOURCE") {
if is_asan && env::var_os("OPT_LEVEL").unwrap_or_default() == "0" {
panic!(
"v8 crate cannot be compiled with OPT_LEVEL=0 and ASAN.\nTry `[profile.dev.package.v8] opt-level = 1`.\nAborting before miscompilations cause issues."
);
}
// cargo publish doesn't like pyc files.
unsafe {
env::set_var("PYTHONDONTWRITEBYTECODE", "1");
}
build_v8(is_asan);
build_binding();
return;
}
print_prebuilt_src_binding_path();
download_static_lib_binaries();
}
fn acquire_lock() -> LockFile {
let root = env::current_dir().unwrap();
let out_dir = env::var_os("OUT_DIR").unwrap();
let lockfilepath = root
.join(out_dir)
.parent()
.unwrap()
.parent()
.unwrap()
.join("v8.fslock");
let mut lockfile = LockFile::open(&lockfilepath)
.expect("Couldn't open lib download lockfile.");
lockfile.lock_with_pid().expect("Couldn't get lock");
println!("lockfile: {lockfilepath:?}");
lockfile
}
fn build_binding() {
// Bindgen needs Clang 21.1+ for V8's libc++ builtin type traits.
if env::var("LIBCLANG_PATH").is_err() {
eprintln!("Warning: LIBCLANG_PATH not set. Bindgen requires Clang 21.1+.");
eprintln!("Set LIBCLANG_PATH to your Clang 21 installation:");
eprintln!(" Linux: export LIBCLANG_PATH=/usr/lib/llvm-21/lib");
eprintln!(" macOS: export LIBCLANG_PATH=$(brew --prefix llvm)/lib");
eprintln!(
" Windows: set LIBCLANG_PATH to the directory containing libclang.dll"
);
}
let output = Command::new(python())
.arg("./tools/get_bindgen_args.py")
.arg("--gn-out")
.arg(build_dir().join("gn_out"))
.output()
.unwrap();
let args = String::from_utf8(output.stdout).unwrap();
let args = args.split('\0').collect::<Vec<_>>();
// Filter out V8's custom libc++ and module args from GN, we'll add them back
// manually with correct ordering for bindgen
let filtered_args: Vec<&str> = args
.iter()
.filter(|arg| {
!arg.starts_with("-fmodule")
&& !arg.starts_with("-fno-implicit-module")
&& !arg.starts_with("-Xclang")
&& !arg.contains("DUSE_LIBCXX_MODULES")
&& !arg.contains("-nostdinc++")
&& !arg.contains("-isystem")
&& !arg.contains("libc++")
})
.copied()
.collect();
// Use V8's custom libc++ headers (requires Clang 21.1+ libclang via
// LIBCLANG_PATH)
// IMPORTANT: libc++ headers must come before clang builtins
let mut clang_args = vec![
"-x".to_string(),
"c++".to_string(),
"-std=c++20".to_string(),
"-nostdinc++".to_string(),
"-Iv8/include".to_string(),
"-I.".to_string(),
"-isystembuildtools/third_party/libc++".to_string(),
"-isystemthird_party/libc++/src/include".to_string(),
"-isystemthird_party/libc++abi/src/include".to_string(),
];
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
if target_os == "macos" {
let output = Command::new("xcrun")
.args(["--show-sdk-path"])
.output()
.unwrap();
let sdk_path = String::from_utf8(output.stdout).unwrap();
clang_args.push("-isysroot".to_string());
clang_args.push(sdk_path.trim().to_string());
} else if target_os == "linux" {
// Add clang resource directory for builtin headers (stddef.h, etc)
let resource_dir = env::var("RUSTY_V8_BINDGEN_RESOURCE_DIR").ok();
if resource_dir.is_none()
&& let Ok(libclang_path) = env::var("LIBCLANG_PATH")
{
let clang_dir = PathBuf::from(&libclang_path)
.parent()
.unwrap()
.to_path_buf();
let clang_bin = clang_dir.join("bin/clang");
if let Ok(output) =
Command::new(clang_bin).arg("-print-resource-dir").output()
{
let resource_dir = String::from_utf8(output.stdout).unwrap();
clang_args.push(format!("-isystem{}/include", resource_dir.trim()));
}
}
// Add target libc headers for Linux cross-builds. bindgen already targets
// Cargo's triple (from $TARGET), but target headers may not be installed in
// the host's search paths.
let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
let musl_sysroot = env::var("RUSTY_V8_MUSL_SYSROOT").ok();
let glibc_prefix = env::var("RUSTY_V8_GLIBC_PREFIX").ok();
clang_args.extend(explicit_linux_bindgen_args(
&target_env,
resource_dir.as_deref(),
musl_sysroot.as_deref(),
glibc_prefix.as_deref(),
));
} else if target_os == "windows" {
// libclang otherwise discovers the runner's system Clang resource
// directory, which may not match the pinned Chromium libclang.
if let Ok(libclang_path) = env::var("LIBCLANG_PATH") {
let libclang_path = PathBuf::from(libclang_path);
if let Some(clang_dir) = libclang_path.parent() {
let clang_bin = clang_dir.join("bin/clang-cl.exe");
match clang_resource_dir(&clang_bin) {
Ok(resource_dir) => {
println!("clang_resource_dir (from LIBCLANG_PATH) {resource_dir}");
clang_args.push(format!("-resource-dir={resource_dir}"));
}
Err(error) => println!(
"cargo:warning=Skipping Clang resource directory override: {error}"
),
}
} else {
println!(
"cargo:warning=Skipping Clang resource directory override: \
LIBCLANG_PATH has no parent directory"
);
}
}
} else if target_os == "ios" {
// iOS: point bindgen at the iOS (device) or iOS-simulator SDK and set the
// matching clang target triple so the V8 headers parse correctly.
let target_triple = env::var("TARGET").unwrap();
let is_sim = target_triple.ends_with("-sim")
|| target_triple.starts_with("x86_64-apple-ios");
let sdk = if is_sim {
"iphonesimulator"
} else {
"iphoneos"
};
let output = Command::new("xcrun")
.args(["--sdk", sdk, "--show-sdk-path"])
.output()
.unwrap();
let sdk_path = String::from_utf8(output.stdout).unwrap();
clang_args.push("-isysroot".to_string());
clang_args.push(sdk_path.trim().to_string());
let clang_target = if is_sim {
"arm64-apple-ios-simulator"
} else {
"arm64-apple-ios"
};
clang_args.push(format!("--target={clang_target}"));
}
let bindings = bindgen::Builder::default()
.header("src/binding.hpp")
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.clang_args(clang_args)
.clang_args(filtered_args)
.generate_cstr(true)
.rustified_enum(".*UseCounterFeature")
.rustified_enum(".*ModuleImportPhase")
.rustified_enum(".*Intercepted")
.bitfield_enum(".*GCType")
.bitfield_enum(".*GCCallbackFlags")
.allowlist_item("v8__.*")
.allowlist_item("cppgc__.*")
.allowlist_item("RustObj")
.allowlist_item("memory_span_t")
.allowlist_item("const_memory_span_t")
.allowlist_item("ExternalConstOneByteStringResource")
.blocklist_item("cppgc.*Visitor")
.blocklist_item("RustObj.*Trace")
.generate()
.expect("Unable to generate bindings");
let out_path = build_dir().join("gn_out").join("src_binding.rs");
println!(
"cargo:rustc-env=RUSTY_V8_SRC_BINDING_PATH={}",
out_path.display()
);
bindings
.write_to_file(out_path)
.expect("Couldn't write bindings!");
}
/// Builds the explicit Linux header-search arguments for bindgen.
///
/// An explicit Clang resource directory uses `-resource-dir` so Clang resolves
/// the complete builtin resource layout. The auto-discovery path only adds the
/// discovered `include` directory because it is supplementing libclang's
/// existing resource setup.
///
/// Musl receives `--sysroot` because its input is a complete sysroot. A GNU
/// cross prefix instead stores target headers directly under `<prefix>/include`;
/// treating it as a sysroot would make Clang search `<prefix>/usr/include`.
/// bindgen supplies the Clang target from Cargo's `TARGET` environment variable.
fn explicit_linux_bindgen_args(
target_env: &str,
resource_dir: Option<&str>,
musl_sysroot: Option<&str>,
glibc_prefix: Option<&str>,
) -> Vec<String> {
let mut args = Vec::new();
if let Some(resource_dir) = resource_dir {
args.push(format!("-resource-dir={resource_dir}"));
}
match target_env {
"musl" => {
if let Some(sysroot) = musl_sysroot {
args.push(format!("--sysroot={sysroot}"));
}
}
"gnu" => {
if let Some(prefix) = glibc_prefix {
args.push(format!("-isystem{prefix}/include"));
}
}
_ => {}
}
args
}
fn build_v8(is_asan: bool) {
unsafe {
env::set_var("DEPOT_TOOLS_WIN_TOOLCHAIN", "0");
}
if need_gn_ninja_download() {
download_ninja_gn_binaries();
}
download_rust_toolchain();
// `#[cfg(...)]` attributes don't work as expected from build.rs -- they refer to the configuration
// of the host system which the build.rs script will be running on. In short, `cfg!(target_<os/arch>)`
// is actually the host os/arch instead of target os/arch while cross compiling. Instead, Environment variables
// are the officially approach to get the target os/arch in build.rs.
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
// On windows, rustc cannot link with a V8 debug build.
let mut gn_args = if is_debug() && target_os != "windows" {
// Note: When building for Android aarch64-qemu, use release instead of debug.
vec!["is_debug=true".to_string()]
} else {
vec!["is_debug=false".to_string()]
};
if is_asan {
gn_args.push("is_asan=true".to_string());
}
gn_args.push(format!(
"use_custom_libcxx={}",
env::var("CARGO_FEATURE_USE_CUSTOM_LIBCXX").is_ok()
));
let extra_args = {
if env::var("CARGO_FEATURE_V8_ENABLE_SANDBOX").is_ok() {
vec![
// Enable pointer compression (along with its dependencies)
"v8_enable_sandbox=true",
"v8_enable_external_code_space=true", // Needed for sandbox
"v8_enable_pointer_compression=true",
// Note that sandbox requires shared_ro_heap and verify_heap
// to be true/default
]
} else {
let mut opts = vec![
// Disable sandbox
"v8_enable_sandbox=false",
];
if env::var("CARGO_FEATURE_V8_ENABLE_POINTER_COMPRESSION").is_ok() {
opts.push("v8_enable_pointer_compression=true");
} else {
opts.push("v8_enable_pointer_compression=false");
}
if multi_cage_requested() {
// Give each isolate group its own pointer compression cage, which is
// what `v8::IsolateGroup::CanCreateNewGroups()` reports on. V8 turns
// `v8_enable_partition_alloc` and `v8_enable_external_code_space` off
// by themselves in this mode; both of their defaults are derived from
// the shared cage flag.
opts.push("v8_enable_pointer_compression_shared_cage=false");
}
opts
}
};
for arg in extra_args {
gn_args.push(arg.to_string());
}
gn_args.push(format!(
"v8_enable_v8_checks={}",
env::var("CARGO_FEATURE_V8_ENABLE_V8_CHECKS").is_ok()
));
// Fix GN's host_cpu detection when using x86_64 bins on Apple Silicon
if cfg!(target_os = "macos") && cfg!(target_arch = "aarch64") {
gn_args.push("host_cpu=\"arm64\"".to_string());
}
if env::var_os("DISABLE_CLANG").is_some() {
gn_args.push("is_clang=false".into());
// -gline-tables-only is Clang-only
gn_args.push("line_tables_only=false".into());
} else if let Some(clang_base_path) = find_compatible_system_clang() {
println!("clang_base_path (system): {}", clang_base_path.display());
gn_args.push(format!("clang_base_path={clang_base_path:?}"));
gn_args.push("treat_warnings_as_errors=false".to_string());
} else {
println!("using Chromium's clang");
let clang_base_path = clang_download();
gn_args.push(format!("clang_base_path={clang_base_path:?}"));
if target_os == "android" && target_arch == "aarch64" {
gn_args.push("treat_warnings_as_errors=false".to_string());
}
}
if let Some(p) = env::var_os("SCCACHE") {
cc_wrapper(&mut gn_args, Path::new(&p));
} else if let Ok(p) = which("sccache") {
cc_wrapper(&mut gn_args, &p);
} else if let Some(p) = env::var_os("CCACHE") {
cc_wrapper(&mut gn_args, Path::new(&p));
} else if let Ok(p) = which("ccache") {
cc_wrapper(&mut gn_args, &p);
} else {
println!("cargo:warning=Not using sccache or ccache");
}
// Forward caller-provided GN args verbatim.
let gn_args_env = env::var("GN_ARGS").unwrap_or_default();
if !gn_args_env.trim().is_empty() {
gn_args.push(gn_args_env.clone());
}
// rusty_v8 ships a single static archive that downstream crates may link
// into a shared library (cdylib). On Linux, V8's default "local-exec" TLS
// model emits R_X86_64_TPOFF32 relocations against thread-locals such as
// `g_current_isolate_`, which lld refuses to place in a `-shared` object,
// so any cdylib that links the archive fails to link. Enabling this V8 GN
// arg routes the `V8_TLS_USED_IN_LIBRARY` define into both `internal_config`
// and the `features` config, switching V8 to the shared-library-safe TLS
// path (local-dynamic model + out-of-line accessor) uniformly across V8's
// own sources and rusty_v8's bindings.
if target_os == "linux"
&& !gn_args_env.contains("v8_monolithic_for_shared_library")
{
gn_args.push("v8_monolithic_for_shared_library=true".to_string());
}
// cross-compilation setup
if target_arch == "aarch64" {
gn_args.push(r#"target_cpu="arm64""#.to_string());
if target_os == "linux" {
gn_args.push("use_sysroot=true".to_string());
maybe_install_sysroot("arm64");
maybe_install_sysroot("amd64");
}
}
// Without this, GN defaults target_cpu to host_cpu, which the Apple Silicon
// block above pins to "arm64". An x86_64 macOS build hosted on arm64 (as CI
// does, to stay on the free standard runner) would then silently produce an
// arm64 V8 for an x86_64 Rust target. On an x86_64 host this matches GN's
// own default and is a no-op.
if target_arch == "x86_64" {
gn_args.push(r#"target_cpu="x64""#.to_string());
}
if target_arch == "arm" {
gn_args.push(r#"target_cpu="arm""#.to_string());
gn_args.push(r#"v8_target_cpu="arm""#.to_string());
gn_args.push("use_sysroot=true".to_string());
maybe_install_sysroot("i386");
maybe_install_sysroot("arm");
}
if target_arch == "riscv64" {
gn_args.push(r#"target_cpu="riscv64""#.to_string());
// Cross compiling needs to set v8_target_cpu
gn_args.push(r#"v8_target_cpu="riscv64""#.to_string());
if target_os == "linux" {
gn_args.push("use_sysroot=true".to_string());
maybe_install_sysroot("riscv64");
maybe_install_sysroot("amd64");
}
}
// musl libc. V8's build targets glibc by default; the vendored build config
// grows a target-scoped `use_musl` arg (see //build/config/rust.gni,
// sysroot.gni, c++/BUILD.gn, toolchain/*). The final librusty_v8.a is a
// static archive of musl-compiled objects (never linked here), so the target
// toolchain needs only musl headers -- the executable build tools (torque,
// mksnapshot, code generators) are built with a separate glibc toolchain so
// they link and run on the (glibc) build host.
let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
if target_env == "musl" && target_os == "linux" {
gn_args.push("use_musl=true".to_string());
// V8-as-a-library has no glib dependency; skip it so a musl target_sysroot
// doesn't send pkg-config looking for glib inside the sysroot.
gn_args.push("use_glib=false".to_string());
// Build libstd + V8's internal Rust crates from source for the musl triple;
// V8's vendored Rust toolchain only ships a glibc host std.
gn_args.push("rust_prebuilt_stdlib=false".to_string());
// Some V8 sources have glibc-only code paths (e.g. execinfo-based
// backtraces in stack_trace_posix.cc) whose helpers are unused on musl,
// tripping -Werror,-Wunused-const-variable. Like the iOS/Android cross
// builds, don't treat warnings as errors here.
gn_args.push("treat_warnings_as_errors=false".to_string());
match target_arch.as_str() {
"x86_64" => {
// Host cpu == target cpu, so V8 would build the executable build tools
// with the (musl) default toolchain. Force the host and snapshot
// toolchains to a dedicated glibc toolchain so those tools stay glibc.
let glibc = "//build/toolchain/linux:clang_x64_glibc";
gn_args.push(format!("host_toolchain=\"{glibc}\""));
gn_args.push(format!("v8_snapshot_toolchain=\"{glibc}\""));
// That glibc toolchain builds against the amd64 sysroot, same as the
// host side of the aarch64/riscv64 cross builds.
maybe_install_sysroot("amd64");
}
"aarch64" => {
// Cross build (x64 host -> arm64 target). The host (clang_x64) and
// snapshot (clang_x64_v8_arm64) toolchains are already non-default, so
// the target-scoped `use_musl` guard keeps them glibc automatically --
// no toolchain overrides needed. target_cpu and the amd64/arm64
// sysroots are set by the aarch64 cross-compilation block above.
}
other => panic!(
"musl builds are only supported for x86_64 and aarch64 (got {other})"
),
}
// Cross-compiling on a glibc host needs a musl sysroot for the target's
// headers/libs. Native musl builds (e.g. on Alpine) can leave this unset.
if let Ok(sysroot) = env::var("RUSTY_V8_MUSL_SYSROOT") {
gn_args.push(format!("target_sysroot=\"{sysroot}\""));
}
}
let target_triple = env::var("TARGET").unwrap();
// check if the target triple describes a non-native environment
if target_triple != env::var("HOST").unwrap() && target_os == "android" {
let arch = if target_arch == "x86_64" {
"x64"
} else if target_arch == "aarch64" {
"arm64"
} else {
"unknown"
};
if target_arch == "x86_64" {
maybe_install_sysroot("amd64");
}
gn_args.push(format!(r#"v8_target_cpu="{arch}""#).to_string());
gn_args.push(format!(r#"target_cpu="{arch}""#).to_string());
gn_args.push(r#"target_os="android""#.to_string());
gn_args.push("treat_warnings_as_errors=false".to_string());
gn_args.push("use_sysroot=true".to_string());
// NDK 23 and above removes libgcc entirely.
// https://github.com/rust-lang/rust/pull/85806
if !Path::new("./third_party/android_ndk/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android24-clang++").exists() {
assert!(Command::new("curl")
.arg("-L")
.arg("-o").arg("./third_party/android-ndk-r26c-linux.zip")
.arg("https://dl.google.com/android/repository/android-ndk-r26c-linux.zip")
.status()
.unwrap()
.success());
assert!(Command::new("unzip")
.arg("-d").arg("./third_party/")
.arg("-o")
.arg("-q")
.arg("./third_party/android-ndk-r26c-linux.zip")
.status()
.unwrap()
.success());
fs::rename("./third_party/android-ndk-r26c", "./third_party/android_ndk").unwrap();
fs::remove_file("./third_party/android-ndk-r26c-linux.zip").unwrap();
}
static CHROMIUM_URI: &str = "https://chromium.googlesource.com";
maybe_clone_repo(
"./third_party/android_platform",
&format!("{CHROMIUM_URI}/chromium/src/third_party/android_platform.git",),
);
maybe_clone_repo(
"./third_party/catapult",
&format!("{CHROMIUM_URI}/catapult.git"),
);
}
// iOS / iOS-simulator. iOS denies the JIT entitlement to non-WebKit apps, so
// a device build must be jitless -- which in turn requires V8's optimizing
// tiers (Sparkplug/Maglev/Turbofan) and WebAssembly to be disabled. The
// simulator runs on the host and could keep the JIT, but WebAssembly is
// disabled there too because Torque can't generate the Wasm builtins in this
// configuration. `target_cpu="arm64"` is already set above for aarch64.
// Pass an explicit `target_os="ios"` in GN_ARGS to fully override this.
if target_os == "ios" && !gn_args_env.contains(r#"target_os="ios""#) {
let is_sim = target_triple.ends_with("-sim")
|| target_triple.starts_with("x86_64-apple-ios");
gn_args.push(r#"target_os="ios""#.to_string());
gn_args.push(format!(
r#"target_environment="{}""#,
if is_sim { "simulator" } else { "device" }
));
gn_args.push(r#"ios_deployment_target="14.0""#.to_string());
gn_args.push("ios_enable_code_signing=false".to_string());
gn_args.push("treat_warnings_as_errors=false".to_string());
gn_args.push("v8_enable_webassembly=false".to_string());
if !is_sim {
// Device: no JIT permitted -> jitless build, all tiers off.
gn_args.push("v8_jitless=true".to_string());
gn_args.push("v8_enable_sparkplug=false".to_string());
gn_args.push("v8_enable_maglev=false".to_string());
gn_args.push("v8_enable_turbofan=false".to_string());
}
}
if target_triple.starts_with("i686-") {
gn_args.push(r#"target_cpu="x86""#.to_string());
}
let gn_out = run_gn_gen(&gn_args);
assert!(gn_out.exists());
assert!(gn_out.join("args.gn").exists());
if env_bool("PRINT_GN_ARGS") {
print_gn_args(&gn_out);
}
build("rusty_v8", None);
}
fn print_gn_args(gn_out_dir: &Path) {
assert!(
Command::new(gn())
.arg(format!("--script-executable={}", python()))
.arg("args")
.arg(gn_out_dir)
.arg("--list")
.status()
.unwrap()
.success()
);
}
fn maybe_clone_repo(dest: &str, repo: &str) {
if !Path::new(&dest).exists() {
assert!(
Command::new("git")
.arg("clone")
.arg("--depth=1")
.arg(repo)
.arg(dest)
.status()
.unwrap()
.success()
);
}
}
fn maybe_install_sysroot(arch: &str) {
let sysroot_path = format!("build/linux/debian_sid_{arch}-sysroot");
if !PathBuf::from(sysroot_path).is_dir() {
assert!(
Command::new(python())
.arg("./build/linux/sysroot_scripts/install-sysroot.py")
.arg(format!("--arch={arch}"))
.status()
.unwrap()
.success()
);
}
}
fn download_ninja_gn_binaries() {
let target_dir = build_dir().join("ninja_gn_binaries");
let gn = target_dir.join("gn").join("gn");
let ninja = target_dir.join("ninja").join("ninja");
#[cfg(windows)]
let gn = gn.with_extension("exe");
#[cfg(windows)]
let ninja = ninja.with_extension("exe");
if !gn.exists() || !ninja.exists() {
assert!(
Command::new(python())
.arg("./tools/ninja_gn_binaries.py")
.arg("--dir")
.arg(&target_dir)
.status()
.unwrap()
.success()
);
}
assert!(gn.exists());
assert!(ninja.exists());
unsafe {
env::set_var("GN", gn);
}
if env::var("NINJA").is_err() {
unsafe {
env::set_var("NINJA", ninja);
}
}
}
fn download_rust_toolchain() {
assert!(
Command::new(python())
.arg("./tools/rust_toolchain.py")
.status()
.unwrap()
.success()
);
}
fn prebuilt_profile() -> &'static str {
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
// Use v8 in release mode unless $V8_FORCE_DEBUG=true
// Note: we always use the release build on windows.
if target_os != "windows" && env_bool("V8_FORCE_DEBUG") {
"debug"
} else {
"release"
}
}
fn multi_cage_requested() -> bool {
env::var("CARGO_FEATURE_V8_ENABLE_MULTI_CAGE").is_ok()
}
/// The multi-cage configuration differs from the published `_ptrcomp` builds in
/// ways that don't show up at link time: it swaps
/// `V8_COMPRESS_POINTERS_IN_SHARED_CAGE` for
/// `V8_COMPRESS_POINTERS_IN_MULTIPLE_CAGES` and turns off partition_alloc and
/// the external code space. Nothing publishes a static library built that way,
/// so without this check enabling the feature would quietly download the shared
/// cage `_ptrcomp` library, link successfully, and leave
/// `IsolateGroup::can_create_new_groups()` returning false at run time.
fn check_multi_cage_config() {
if !multi_cage_requested() {
return;
}
assert!(
env::var("CARGO_FEATURE_V8_ENABLE_SANDBOX").is_err(),
"The 'v8_enable_multi_cage' and 'v8_enable_sandbox' features are mutually \
exclusive: V8's sandbox requires a shared pointer compression cage."
);
// A custom archive is the other supported way to consume an experimental
// configuration, so take the embedder's word for it if one is supplied.
assert!(
env_bool("V8_FROM_SOURCE") || env::var_os("RUSTY_V8_ARCHIVE").is_some(),
"The 'v8_enable_multi_cage' feature requires building V8 from source (set \
V8_FROM_SOURCE=1) or supplying a matching library via RUSTY_V8_ARCHIVE. \
No prebuilt libraries are published for this configuration, and the \
prebuilt '_ptrcomp' libraries use a shared cage, in which isolate groups \
cannot be created."
);
}
fn prebuilt_features_suffix() -> String {
let mut features = String::new();
if env::var("CARGO_FEATURE_V8_ENABLE_POINTER_COMPRESSION").is_ok() {
features.push_str("_ptrcomp");
}
if env::var("CARGO_FEATURE_V8_ENABLE_SANDBOX").is_ok() {
features.push_str("_sandbox");
}
features
}
fn static_lib_name(suffix: &str) -> String {
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
if target_os == "windows" {
format!("rusty_v8{suffix}.lib")
} else {
format!("librusty_v8{suffix}.a")
}
}
const DEFAULT_ARTIFACT_BASE: &str =
"https://github.com/denoland/rusty_v8/releases/download";
/// Values substituted into artifact URLs and URL templates.
struct UrlVars<'a> {
/// Release tag path segment, e.g. `v152.0.0` (see [`resolved_tag`]).
tag: &'a str,
/// Raw `CARGO_PKG_VERSION`, without the `v` prefix.
version: &'a str,
/// The `TARGET` triple.
target: &'a str,
/// `release` or `debug`, from [`prebuilt_profile`].
profile: &'a str,
/// Feature suffix from [`prebuilt_features_suffix`].
features: &'a str,
/// The full artifact filename.
file: &'a str,
}
/// The tag path segment under which prebuilt artifacts are looked up.
/// `RUSTY_V8_MIRROR_TAG` overrides the default `v{version}` verbatim (no `v`
/// is prepended), so mirrors can serve artifacts from e.g. the last published
/// tag while `Cargo.toml` carries an unpublished version.
fn resolved_tag(tag_override: Option<&str>, version: &str) -> String {
match tag_override {
Some(tag) => tag.to_string(),
None => format!("v{version}"),
}
}
/// Expand `{tag}`, `{version}`, `{target}`, `{profile}`, `{features}` and
/// `{file}` placeholders in a `RUSTY_V8_MIRROR` template.
fn expand_url_template(template: &str, vars: &UrlVars) -> String {
template
.replace("{tag}", vars.tag)
.replace("{version}", vars.version)
.replace("{target}", vars.target)
.replace("{profile}", vars.profile)
.replace("{features}", vars.features)
.replace("{file}", vars.file)
}
fn is_remote_url(url: &str) -> bool {
url.starts_with("http:") || url.starts_with("https:")
}
/// The ordered list of URLs an artifact is fetched from:
///
/// 1. The mirror, if `RUSTY_V8_MIRROR` is set. A value containing a `{`
/// placeholder is treated as a full URL template; otherwise it is a base
/// and the artifact is looked up at `{base}/{tag}/{file}`.
/// 2. For plain (non-template) filesystem mirrors only: the flat layout
/// `{base}/{file}`, so a directory of downloaded artifacts works as a
/// cache without tag subdirectories.
/// 3. The upstream GitHub release. When a mirror is configured this entry is
/// only present with `fallback` (`RUSTY_V8_MIRROR_FALLBACK=1`): a mirror
/// fails closed by default and never silently reaches the network.
fn candidate_urls(
mirror: Option<&str>,
fallback: bool,
vars: &UrlVars,
) -> Vec<String> {
let mut urls = Vec::new();
if let Some(mirror) = mirror {
if mirror.contains('{') {
urls.push(expand_url_template(mirror, vars));
} else {
urls.push(format!("{mirror}/{}/{}", vars.tag, vars.file));
if !is_remote_url(mirror) {
urls.push(format!("{mirror}/{}", vars.file));
}
}
}
if mirror.is_none() || fallback {
urls.push(format!(
"{DEFAULT_ARTIFACT_BASE}/{}/{}",
vars.tag, vars.file
));
}
urls
}
/// [`candidate_urls`] with all inputs read from the environment.
fn artifact_url_candidates(file: &str) -> Vec<String> {
let version = env::var("CARGO_PKG_VERSION").unwrap();
let tag_override = env::var("RUSTY_V8_MIRROR_TAG").ok();
let tag = resolved_tag(tag_override.as_deref(), &version);
let target = env::var("TARGET").unwrap();
let features = prebuilt_features_suffix();
let vars = UrlVars {
tag: &tag,
version: &version,
target: &target,
profile: prebuilt_profile(),
features: &features,
file,
};
let mirror = env::var("RUSTY_V8_MIRROR").ok();
let fallback = env_bool("RUSTY_V8_MIRROR_FALLBACK");
if mirror.is_some() && !fallback {
println!(
"RUSTY_V8_MIRROR is set; not falling back to {DEFAULT_ARTIFACT_BASE} \
(set RUSTY_V8_MIRROR_FALLBACK=1 to enable)"
);
}
candidate_urls(mirror.as_deref(), fallback, &vars)
}
/// Candidate locations for a `RUSTY_V8_ARCHIVE` value. A value naming an
/// existing directory is searched for the expected artifact filename
/// (gzipped first, then plain); anything else is used verbatim as a URL or
/// file path, exactly as before.
fn archive_urls(archive: &str, gz_name: &str, plain_name: &str) -> Vec<String> {
let path = Path::new(archive);
if path.is_dir() {
vec![
path.join(gz_name).to_string_lossy().into_owned(),
path.join(plain_name).to_string_lossy().into_owned(),
]
} else {
vec![archive.to_string()]
}
}
/// How the prebuilt src binding file is obtained.
/// `RUSTY_V8_SRC_BINDING_PATH` names a local file that is used directly (no
/// download, no copy) and wins over `RUSTY_V8_SRC_BINDING_URL`, which
/// short-circuits the mirror/upstream candidates with exactly one URL or
/// path to fetch from -- mirroring what `RUSTY_V8_ARCHIVE` does for the
/// static lib. With neither set the usual candidate list is tried.
#[derive(Debug, PartialEq)]
enum BindingSource {
Path(String),
Url(String),
Candidates,
}
fn resolve_binding_source(
path: Option<String>,
url: Option<String>,
) -> BindingSource {
// A set-but-empty URL counts as unset, like the boolean toggles.
let url = url.filter(|url| !url.is_empty());
match (path, url) {
(Some(path), _) => BindingSource::Path(path),
(None, Some(url)) => BindingSource::Url(url),
(None, None) => BindingSource::Candidates,
}
}
/// Cache key under `~/.cargo/.rusty_v8`: `<tag>/<artifact filename>`,
/// escaped with [`replace_non_alphanumeric`] to form the file name. Keying
/// on the tag and filename (rather than the full source URL) lets the cache
/// survive switching mirrors without re-downloading identical bytes.
fn artifact_cache_key(file: &str) -> String {
let version = env::var("CARGO_PKG_VERSION").unwrap();