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 DEFAULT: bool = true;
184            const IS_HOST: bool = $IS_HOST;
185            $(const $c: bool = true;)*
186
187            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
188                let $_config = &run.builder.config;
189                run.$condition_name($path_or_alias).default_condition($default_cond)
190            }
191
192            fn make_run(run: RunConfig<'_>) {
193                run.builder.ensure($name {
194                    build_compiler: run.builder.compiler(run.builder.top_stage - 1, run.builder.config.host_target),
195                    target: run.target,
196                });
197            }
198
199            fn run($sel, $builder: &Builder<'_>) {
200                $run_item
201            }
202        })+
203    }
204}
205
206install!((self, builder, _config),
207    Docs, path = "src/doc", _config.docs, IS_HOST: false, {
208        let tarball = builder.ensure(dist::Docs { host: self.target }).expect("missing docs");
209        install_sh(builder, "docs", self.build_compiler, Some(self.target), &tarball);
210    };
211    Std, path = "library/std", true, IS_HOST: false, {
212        // `expect` should be safe, only None when host != build, but this
213        // only runs when host == build
214        let std = dist::Std::new(builder, self.target);
215        let build_compiler = std.build_compiler;
216        let tarball = builder.ensure(std).expect("missing std");
217        install_sh(builder, "std", build_compiler, Some(self.target), &tarball);
218    };
219    Cargo, alias = "cargo", Self::should_build(_config), IS_HOST: true, {
220        let tarball = builder
221            .ensure(dist::Cargo { build_compiler: self.build_compiler, target: self.target })
222            .expect("missing cargo");
223        install_sh(builder, "cargo", self.build_compiler, Some(self.target), &tarball);
224    };
225    RustAnalyzer, alias = "rust-analyzer", Self::should_build(_config), IS_HOST: true, {
226        if let Some(tarball) =
227            builder.ensure(dist::RustAnalyzer { compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target), target: self.target })
228        {
229            install_sh(builder, "rust-analyzer", self.build_compiler, Some(self.target), &tarball);
230        } else {
231            builder.info(
232                &format!("skipping Install rust-analyzer stage{} ({})", self.build_compiler.stage + 1, self.target),
233            );
234        }
235    };
236    Clippy, alias = "clippy", Self::should_build(_config), IS_HOST: true, {
237        let tarball = builder
238            .ensure(dist::Clippy { compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target), target: self.target })
239            .expect("missing clippy");
240        install_sh(builder, "clippy", self.build_compiler, Some(self.target), &tarball);
241    };
242    Miri, alias = "miri", Self::should_build(_config), IS_HOST: true, {
243        if let Some(tarball) = builder.ensure(dist::Miri { compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target) , target: self.target }) {
244            install_sh(builder, "miri", self.build_compiler, Some(self.target), &tarball);
245        } else {
246            // Miri is only available on nightly
247            builder.info(
248                &format!("skipping Install miri stage{} ({})", self.build_compiler.stage + 1, self.target),
249            );
250        }
251    };
252    LlvmTools, alias = "llvm-tools", _config.llvm_tools_enabled && _config.llvm_enabled(_config.host_target), IS_HOST: true, {
253        if let Some(tarball) = builder.ensure(dist::LlvmTools { target: self.target }) {
254            install_sh(builder, "llvm-tools", None, Some(self.target), &tarball);
255        } else {
256            builder.info(
257                &format!("skipping llvm-tools ({}): external LLVM", self.target),
258            );
259        }
260    };
261    Rustfmt, alias = "rustfmt", Self::should_build(_config), IS_HOST: true, {
262        if let Some(tarball) = builder.ensure(dist::Rustfmt {
263            compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target),
264            target: self.target
265        }) {
266            install_sh(builder, "rustfmt", self.build_compiler, Some(self.target), &tarball);
267        } else {
268            builder.info(
269                &format!("skipping Install Rustfmt stage{} ({})", self.build_compiler.stage + 1, self.target),
270            );
271        }
272    };
273    Rustc, path = "compiler/rustc", true, IS_HOST: true, {
274        let tarball = builder.ensure(dist::Rustc {
275            target_compiler: builder.compiler(self.build_compiler.stage + 1, self.target),
276        });
277        install_sh(builder, "rustc", self.build_compiler, Some(self.target), &tarball);
278    };
279    RustcCodegenCranelift, alias = "rustc-codegen-cranelift", Self::should_build(_config), IS_HOST: true, {
280        if let Some(tarball) = builder.ensure(dist::CraneliftCodegenBackend {
281            compilers: RustcPrivateCompilers::from_build_compiler(builder, self.build_compiler, self.target),
282            target: self.target
283        }) {
284            install_sh(builder, "rustc-codegen-cranelift", self.build_compiler, Some(self.target), &tarball);
285        } else {
286            builder.info(
287                &format!("skipping Install CodegenBackend(\"cranelift\") stage{} ({})",
288                         self.build_compiler.stage + 1, self.target),
289            );
290        }
291    };
292    LlvmBitcodeLinker, alias = "llvm-bitcode-linker", Self::should_build(_config), IS_HOST: true, {
293        if let Some(tarball) = builder.ensure(dist::LlvmBitcodeLinker { build_compiler: self.build_compiler, target: self.target }) {
294            install_sh(builder, "llvm-bitcode-linker", self.build_compiler, Some(self.target), &tarball);
295        } else {
296            builder.info(
297                &format!("skipping llvm-bitcode-linker stage{} ({})", self.build_compiler.stage + 1, self.target),
298            );
299        }
300    };
301);
302
303#[derive(Debug, Clone, Hash, PartialEq, Eq)]
304pub struct Src {
305    stage: u32,
306}
307
308impl Step for Src {
309    type Output = ();
310    const DEFAULT: bool = true;
311    const IS_HOST: bool = true;
312
313    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
314        let config = &run.builder.config;
315        let cond = config.extended && config.tools.as_ref().is_none_or(|t| t.contains("src"));
316        run.path("src").default_condition(cond)
317    }
318
319    fn make_run(run: RunConfig<'_>) {
320        run.builder.ensure(Src { stage: run.builder.top_stage });
321    }
322
323    fn run(self, builder: &Builder<'_>) {
324        let tarball = builder.ensure(dist::Src);
325        install_sh(builder, "src", None, None, &tarball);
326    }
327}