build.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. use std::path::PathBuf;
  2. use std::{env, fs};
  3. fn read_dependent_script(script: &str) -> Result<String, Box<dyn std::error::Error>> {
  4. let content = fs::read_to_string(script)?;
  5. println!("cargo:rerun-if-changed={}", script);
  6. Ok(content)
  7. }
  8. fn process_ldscript_riscv64(script: &mut String) -> Result<(), Box<dyn std::error::Error>> {
  9. println!("cargo:extra-link-args= --no-check-sections");
  10. let memory = read_dependent_script("src/arch/riscv64/memory.x")?;
  11. let link = read_dependent_script("src/arch/riscv64/link.x")?;
  12. *script = memory + script;
  13. script.push_str(&link);
  14. Ok(())
  15. }
  16. fn process_ldscript_x86(script: &mut String) -> Result<(), Box<dyn std::error::Error>> {
  17. // Otherwise `bootstrap.rs` might be ignored and not linked in.
  18. println!("cargo:extra-link-args=--undefined=move_mbr --no-check-sections");
  19. let memory = read_dependent_script("src/arch/x86_64/memory.x")?;
  20. let link = read_dependent_script("src/arch/x86_64/link.x")?;
  21. *script = memory + script;
  22. script.push_str(&link);
  23. Ok(())
  24. }
  25. fn process_ldscript_arch(
  26. script: &mut String,
  27. arch: &str,
  28. ) -> Result<(), Box<dyn std::error::Error>> {
  29. match arch {
  30. "x86_64" => {
  31. process_ldscript_x86(script)?;
  32. }
  33. "riscv64" => {
  34. process_ldscript_riscv64(script)?;
  35. }
  36. _ => panic!("Unsupported architecture: {}", arch),
  37. }
  38. Ok(())
  39. }
  40. fn main() -> Result<(), Box<dyn std::error::Error>> {
  41. let out_dir = PathBuf::from(env::var("OUT_DIR")?);
  42. let out_script = out_dir.join("link.x");
  43. let in_script = "src/link.x.in";
  44. let mut script = read_dependent_script(in_script)?;
  45. process_ldscript_arch(&mut script, &env::var("CARGO_CFG_TARGET_ARCH")?)?;
  46. fs::write(out_script, script)?;
  47. println!("cargo:rustc-link-search={}", out_dir.display());
  48. Ok(())
  49. }