bootstrap/core/build_steps/
gcc.rs1use std::fs;
12use std::path::{Path, PathBuf};
13use std::sync::OnceLock;
14
15use crate::FileType;
16use crate::core::builder::{Builder, Cargo, Kind, RunConfig, ShouldRun, Step};
17use crate::core::config::TargetSelection;
18use crate::utils::build_stamp::{BuildStamp, generate_smart_stamp_hash};
19use crate::utils::exec::command;
20use crate::utils::helpers::{self, t};
21
22#[derive(Debug, Clone, Hash, PartialEq, Eq)]
23pub struct Gcc {
24 pub target: TargetSelection,
25}
26
27#[derive(Clone)]
28pub struct GccOutput {
29 pub libgccjit: PathBuf,
30}
31
32impl GccOutput {
33 pub fn install_to(&self, builder: &Builder<'_>, directory: &Path) {
35 let mut target_filename = self.libgccjit.file_name().unwrap().to_str().unwrap().to_string();
40 target_filename.push_str(".0");
41
42 let dst = directory.join(target_filename);
43 builder.copy_link(&self.libgccjit, &dst, FileType::NativeLibrary);
44 }
45}
46
47impl Step for Gcc {
48 type Output = GccOutput;
49
50 const IS_HOST: bool = true;
51
52 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
53 run.path("src/gcc").alias("gcc")
54 }
55
56 fn make_run(run: RunConfig<'_>) {
57 run.builder.ensure(Gcc { target: run.target });
58 }
59
60 fn run(self, builder: &Builder<'_>) -> Self::Output {
62 let target = self.target;
63
64 let metadata = match get_gcc_build_status(builder, target) {
66 GccBuildStatus::AlreadyBuilt(path) => return GccOutput { libgccjit: path },
67 GccBuildStatus::ShouldBuild(m) => m,
68 };
69
70 let _guard = builder.msg_unstaged(Kind::Build, "GCC", target);
71 t!(metadata.stamp.remove());
72 let _time = helpers::timeit(builder);
73
74 let libgccjit_path = libgccjit_built_path(&metadata.install_dir);
75 if builder.config.dry_run() {
76 return GccOutput { libgccjit: libgccjit_path };
77 }
78
79 build_gcc(&metadata, builder, target);
80
81 t!(metadata.stamp.write());
82
83 GccOutput { libgccjit: libgccjit_path }
84 }
85}
86
87pub struct Meta {
88 stamp: BuildStamp,
89 out_dir: PathBuf,
90 install_dir: PathBuf,
91 root: PathBuf,
92}
93
94pub enum GccBuildStatus {
95 AlreadyBuilt(PathBuf),
97 ShouldBuild(Meta),
98}
99
100#[cfg(not(test))]
104fn try_download_gcc(builder: &Builder<'_>, target: TargetSelection) -> Option<PathBuf> {
105 use build_helper::git::PathFreshness;
106
107 if !matches!(builder.config.gcc_ci_mode, crate::core::config::GccCiMode::DownloadFromCi) {
109 return None;
110 }
111 if target != "x86_64-unknown-linux-gnu" {
112 eprintln!("GCC CI download is only available for the `x86_64-unknown-linux-gnu` target");
113 return None;
114 }
115 let source = detect_gcc_freshness(
116 &builder.config,
117 builder.config.rust_info.is_managed_git_subrepository(),
118 );
119 builder.verbose(|| {
120 eprintln!("GCC freshness: {source:?}");
121 });
122 match source {
123 PathFreshness::LastModifiedUpstream { upstream } => {
124 let root = ci_gcc_root(&builder.config, target);
126 let gcc_stamp = BuildStamp::new(&root).with_prefix("gcc").add_stamp(&upstream);
127 if !gcc_stamp.is_up_to_date() && !builder.config.dry_run() {
128 builder.config.download_ci_gcc(&upstream, &root);
129 t!(gcc_stamp.write());
130 }
131
132 let libgccjit = root.join("lib").join("libgccjit.so");
133 Some(libgccjit)
134 }
135 PathFreshness::HasLocalModifications { .. } => {
136 eprintln!("Found local GCC modifications, GCC will *not* be downloaded");
138 None
139 }
140 PathFreshness::MissingUpstream => {
141 eprintln!("error: could not find commit hash for downloading GCC");
142 eprintln!("HELP: maybe your repository history is too shallow?");
143 eprintln!("HELP: consider disabling `download-ci-gcc`");
144 eprintln!("HELP: or fetch enough history to include one upstream commit");
145 None
146 }
147 }
148}
149
150#[cfg(test)]
151fn try_download_gcc(_builder: &Builder<'_>, _target: TargetSelection) -> Option<PathBuf> {
152 None
153}
154
155pub fn get_gcc_build_status(builder: &Builder<'_>, target: TargetSelection) -> GccBuildStatus {
161 if let Some(path) = try_download_gcc(builder, target) {
162 return GccBuildStatus::AlreadyBuilt(path);
163 }
164
165 static STAMP_HASH_MEMO: OnceLock<String> = OnceLock::new();
166 let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| {
167 generate_smart_stamp_hash(
168 builder,
169 &builder.config.src.join("src/gcc"),
170 builder.in_tree_gcc_info.sha().unwrap_or_default(),
171 )
172 });
173
174 builder.config.update_submodule("src/gcc");
176
177 let root = builder.src.join("src/gcc");
178 let out_dir = builder.gcc_out(target).join("build");
179 let install_dir = builder.gcc_out(target).join("install");
180
181 let stamp = BuildStamp::new(&out_dir).with_prefix("gcc").add_stamp(smart_stamp_hash);
182
183 if stamp.is_up_to_date() {
184 if stamp.stamp().is_empty() {
185 builder.info(
186 "Could not determine the GCC submodule commit hash. \
187 Assuming that an GCC rebuild is not necessary.",
188 );
189 builder.info(&format!(
190 "To force GCC to rebuild, remove the file `{}`",
191 stamp.path().display()
192 ));
193 }
194 let path = libgccjit_built_path(&install_dir);
195 if path.is_file() {
196 return GccBuildStatus::AlreadyBuilt(path);
197 } else {
198 builder.info(&format!(
199 "GCC stamp is up-to-date, but the libgccjit.so file was not found at `{}`",
200 path.display(),
201 ));
202 }
203 }
204
205 GccBuildStatus::ShouldBuild(Meta { stamp, out_dir, install_dir, root })
206}
207
208fn libgccjit_built_path(install_dir: &Path) -> PathBuf {
210 install_dir.join("lib/libgccjit.so")
211}
212
213fn build_gcc(metadata: &Meta, builder: &Builder<'_>, target: TargetSelection) {
214 if builder.build.cc_tool(target).is_like_clang()
215 || builder.build.cxx_tool(target).is_like_clang()
216 {
217 panic!(
218 "Attempting to build GCC using Clang, which is known to misbehave. Please use GCC as the host C/C++ compiler. "
219 );
220 }
221
222 let Meta { stamp: _, out_dir, install_dir, root } = metadata;
223
224 t!(fs::create_dir_all(out_dir));
225 t!(fs::create_dir_all(install_dir));
226
227 let src_dir = builder.gcc_out(target).join("src");
235 if src_dir.exists() {
236 builder.remove_dir(&src_dir);
237 }
238 builder.create_dir(&src_dir);
239 builder.cp_link_r(root, &src_dir);
240
241 command(src_dir.join("contrib/download_prerequisites")).current_dir(&src_dir).run(builder);
242 let mut configure_cmd = command(src_dir.join("configure"));
243 configure_cmd
244 .current_dir(out_dir)
245 .arg("--enable-host-shared")
246 .arg("--enable-languages=c,jit,lto")
247 .arg("--enable-checking=release")
248 .arg("--disable-bootstrap")
249 .arg("--disable-multilib")
250 .arg(format!("--prefix={}", install_dir.display()));
251
252 let cc = builder.build.cc(target).display().to_string();
253 let cc = builder
254 .build
255 .config
256 .ccache
257 .as_ref()
258 .map_or_else(|| cc.clone(), |ccache| format!("{ccache} {cc}"));
259 configure_cmd.env("CC", cc);
260
261 if let Ok(ref cxx) = builder.build.cxx(target) {
262 let cxx = cxx.display().to_string();
263 let cxx = builder
264 .build
265 .config
266 .ccache
267 .as_ref()
268 .map_or_else(|| cxx.clone(), |ccache| format!("{ccache} {cxx}"));
269 configure_cmd.env("CXX", cxx);
270 }
271 configure_cmd.run(builder);
272
273 command("make")
274 .current_dir(out_dir)
275 .arg("--silent")
276 .arg(format!("-j{}", builder.jobs()))
277 .run_capture_stdout(builder);
278 command("make").current_dir(out_dir).arg("--silent").arg("install").run_capture_stdout(builder);
279}
280
281pub fn add_cg_gcc_cargo_flags(cargo: &mut Cargo, gcc: &GccOutput) {
283 cargo.rustflag(&format!("-L{}", gcc.libgccjit.parent().unwrap().to_str().unwrap()));
285}
286
287#[cfg(not(test))]
289fn ci_gcc_root(config: &crate::Config, target: TargetSelection) -> PathBuf {
290 config.out.join(target).join("ci-gcc")
291}
292
293#[cfg(not(test))]
295fn detect_gcc_freshness(config: &crate::Config, is_git: bool) -> build_helper::git::PathFreshness {
296 use build_helper::git::PathFreshness;
297
298 if is_git {
299 config.check_path_modifications(&["src/gcc", "src/bootstrap/download-ci-gcc-stamp"])
300 } else if let Some(info) = crate::utils::channel::read_commit_info_file(&config.src) {
301 PathFreshness::LastModifiedUpstream { upstream: info.sha.trim().to_owned() }
302 } else {
303 PathFreshness::MissingUpstream
304 }
305}