bootstrap/core/build_steps/
install.rs

1//! Implementation of the install aspects of the compiler.
2//!
3//! This module is responsible for installing the standard library,
4//! compiler, and documentation.
5
6use std::path::{Component, Path, PathBuf};
7use std::{env, fs};
8
9use crate::core::build_steps::dist;
10use crate::core::build_steps::tool::RustcPrivateCompilers;
11use crate::core::builder::{Builder, RunConfig, ShouldRun, Step};
12use crate::core::config::{Config, TargetSelection};
13use crate::utils::exec::command;
14use crate::utils::helpers::t;
15use crate::utils::tarball::GeneratedTarball;
16use crate::{Compiler, Kind};
17
18#[cfg(target_os = "illumos")]
19const SHELL: &str = "bash";
20#[cfg(not(target_os = "illumos"))]
21const SHELL: &str = "sh";
22
23/// We have to run a few shell scripts, which choke quite a bit on both `\`
24/// characters and on `C:\` paths, so normalize both of them away.
25fn sanitize_sh(path: &Path, is_cygwin: bool) -> String {
26    let path = path.to_str().unwrap().replace('\\', "/");
27    return if is_cygwin { path } else { change_drive(unc_to_lfs(&path)).unwrap_or(path) };
28
29    fn unc_to_lfs(s: &str) -> &str {
30        s.strip_prefix("//?/").unwrap_or(s)
31    }
32
33    fn change_drive(s: &str) -> Option<String> {
34        let mut ch = s.chars();
35        let drive = ch.next().unwrap_or('C');
36        if ch.next() != Some(':') {
37            return None;
38        }
39        if ch.next() != Some('/') {
40            return None;
41        }
42        // The prefix for Windows drives in Cygwin/MSYS2 is configurable, but
43        // /proc/cygdrive is available regardless of configuration since 1.7.33
44        Some(format!("/proc/cygdrive/{}/{}", drive, &s[drive.len_utf8() + 2..]))
45    }
46}
47
48fn is_dir_writable_for_user(dir: &Path) -> bool {
49    let tmp = dir.join(".tmp");
50    match fs::create_dir_all(&tmp) {
51        Ok(_) => {
52            fs::remove_dir_all(tmp).unwrap();
53            true
54        }
55        Err(e) => {
56            if e.kind() == std::io::ErrorKind::PermissionDenied {
57                false
58            } else {
59                panic!("Failed the write access check for the current user. {e}");
60            }
61        }
62    }
63}
64
65fn install_sh(
66    builder: &Builder<'_>,
67    package: &str,
68    build_compiler: impl Into<Option<Compiler>>,
69    target: Option<TargetSelection>,
70    tarball: &GeneratedTarball,
71) {
72    let _guard = match build_compiler.into() {
73        Some(build_compiler) => builder.msg(Kind::Install, package, None, build_compiler, target),
74        None => builder.msg_unstaged(Kind::Install, package, target.unwrap_or(builder.host_target)),
75    };
76
77    let prefix = default_path(&builder.config.prefix, "/usr/local");
78    let sysconfdir = prefix.join(default_path(&builder.config.sysconfdir, "/etc"));
79    let destdir_env = env::var_os("DESTDIR").map(PathBuf::from);
80    let is_cygwin = builder.config.host_target.is_cygwin();
81
82    // Sanity checks on the write access of user.
83    //
84    // When the `DESTDIR` environment variable is present, there is no point to
85    // check write access for `prefix` and `sysconfdir` individually, as they
86    // are combined with the path from the `DESTDIR` environment variable. In
87    // this case, we only need to check the `DESTDIR` path, disregarding the
88    // `prefix` and `sysconfdir` paths.
89    if let Some(destdir) = &destdir_env {
90        assert!(is_dir_writable_for_user(destdir), "User doesn't have write access on DESTDIR.");
91    } else {
92        assert!(
93            is_dir_writable_for_user(&prefix),
94            "User doesn't have write access on `install.prefix` path in the `bootstrap.toml`.",
95        );
96        assert!(
97            is_dir_writable_for_user(&sysconfdir),
98            "User doesn't have write access on `install.sysconfdir` path in `bootstrap.toml`."
99        );
100    }
101
102    let datadir = prefix.join(default_path(&builder.config.datadir, "share"));
103    let docdir = prefix.join(default_path(&builder.config.docdir, &format!("share/doc/{package}")));
104    let mandir = prefix.join(default_path(&builder.config.mandir, "share/man"));
105    let libdir = prefix.join(default_path(&builder.config.libdir, "lib"));
106    let bindir = prefix.join(&builder.config.bindir); // Default in config.rs
107
108    let empty_dir = builder.out.join("tmp/empty_dir");
109    t!(fs::create_dir_all(&empty_dir));
110
111    let mut cmd = command(SHELL);
112    cmd.current_dir(&empty_dir)
113        .arg(sanitize_sh(&tarball.decompressed_output().join("install.sh"), is_cygwin))
114        .arg(format!("--prefix={}", prepare_dir(&destdir_env, prefix, is_cygwin)))
115        .arg(format!("--sysconfdir={}", prepare_dir(&destdir_env, sysconfdir, is_cygwin)))
116        .arg(format!("--datadir={}", prepare_dir(&destdir_env, datadir, is_cygwin)))
117        .arg(format!("--docdir={}", prepare_dir(&destdir_env, docdir, is_cygwin)))
118        .arg(format!("--bindir={}", prepare_dir(&destdir_env, bindir, is_cygwin)))
119        .arg(format!("--libdir={}", prepare_dir(&destdir_env, libdir, is_cygwin)))
120        .arg(format!("--mandir={}", prepare_dir(&destdir_env, mandir, is_cygwin)))
121        .arg("--disable-ldconfig");
122    cmd.run(builder);
123    t!(fs::remove_dir_all(&empty_dir));
124}
125
126fn default_path(config: &Option<PathBuf>, default: &str) -> PathBuf {
127    config.as_ref().cloned().unwrap_or_else(|| PathBuf::from(default))
128}
129
130fn prepare_dir(destdir_env: &Option<PathBuf>, mut path: PathBuf, is_cygwin: bool) -> String {
131    // The DESTDIR environment variable is a standard way to install software in a subdirectory
132    // while keeping the original directory structure, even if the prefix or other directories
133    // contain absolute paths.
134    //
135    // More information on the environment variable is available here:
136    // https://www.gnu.org/prep/standards/html_node/DESTDIR.html
137    if let Some(destdir) = destdir_env {
138        let without_destdir = path.clone();
139        path.clone_from(destdir);
140        // Custom .join() which ignores disk roots.
141        for part in without_destdir.components() {
142            if let Component::Normal(s) = part {
143                path.push(s)
144            }
145        }
146    }
147
148    // The installation command is not executed from the current directory, but from a temporary
149    // directory. To prevent relative paths from breaking this converts relative paths to absolute
150    // paths. std::fs::canonicalize is not used as that requires the path to actually be present.
151    if path.is_relative() {
152        path = std::env::current_dir().expect("failed to get the current directory").join(path);
153        assert!(path.is_absolute(), "could not make the path relative");
154    }
155
156    sanitize_sh(&path, is_cygwin)
157}
158
159macro_rules! install {
160    (($sel:ident, $builder:ident, $_config:ident),
161       $($name:ident,
162       $condition_name: ident = $path_or_alias: literal,
163       $default_cond:expr,
164       IS_HOST: $IS_HOST:expr,
165       $run_item:block $(, $c:ident)*;)+) => {
166        $(
167        #[derive(Debug, Clone, Hash, PartialEq, Eq)]
168        pub struct $name {
169            build_compiler: Compiler,
170            target: TargetSelection,
171        }
172
173        impl $name {
174            #[allow(dead_code)]
175            fn should_build(config: &Config) -> bool {
176                config.extended && config.tools.as_ref()
177                    .map_or(true, |t| t.contains($path_or_alias))
178            }
179        }
180
181        impl Step for $name {
182            type Output = ();
183            const IS_HOST: bool = $IS_HOST;
184            $(const $c: bool = true;)*
185
186            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
187                run.$condition_name($path_or_alias)
188            }
189
190            fn is_default_step(builder: &Builder<'_>) -> bool {
191                let $_config = &builder.config;
192                $default_cond
193            }
194
195            fn make_run(run: RunConfig<'_>) {
196                run.builder.ensure($name {
197                    build_compiler: run.builder.compiler(run.builder.top_stage - 1, run.builder.config.host_target),
198                    target: run.target,
199                });
200            }
201
202            fn run($sel, $builder: &Builder<'_>) {
203                $run_item
204            }
205        })+
206    }
207}
208
209install!((self, builder, _config),
210    Docs, path = "src/doc", _config.docs, IS_HOST: false, {
211        let tarball = builder.ensure(dist::Docs { host: self.target }).expect("missing docs");
212        install_sh(builder, "docs", self.build_compiler, Some(self.target), &tarball);
213    };
214    Std, path = "library/std", true, IS_HOST: false, {
215        // `expect` should be safe, only None when host != build, but this
216        // only runs when host == build
217        let std = dist::Std::new(builder, self.target);
218        let build_compiler = std.build_compiler;
219        let tarball = builder.ensure(std).expect("missing std");
220        install_sh(builder, "std", build_compiler, Some(self.target), &tarball);
221    };
222    Cargo, alias = "cargo", Self::should_build(_config), IS_HOST: true, {
223        let tarball = builder
224            .ensure(dist::Cargo { build_compiler: self.build_compiler, target: self.target })
225            .expect("missing cargo");
226        install_sh(builder, "cargo", self.build_compiler, Some(self.target), &tarball);
227    };
228    RustAnalyzer, alias = "rust-analyzer", Self::should_build(_config), IS_HOST: true, {
229        if let Some(tarball) =
230            builder.ensure(dist::RustAnalyzer { compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target), target: self.target })
231        {
232            install_sh(builder, "rust-analyzer", self.build_compiler, Some(self.target), &tarball);
233        } else {
234            builder.info(
235                &format!("skipping Install rust-analyzer stage{} ({})", self.build_compiler.stage + 1, self.target),
236            );
237        }
238    };
239    Clippy, alias = "clippy", Self::should_build(_config), IS_HOST: true, {
240        let tarball = builder
241            .ensure(dist::Clippy { compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target), target: self.target })
242            .expect("missing clippy");
243        install_sh(builder, "clippy", self.build_compiler, Some(self.target), &tarball);
244    };
245    Miri, alias = "miri", Self::should_build(_config), IS_HOST: true, {
246        if let Some(tarball) = builder.ensure(dist::Miri { compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target) , target: self.target }) {
247            install_sh(builder, "miri", self.build_compiler, Some(self.target), &tarball);
248        } else {
249            // Miri is only available on nightly
250            builder.info(
251                &format!("skipping Install miri stage{} ({})", self.build_compiler.stage + 1, self.target),
252            );
253        }
254    };
255    LlvmTools, alias = "llvm-tools", _config.llvm_tools_enabled && _config.llvm_enabled(_config.host_target), IS_HOST: true, {
256        if let Some(tarball) = builder.ensure(dist::LlvmTools { target: self.target }) {
257            install_sh(builder, "llvm-tools", None, Some(self.target), &tarball);
258        } else {
259            builder.info(
260                &format!("skipping llvm-tools ({}): external LLVM", self.target),
261            );
262        }
263    };
264    Rustfmt, alias = "rustfmt", Self::should_build(_config), IS_HOST: true, {
265        if let Some(tarball) = builder.ensure(dist::Rustfmt {
266            compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target),
267            target: self.target
268        }) {
269            install_sh(builder, "rustfmt", self.build_compiler, Some(self.target), &tarball);
270        } else {
271            builder.info(
272                &format!("skipping Install Rustfmt stage{} ({})", self.build_compiler.stage + 1, self.target),
273            );
274        }
275    };
276    Rustc, path = "compiler/rustc", true, IS_HOST: true, {
277        let tarball = builder.ensure(dist::Rustc {
278            target_compiler: builder.compiler(self.build_compiler.stage + 1, self.target),
279        });
280        install_sh(builder, "rustc", self.build_compiler, Some(self.target), &tarball);
281    };
282    RustcDev, alias = "rustc-dev", Self::should_build(_config), IS_HOST: true, {
283        if let Some(tarball) = builder.ensure(dist::RustcDev {
284            build_compiler: self.build_compiler, target: self.target
285        }) {
286            install_sh(builder, "rustc-dev", self.build_compiler, Some(self.target), &tarball);
287        } else {
288            builder.info(
289                &format!("skipping Install RustcDev stage{} ({})", self.build_compiler.stage + 1, self.target),
290            );
291        }
292    };
293    RustcCodegenCranelift, alias = "rustc-codegen-cranelift", Self::should_build(_config), IS_HOST: true, {
294        if let Some(tarball) = builder.ensure(dist::CraneliftCodegenBackend {
295            compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target),
296            target: self.target
297        }) {
298            install_sh(builder, "rustc-codegen-cranelift", self.build_compiler, Some(self.target), &tarball);
299        } else {
300            builder.info(
301                &format!("skipping Install CodegenBackend(\"cranelift\") stage{} ({})",
302                         self.build_compiler.stage + 1, self.target),
303            );
304        }
305    };
306    LlvmBitcodeLinker, alias = "llvm-bitcode-linker", Self::should_build(_config), IS_HOST: true, {
307        if let Some(tarball) = builder.ensure(dist::LlvmBitcodeLinker { build_compiler: self.build_compiler, target: self.target }) {
308            install_sh(builder, "llvm-bitcode-linker", self.build_compiler, Some(self.target), &tarball);
309        } else {
310            builder.info(
311                &format!("skipping llvm-bitcode-linker stage{} ({})", self.build_compiler.stage + 1, self.target),
312            );
313        }
314    };
315);
316
317#[derive(Debug, Clone, Hash, PartialEq, Eq)]
318pub struct Src {
319    stage: u32,
320}
321
322impl Step for Src {
323    type Output = ();
324    const IS_HOST: bool = true;
325
326    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
327        run.path("src")
328    }
329
330    fn is_default_step(builder: &Builder<'_>) -> bool {
331        let config = &builder.config;
332        config.extended && config.tools.as_ref().is_none_or(|t| t.contains("src"))
333    }
334
335    fn make_run(run: RunConfig<'_>) {
336        run.builder.ensure(Src { stage: run.builder.top_stage });
337    }
338
339    fn run(self, builder: &Builder<'_>) {
340        let tarball = builder.ensure(dist::Src);
341        install_sh(builder, "src", None, None, &tarball);
342    }
343}