about summary refs log tree commit diff
path: root/compiler/rustc_codegen_gcc/build_system/src/build.rs
diff options
context:
space:
mode:
authorGuillaume Gomez <guillaume.gomez@huawei.com>2024-07-10 12:44:23 +0200
committerGuillaume Gomez <guillaume.gomez@huawei.com>2024-07-10 12:44:23 +0200
commit7cbe50e2098c35fda06433cd36bbced941607317 (patch)
tree5f93154e463e7258902781d746195519e20a9fc6 /compiler/rustc_codegen_gcc/build_system/src/build.rs
parent649feb9c1a3c56650a4b6fa638b23103cbcd0dcd (diff)
parent98ed962c7d3eebe12c97588e61245273d265e72f (diff)
downloadrust-7cbe50e2098c35fda06433cd36bbced941607317.tar.gz
rust-7cbe50e2098c35fda06433cd36bbced941607317.zip
Merge commit '98ed962c7d3eebe12c97588e61245273d265e72f' into master
Diffstat (limited to 'compiler/rustc_codegen_gcc/build_system/src/build.rs')
-rw-r--r--compiler/rustc_codegen_gcc/build_system/src/build.rs120
1 files changed, 62 insertions, 58 deletions
diff --git a/compiler/rustc_codegen_gcc/build_system/src/build.rs b/compiler/rustc_codegen_gcc/build_system/src/build.rs
index c81b02e2183..d465ab7e506 100644
--- a/compiler/rustc_codegen_gcc/build_system/src/build.rs
+++ b/compiler/rustc_codegen_gcc/build_system/src/build.rs
@@ -1,5 +1,7 @@
 use crate::config::{Channel, ConfigInfo};
-use crate::utils::{run_command, run_command_with_output_and_env, walk_dir};
+use crate::utils::{
+    copy_file, create_dir, get_sysroot_dir, run_command, run_command_with_output_and_env, walk_dir,
+};
 use std::collections::HashMap;
 use std::ffi::OsStr;
 use std::fs;
@@ -9,12 +11,14 @@ use std::path::Path;
 struct BuildArg {
     flags: Vec<String>,
     config_info: ConfigInfo,
+    build_sysroot: bool,
 }
 
 impl BuildArg {
+    /// Creates a new `BuildArg` instance by parsing command-line arguments.
     fn new() -> Result<Option<Self>, String> {
         let mut build_arg = Self::default();
-        // We skip binary name and the `build` command.
+        // Skip binary name and the `build` command.
         let mut args = std::env::args().skip(2);
 
         while let Some(arg) = args.next() {
@@ -29,6 +33,9 @@ impl BuildArg {
                         );
                     }
                 }
+                "--sysroot" => {
+                    build_arg.build_sysroot = true;
+                }
                 "--help" => {
                     Self::usage();
                     return Ok(None);
@@ -48,20 +55,20 @@ impl BuildArg {
             r#"
 `build` command help:
 
-    --features [arg]       : Add a new feature [arg]"#
+    --features [arg]       : Add a new feature [arg]
+    --sysroot              : Build with sysroot"#
         );
         ConfigInfo::show_usage();
         println!("    --help                 : Show this help");
     }
 }
 
-pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Result<(), String> {
-    let start_dir = Path::new("build_sysroot");
+fn cleanup_sysroot_previous_build(start_dir: &Path) {
     // Cleanup for previous run
     // Clean target dir except for build scripts and incremental cache
     let _ = walk_dir(
         start_dir.join("target"),
-        |dir: &Path| {
+        &mut |dir: &Path| {
             for top in &["debug", "release"] {
                 let _ = fs::remove_dir_all(dir.join(top).join("build"));
                 let _ = fs::remove_dir_all(dir.join(top).join("deps"));
@@ -70,7 +77,7 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu
 
                 let _ = walk_dir(
                     dir.join(top),
-                    |sub_dir: &Path| {
+                    &mut |sub_dir: &Path| {
                         if sub_dir
                             .file_name()
                             .map(|filename| filename.to_str().unwrap().starts_with("libsysroot"))
@@ -80,7 +87,7 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu
                         }
                         Ok(())
                     },
-                    |file: &Path| {
+                    &mut |file: &Path| {
                         if file
                             .file_name()
                             .map(|filename| filename.to_str().unwrap().starts_with("libsysroot"))
@@ -90,16 +97,39 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu
                         }
                         Ok(())
                     },
+                    false,
                 );
             }
             Ok(())
         },
-        |_| Ok(()),
+        &mut |_| Ok(()),
+        false,
     );
 
     let _ = fs::remove_file(start_dir.join("Cargo.lock"));
     let _ = fs::remove_file(start_dir.join("test_target/Cargo.lock"));
     let _ = fs::remove_dir_all(start_dir.join("sysroot"));
+}
+
+pub fn create_build_sysroot_content(start_dir: &Path) -> Result<(), String> {
+    if !start_dir.is_dir() {
+        create_dir(start_dir)?;
+    }
+    copy_file("build_system/build_sysroot/Cargo.toml", &start_dir.join("Cargo.toml"))?;
+    copy_file("build_system/build_sysroot/Cargo.lock", &start_dir.join("Cargo.lock"))?;
+
+    let src_dir = start_dir.join("src");
+    if !src_dir.is_dir() {
+        create_dir(&src_dir)?;
+    }
+    copy_file("build_system/build_sysroot/lib.rs", &start_dir.join("src/lib.rs"))
+}
+
+pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Result<(), String> {
+    let start_dir = get_sysroot_dir();
+
+    cleanup_sysroot_previous_build(&start_dir);
+    create_build_sysroot_content(&start_dir)?;
 
     // Builds libs
     let mut rustflags = env.get("RUSTFLAGS").cloned().unwrap_or_default();
@@ -110,7 +140,6 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu
     if config.no_default_features {
         rustflags.push_str(" -Csymbol-mangling-version=v0");
     }
-    let mut env = env.clone();
 
     let mut args: Vec<&dyn AsRef<OsStr>> = vec![&"cargo", &"build", &"--target", &config.target];
 
@@ -127,46 +156,33 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu
         "debug"
     };
 
+    if let Ok(cg_rustflags) = std::env::var("CG_RUSTFLAGS") {
+        rustflags.push(' ');
+        rustflags.push_str(&cg_rustflags);
+    }
+
+    let mut env = env.clone();
     env.insert("RUSTFLAGS".to_string(), rustflags);
-    run_command_with_output_and_env(&args, Some(start_dir), Some(&env))?;
+    run_command_with_output_and_env(&args, Some(&start_dir), Some(&env))?;
 
     // Copy files to sysroot
     let sysroot_path = start_dir.join(format!("sysroot/lib/rustlib/{}/lib/", config.target_triple));
-    fs::create_dir_all(&sysroot_path).map_err(|error| {
-        format!(
-            "Failed to create directory `{}`: {:?}",
-            sysroot_path.display(),
-            error
-        )
-    })?;
-    let copier = |dir_to_copy: &Path| {
+    create_dir(&sysroot_path)?;
+    let mut copier = |dir_to_copy: &Path| {
         // FIXME: should not use shell command!
         run_command(&[&"cp", &"-r", &dir_to_copy, &sysroot_path], None).map(|_| ())
     };
     walk_dir(
         start_dir.join(&format!("target/{}/{}/deps", config.target_triple, channel)),
-        copier,
-        copier,
+        &mut copier.clone(),
+        &mut copier,
+        false,
     )?;
 
     // Copy the source files to the sysroot (Rust for Linux needs this).
     let sysroot_src_path = start_dir.join("sysroot/lib/rustlib/src/rust");
-    fs::create_dir_all(&sysroot_src_path).map_err(|error| {
-        format!(
-            "Failed to create directory `{}`: {:?}",
-            sysroot_src_path.display(),
-            error
-        )
-    })?;
-    run_command(
-        &[
-            &"cp",
-            &"-r",
-            &start_dir.join("sysroot_src/library/"),
-            &sysroot_src_path,
-        ],
-        None,
-    )?;
+    create_dir(&sysroot_src_path)?;
+    run_command(&[&"cp", &"-r", &start_dir.join("sysroot_src/library/"), &sysroot_src_path], None)?;
 
     Ok(())
 }
@@ -174,20 +190,11 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu
 fn build_codegen(args: &mut BuildArg) -> Result<(), String> {
     let mut env = HashMap::new();
 
-    env.insert(
-        "LD_LIBRARY_PATH".to_string(),
-        args.config_info.gcc_path.clone(),
-    );
-    env.insert(
-        "LIBRARY_PATH".to_string(),
-        args.config_info.gcc_path.clone(),
-    );
+    env.insert("LD_LIBRARY_PATH".to_string(), args.config_info.gcc_path.clone());
+    env.insert("LIBRARY_PATH".to_string(), args.config_info.gcc_path.clone());
 
     if args.config_info.no_default_features {
-        env.insert(
-            "RUSTFLAGS".to_string(),
-            "-Csymbol-mangling-version=v0".to_string(),
-        );
+        env.insert("RUSTFLAGS".to_string(), "-Csymbol-mangling-version=v0".to_string());
     }
 
     let mut command: Vec<&dyn AsRef<OsStr>> = vec![&"cargo", &"rustc"];
@@ -212,18 +219,15 @@ fn build_codegen(args: &mut BuildArg) -> Result<(), String> {
     // We voluntarily ignore the error.
     let _ = fs::remove_dir_all("target/out");
     let gccjit_target = "target/out/gccjit";
-    fs::create_dir_all(gccjit_target).map_err(|error| {
-        format!(
-            "Failed to create directory `{}`: {:?}",
-            gccjit_target, error
-        )
-    })?;
-
-    println!("[BUILD] sysroot");
-    build_sysroot(&env, &args.config_info)?;
+    create_dir(gccjit_target)?;
+    if args.build_sysroot {
+        println!("[BUILD] sysroot");
+        build_sysroot(&env, &args.config_info)?;
+    }
     Ok(())
 }
 
+/// Executes the build process.
 pub fn run() -> Result<(), String> {
     let mut args = match BuildArg::new()? {
         Some(args) => args,