static_vcruntime.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2019-2022 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. // taken from https://github.com/ChrisDenton/static_vcruntime/
  5. // we're not using static_vcruntime directly because we want this for debug builds too
  6. use std::{env, fs, io::Write, path::Path};
  7. pub fn build() {
  8. override_msvcrt_lib();
  9. // Disable conflicting libraries that aren't hard coded by Rust
  10. println!("cargo:rustc-link-arg=/NODEFAULTLIB:libvcruntimed.lib");
  11. println!("cargo:rustc-link-arg=/NODEFAULTLIB:vcruntime.lib");
  12. println!("cargo:rustc-link-arg=/NODEFAULTLIB:vcruntimed.lib");
  13. println!("cargo:rustc-link-arg=/NODEFAULTLIB:libcmtd.lib");
  14. println!("cargo:rustc-link-arg=/NODEFAULTLIB:msvcrt.lib");
  15. println!("cargo:rustc-link-arg=/NODEFAULTLIB:msvcrtd.lib");
  16. println!("cargo:rustc-link-arg=/NODEFAULTLIB:libucrt.lib");
  17. println!("cargo:rustc-link-arg=/NODEFAULTLIB:libucrtd.lib");
  18. // Set the libraries we want.
  19. println!("cargo:rustc-link-arg=/DEFAULTLIB:libcmt.lib");
  20. println!("cargo:rustc-link-arg=/DEFAULTLIB:libvcruntime.lib");
  21. println!("cargo:rustc-link-arg=/DEFAULTLIB:ucrt.lib");
  22. }
  23. /// Override the hard-coded msvcrt.lib by replacing it with a (mostly) empty object file.
  24. fn override_msvcrt_lib() {
  25. // Get the right machine type for the empty library.
  26. let arch = std::env::var("CARGO_CFG_TARGET_ARCH");
  27. let machine: &[u8] = if arch.as_deref() == Ok("x86_64") {
  28. &[0x64, 0x86]
  29. } else if arch.as_deref() == Ok("x86") {
  30. &[0x4C, 0x01]
  31. } else {
  32. return;
  33. };
  34. let bytes: &[u8] = &[
  35. 1, 0, 94, 3, 96, 98, 60, 0, 0, 0, 1, 0, 0, 0, 0, 0, 132, 1, 46, 100, 114, 101, 99, 116, 118,
  36. 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  37. 10, 16, 0, 46, 100, 114, 101, 99, 116, 118, 101, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 4, 0, 0, 0,
  38. ];
  39. // Write the empty "msvcrt.lib" to the output directory.
  40. let out_dir = env::var("OUT_DIR").unwrap();
  41. let path = Path::new(&out_dir).join("msvcrt.lib");
  42. let f = fs::OpenOptions::new()
  43. .write(true)
  44. .create_new(true)
  45. .open(path);
  46. if let Ok(mut f) = f {
  47. f.write_all(machine).unwrap();
  48. f.write_all(bytes).unwrap();
  49. }
  50. // Add the output directory to the native library path.
  51. println!("cargo:rustc-link-search=native={}", out_dir);
  52. }