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
use crate::{write_file_if_changed, CargoCommandVersioned};
use std::{
borrow::ToOwned,
collections::HashSet,
env, fs,
hash::{Hash, Hasher},
ops::Deref,
path::{Path, PathBuf},
process,
};
use toml::value::Table;
use build_helper::rerun_if_changed;
use cargo_metadata::{Metadata, MetadataCommand};
use walkdir::WalkDir;
fn colorize_info_message(message: &str) -> String {
if super::color_output_enabled() {
ansi_term::Color::Yellow.bold().paint(message).to_string()
} else {
message.into()
}
}
pub struct WasmBinaryBloaty(PathBuf);
impl WasmBinaryBloaty {
pub fn wasm_binary_bloaty_path_escaped(&self) -> String {
self.0.display().to_string().escape_default().to_string()
}
}
pub struct WasmBinary(PathBuf);
impl WasmBinary {
pub fn wasm_binary_path(&self) -> &Path {
&self.0
}
pub fn wasm_binary_path_escaped(&self) -> String {
self.0.display().to_string().escape_default().to_string()
}
}
fn crate_metadata(cargo_manifest: &Path) -> Metadata {
let mut cargo_lock = cargo_manifest.to_path_buf();
cargo_lock.set_file_name("Cargo.lock");
let cargo_lock_existed = cargo_lock.exists();
let crate_metadata = MetadataCommand::new()
.manifest_path(cargo_manifest)
.exec()
.expect("`cargo metadata` can not fail on project `Cargo.toml`; qed");
if !cargo_lock_existed {
let _ = fs::remove_file(&cargo_lock);
}
crate_metadata
}
pub(crate) fn create_and_compile(
project_cargo_toml: &Path,
default_rustflags: &str,
cargo_cmd: CargoCommandVersioned,
features_to_enable: Vec<String>,
wasm_binary_name: Option<String>,
) -> (Option<WasmBinary>, WasmBinaryBloaty) {
let wasm_workspace_root = get_wasm_workspace_root();
let wasm_workspace = wasm_workspace_root.join("wbuild");
let crate_metadata = crate_metadata(project_cargo_toml);
let project = create_project(
project_cargo_toml,
&wasm_workspace,
&crate_metadata,
crate_metadata.workspace_root.as_ref(),
features_to_enable,
);
build_project(&project, default_rustflags, cargo_cmd);
let (wasm_binary, wasm_binary_compressed, bloaty) =
compact_wasm_file(&project, project_cargo_toml, wasm_binary_name);
wasm_binary
.as_ref()
.map(|wasm_binary| copy_wasm_to_target_directory(project_cargo_toml, wasm_binary));
wasm_binary_compressed.as_ref().map(|wasm_binary_compressed| {
copy_wasm_to_target_directory(project_cargo_toml, wasm_binary_compressed)
});
generate_rerun_if_changed_instructions(project_cargo_toml, &project, &wasm_workspace);
(wasm_binary_compressed.or(wasm_binary), bloaty)
}
fn find_cargo_lock(cargo_manifest: &Path) -> Option<PathBuf> {
fn find_impl(mut path: PathBuf) -> Option<PathBuf> {
loop {
if path.join("Cargo.lock").exists() {
return Some(path.join("Cargo.lock"))
}
if !path.pop() {
return None
}
}
}
if let Some(path) = find_impl(build_helper::out_dir()) {
return Some(path)
}
if let Some(path) = find_impl(cargo_manifest.to_path_buf()) {
return Some(path)
}
build_helper::warning!(
"Could not find `Cargo.lock` for `{}`, while searching from `{}`.",
cargo_manifest.display(),
build_helper::out_dir().display()
);
None
}
fn get_crate_name(cargo_manifest: &Path) -> String {
let cargo_toml: Table = toml::from_str(
&fs::read_to_string(cargo_manifest).expect("File exists as checked before; qed"),
)
.expect("Cargo manifest is a valid toml file; qed");
let package = cargo_toml
.get("package")
.and_then(|t| t.as_table())
.expect("`package` key exists in valid `Cargo.toml`; qed");
package
.get("name")
.and_then(|p| p.as_str())
.map(ToOwned::to_owned)
.expect("Package name exists; qed")
}
fn get_wasm_binary_name(cargo_manifest: &Path) -> String {
get_crate_name(cargo_manifest).replace('-', "_")
}
fn get_wasm_workspace_root() -> PathBuf {
let mut out_dir = build_helper::out_dir();
loop {
match out_dir.parent() {
Some(parent) if out_dir.ends_with("build") => return parent.to_path_buf(),
_ =>
if !out_dir.pop() {
break
},
}
}
panic!("Could not find target dir in: {}", build_helper::out_dir().display())
}
fn create_project_cargo_toml(
wasm_workspace: &Path,
workspace_root_path: &Path,
crate_name: &str,
crate_path: &Path,
wasm_binary: &str,
enabled_features: impl Iterator<Item = String>,
) {
let mut workspace_toml: Table = toml::from_str(
&fs::read_to_string(workspace_root_path.join("Cargo.toml"))
.expect("Workspace root `Cargo.toml` exists; qed"),
)
.expect("Workspace root `Cargo.toml` is a valid toml file; qed");
let mut wasm_workspace_toml = Table::new();
let mut release_profile = Table::new();
release_profile.insert("panic".into(), "abort".into());
release_profile.insert("lto".into(), true.into());
let mut dev_profile = Table::new();
dev_profile.insert("panic".into(), "abort".into());
let mut profile = Table::new();
profile.insert("release".into(), release_profile.into());
profile.insert("dev".into(), dev_profile.into());
wasm_workspace_toml.insert("profile".into(), profile.into());
while let Some(mut patch) =
workspace_toml.remove("patch").and_then(|p| p.try_into::<Table>().ok())
{
patch
.iter_mut()
.filter_map(|p| {
p.1.as_table_mut().map(|t| t.iter_mut().filter_map(|t| t.1.as_table_mut()))
})
.flatten()
.for_each(|p| {
p.iter_mut().filter(|(k, _)| k == &"path").for_each(|(_, v)| {
if let Some(path) = v.as_str().map(PathBuf::from) {
if path.is_relative() {
*v = workspace_root_path.join(path).display().to_string().into();
}
}
})
});
wasm_workspace_toml.insert("patch".into(), patch.into());
}
let mut package = Table::new();
package.insert("name".into(), format!("{}-wasm", crate_name).into());
package.insert("version".into(), "1.0.0".into());
package.insert("edition".into(), "2018".into());
package.insert("resolver".into(), "2".into());
wasm_workspace_toml.insert("package".into(), package.into());
let mut lib = Table::new();
lib.insert("name".into(), wasm_binary.into());
lib.insert("crate-type".into(), vec!["cdylib".to_string()].into());
wasm_workspace_toml.insert("lib".into(), lib.into());
let mut dependencies = Table::new();
let mut wasm_project = Table::new();
wasm_project.insert("package".into(), crate_name.into());
wasm_project.insert("path".into(), crate_path.display().to_string().into());
wasm_project.insert("default-features".into(), false.into());
wasm_project.insert("features".into(), enabled_features.collect::<Vec<_>>().into());
dependencies.insert("wasm-project".into(), wasm_project.into());
wasm_workspace_toml.insert("dependencies".into(), dependencies.into());
wasm_workspace_toml.insert("workspace".into(), Table::new().into());
write_file_if_changed(
wasm_workspace.join("Cargo.toml"),
toml::to_string_pretty(&wasm_workspace_toml).expect("Wasm workspace toml is valid; qed"),
);
}
fn find_package_by_manifest_path<'a>(
manifest_path: &Path,
crate_metadata: &'a cargo_metadata::Metadata,
) -> &'a cargo_metadata::Package {
crate_metadata
.packages
.iter()
.find(|p| p.manifest_path == manifest_path)
.expect("Wasm project exists in its own metadata; qed")
}
fn project_enabled_features(
cargo_manifest: &Path,
crate_metadata: &cargo_metadata::Metadata,
) -> Vec<String> {
let package = find_package_by_manifest_path(cargo_manifest, crate_metadata);
let mut enabled_features = package
.features
.keys()
.filter(|f| {
let mut feature_env = f.replace("-", "_");
feature_env.make_ascii_uppercase();
*f != "std" &&
*f != "default" && env::var(format!("CARGO_FEATURE_{}", feature_env))
.map(|v| v == "1")
.unwrap_or_default()
})
.cloned()
.collect::<Vec<_>>();
enabled_features.sort();
enabled_features
}
fn has_runtime_wasm_feature_declared(
cargo_manifest: &Path,
crate_metadata: &cargo_metadata::Metadata,
) -> bool {
let package = find_package_by_manifest_path(cargo_manifest, crate_metadata);
package.features.keys().any(|k| k == "runtime-wasm")
}
fn create_project(
project_cargo_toml: &Path,
wasm_workspace: &Path,
crate_metadata: &Metadata,
workspace_root_path: &Path,
features_to_enable: Vec<String>,
) -> PathBuf {
let crate_name = get_crate_name(project_cargo_toml);
let crate_path = project_cargo_toml.parent().expect("Parent path exists; qed");
let wasm_binary = get_wasm_binary_name(project_cargo_toml);
let wasm_project_folder = wasm_workspace.join(&crate_name);
fs::create_dir_all(wasm_project_folder.join("src"))
.expect("Wasm project dir create can not fail; qed");
let mut enabled_features = project_enabled_features(&project_cargo_toml, &crate_metadata);
if has_runtime_wasm_feature_declared(project_cargo_toml, crate_metadata) {
enabled_features.push("runtime-wasm".into());
}
let mut enabled_features = enabled_features.into_iter().collect::<HashSet<_>>();
enabled_features.extend(features_to_enable.into_iter());
create_project_cargo_toml(
&wasm_project_folder,
workspace_root_path,
&crate_name,
&crate_path,
&wasm_binary,
enabled_features.into_iter(),
);
write_file_if_changed(
wasm_project_folder.join("src/lib.rs"),
"#![no_std] pub use wasm_project::*;",
);
if let Some(crate_lock_file) = find_cargo_lock(project_cargo_toml) {
crate::copy_file_if_changed(crate_lock_file, wasm_project_folder.join("Cargo.lock"));
}
wasm_project_folder
}
fn is_release_build() -> bool {
if let Ok(var) = env::var(crate::WASM_BUILD_TYPE_ENV) {
match var.as_str() {
"release" => true,
"debug" => false,
var => panic!(
"Unexpected value for `{}` env variable: {}\nOne of the following are expected: `debug` or `release`.",
crate::WASM_BUILD_TYPE_ENV,
var,
),
}
} else {
true
}
}
fn build_project(project: &Path, default_rustflags: &str, cargo_cmd: CargoCommandVersioned) {
let manifest_path = project.join("Cargo.toml");
let mut build_cmd = cargo_cmd.command();
let rustflags = format!(
"-C link-arg=--export-table {} {}",
default_rustflags,
env::var(crate::WASM_BUILD_RUSTFLAGS_ENV).unwrap_or_default(),
);
build_cmd
.args(&["rustc", "--target=wasm32-unknown-unknown"])
.arg(format!("--manifest-path={}", manifest_path.display()))
.env("RUSTFLAGS", rustflags)
.env_remove("CARGO_TARGET_DIR")
.env(crate::SKIP_BUILD_ENV, "");
if super::color_output_enabled() {
build_cmd.arg("--color=always");
}
if is_release_build() {
build_cmd.arg("--release");
};
println!("{}", colorize_info_message("Information that should be included in a bug report."));
println!("{} {:?}", colorize_info_message("Executing build command:"), build_cmd);
println!("{} {}", colorize_info_message("Using rustc version:"), cargo_cmd.rustc_version());
match build_cmd.status().map(|s| s.success()) {
Ok(true) => {},
_ => process::exit(1),
}
}
fn compact_wasm_file(
project: &Path,
cargo_manifest: &Path,
wasm_binary_name: Option<String>,
) -> (Option<WasmBinary>, Option<WasmBinary>, WasmBinaryBloaty) {
let is_release_build = is_release_build();
let target = if is_release_build { "release" } else { "debug" };
let default_wasm_binary_name = get_wasm_binary_name(cargo_manifest);
let wasm_file = project
.join("target/wasm32-unknown-unknown")
.join(target)
.join(format!("{}.wasm", default_wasm_binary_name));
let wasm_compact_file = if is_release_build {
let wasm_compact_file = project.join(format!(
"{}.compact.wasm",
wasm_binary_name.clone().unwrap_or_else(|| default_wasm_binary_name.clone()),
));
wasm_gc::garbage_collect_file(&wasm_file, &wasm_compact_file)
.expect("Failed to compact generated WASM binary.");
Some(WasmBinary(wasm_compact_file))
} else {
None
};
let wasm_compact_compressed_file = wasm_compact_file.as_ref().and_then(|compact_binary| {
let file_name =
wasm_binary_name.clone().unwrap_or_else(|| default_wasm_binary_name.clone());
let wasm_compact_compressed_file =
project.join(format!("{}.compact.compressed.wasm", file_name));
if compress_wasm(&compact_binary.0, &wasm_compact_compressed_file) {
Some(WasmBinary(wasm_compact_compressed_file))
} else {
None
}
});
let bloaty_file_name = if let Some(name) = wasm_binary_name {
format!("{}.wasm", name)
} else {
format!("{}.wasm", default_wasm_binary_name)
};
let bloaty_file = project.join(bloaty_file_name);
fs::copy(wasm_file, &bloaty_file).expect("Copying the bloaty file to the project dir.");
(wasm_compact_file, wasm_compact_compressed_file, WasmBinaryBloaty(bloaty_file))
}
fn compress_wasm(wasm_binary_path: &Path, compressed_binary_out_path: &Path) -> bool {
use sp_maybe_compressed_blob::CODE_BLOB_BOMB_LIMIT;
let data = fs::read(wasm_binary_path).expect("Failed to read WASM binary");
if let Some(compressed) = sp_maybe_compressed_blob::compress(&data, CODE_BLOB_BOMB_LIMIT) {
fs::write(compressed_binary_out_path, &compressed[..])
.expect("Failed to write WASM binary");
true
} else {
println!(
"cargo:warning=Writing uncompressed wasm. Exceeded maximum size {}",
CODE_BLOB_BOMB_LIMIT,
);
false
}
}
#[derive(Debug)]
struct DeduplicatePackage<'a> {
package: &'a cargo_metadata::Package,
identifier: String,
}
impl<'a> From<&'a cargo_metadata::Package> for DeduplicatePackage<'a> {
fn from(package: &'a cargo_metadata::Package) -> Self {
Self {
package,
identifier: format!("{}{}{:?}", package.name, package.version, package.source),
}
}
}
impl<'a> Hash for DeduplicatePackage<'a> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.identifier.hash(state);
}
}
impl<'a> PartialEq for DeduplicatePackage<'a> {
fn eq(&self, other: &Self) -> bool {
self.identifier == other.identifier
}
}
impl<'a> Eq for DeduplicatePackage<'a> {}
impl<'a> Deref for DeduplicatePackage<'a> {
type Target = cargo_metadata::Package;
fn deref(&self) -> &Self::Target {
self.package
}
}
fn generate_rerun_if_changed_instructions(
cargo_manifest: &Path,
project_folder: &Path,
wasm_workspace: &Path,
) {
if let Some(cargo_lock) = find_cargo_lock(cargo_manifest) {
rerun_if_changed(cargo_lock);
}
let metadata = MetadataCommand::new()
.manifest_path(project_folder.join("Cargo.toml"))
.exec()
.expect("`cargo metadata` can not fail!");
let package = metadata
.packages
.iter()
.find(|p| p.manifest_path == cargo_manifest)
.expect("The crate package is contained in its own metadata; qed");
let mut dependencies = package.dependencies.iter().collect::<Vec<_>>();
let mut packages = HashSet::new();
packages.insert(DeduplicatePackage::from(package));
while let Some(dependency) = dependencies.pop() {
let path_or_git_dep =
dependency.source.as_ref().map(|s| s.starts_with("git+")).unwrap_or(true);
let package = metadata
.packages
.iter()
.filter(|p| !p.manifest_path.starts_with(wasm_workspace))
.find(|p| {
(path_or_git_dep || dependency.req.matches(&p.version)) && dependency.name == p.name
});
if let Some(package) = package {
if packages.insert(DeduplicatePackage::from(package)) {
dependencies.extend(package.dependencies.iter());
}
}
}
packages.iter().for_each(package_rerun_if_changed);
println!("cargo:rerun-if-env-changed={}", crate::SKIP_BUILD_ENV);
println!("cargo:rerun-if-env-changed={}", crate::WASM_BUILD_TYPE_ENV);
println!("cargo:rerun-if-env-changed={}", crate::WASM_BUILD_RUSTFLAGS_ENV);
println!("cargo:rerun-if-env-changed={}", crate::WASM_TARGET_DIRECTORY);
println!("cargo:rerun-if-env-changed={}", crate::WASM_BUILD_TOOLCHAIN);
}
fn package_rerun_if_changed(package: &DeduplicatePackage) {
let mut manifest_path = package.manifest_path.clone();
if manifest_path.ends_with("Cargo.toml") {
manifest_path.pop();
}
WalkDir::new(&manifest_path)
.into_iter()
.filter_entry(|p| {
p.path() == manifest_path || !p.path().is_dir() || !p.path().join("Cargo.toml").exists()
})
.filter_map(|p| p.ok().map(|p| p.into_path()))
.filter(|p| {
p.is_dir() || p.extension().map(|e| e == "rs" || e == "toml").unwrap_or_default()
})
.for_each(|p| rerun_if_changed(p));
}
fn copy_wasm_to_target_directory(cargo_manifest: &Path, wasm_binary: &WasmBinary) {
let target_dir = match env::var(crate::WASM_TARGET_DIRECTORY) {
Ok(path) => PathBuf::from(path),
Err(_) => return,
};
if !target_dir.is_absolute() {
panic!(
"Environment variable `{}` with `{}` is not an absolute path!",
crate::WASM_TARGET_DIRECTORY,
target_dir.display(),
);
}
fs::create_dir_all(&target_dir).expect("Creates `WASM_TARGET_DIRECTORY`.");
fs::copy(
wasm_binary.wasm_binary_path(),
target_dir.join(format!("{}.wasm", get_wasm_binary_name(cargo_manifest))),
)
.expect("Copies WASM binary to `WASM_TARGET_DIRECTORY`.");
}